Skip to content

Truly independent web browser

Tests/LibWeb: Import Sanitizer API WPT tests

Andreas Kling0c287c2dd00c
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/html5lib-basics.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/html5lib-basics.txt
new file mode 100644
index 00000000000..4216d94d00c
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/html5lib-basics.txt
@@ -0,0 +1,23 @@
+Harness status: OK
+
+Found 18 tests
+
+18 Pass
+Pass Testcase #0 with .setHTMLUnsafe("Hello!")
+Pass Testcase #0, .innerHTML matches .setHTMLUnsafe
+Pass Testcase #1 with .setHTMLUnsafe("<p>bla")
+Pass Testcase #1, .innerHTML matches .setHTMLUnsafe
+Pass Testcase #2 with .setHTMLUnsafe("<p id=abc def='123'>texty<!-- xxx -->textz")
+Pass Testcase #2, .innerHTML matches .setHTMLUnsafe
+Pass Testcase #3 with .setHTMLUnsafe("<p>Hello <b>World</b><span>!")
+Pass Testcase #3, .innerHTML matches .setHTMLUnsafe
+Pass Testcase #4 with .setHTMLUnsafe("<p>A template example.<template>Hello <b>World</b></template>!")
+Pass Testcase #4, .innerHTML matches .setHTMLUnsafe
+Pass Testcase #5 with .setHTMLUnsafe("<td>Interesting parse context.</td>")
+Pass Testcase #5, .innerHTML matches .setHTMLUnsafe
+Pass Testcase #6 with .setHTMLUnsafe("<p>A rather boring parse context.")
+Pass Testcase #6, .innerHTML matches .setHTMLUnsafe
+Pass Testcase #7 with .setHTMLUnsafe("<table><b>a</b>bb<tr><td>y")
+Pass Testcase #7, .innerHTML matches .setHTMLUnsafe
+Pass Testcase #8 with .setHTMLUnsafe("<table><div>d</div><td>")
+Pass Testcase #8, .innerHTML matches .setHTMLUnsafe
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/parsehtmlunsafe-with-trustedtypes.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/parsehtmlunsafe-with-trustedtypes.txt
new file mode 100644
index 00000000000..c6cda1a67d5
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/parsehtmlunsafe-with-trustedtypes.txt
@@ -0,0 +1,12 @@
+Harness status: OK
+
+Found 7 tests
+
+7 Fail
+Fail Document.parseHTMLUnsafe: createParserOptions can inject a sanitizer config
+Fail Document.parseHTMLUnsafe: passing TrustedHTMLParserOptions directly works
+Fail Document.parseHTMLUnsafe: createParserOptions returning null fails
+Fail Document.parseHTMLUnsafe: createParserOptions returning undefined fails
+Fail Document.parseHTMLUnsafe: createParserOptions returning 0 fails
+Fail Document.parseHTMLUnsafe: createParserOptions returning 123 fails
+Fail Document.parseHTMLUnsafe: createParserOptions returning "foo" fails
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-base-immutable.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-base-immutable.txt
new file mode 100644
index 00000000000..fde9b806f8d
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-base-immutable.txt
@@ -0,0 +1,33 @@
+Harness status: OK
+
+Found 27 tests
+
+2 Pass
+25 Fail
+Fail Modifying a Sanitizer instance does not change subsequent new Sanitizer() instances
+Fail allowElement() on new Sanitizer() does not affect subsequent instances
+Fail removeElement() on new Sanitizer() does not affect subsequent instances
+Fail replaceElementWithChildren() on new Sanitizer() does not affect subsequent instances
+Fail allowAttribute() on new Sanitizer() does not affect subsequent instances
+Fail removeAttribute() on new Sanitizer() does not affect subsequent instances
+Fail allowProcessingInstruction() on new Sanitizer() does not affect subsequent instances
+Fail removeProcessingInstruction() on new Sanitizer() does not affect subsequent instances
+Fail setComments() on new Sanitizer() does not affect subsequent instances
+Fail setDataAttributes() on new Sanitizer() does not affect subsequent instances
+Fail removeUnsafe() on new Sanitizer() does not affect subsequent instances
+Fail Mutating the object returned by sanitizer.get() does not affect the Sanitizer or default configuration
+Fail Repeated calls to sanitizer.get() return distinct object copies
+Fail Modifying a Sanitizer after removeUnsafe() does not change the built-in safe baseline configuration
+Fail Mutating config returned from baseline sanitizer does not affect subsequent removeUnsafe() calls
+Fail Modifying input configuration dictionary after new Sanitizer(config) does not affect the Sanitizer
+Fail Sanitization with Element.prototype.setHTML() does not change default base configuration
+Pass Sanitization with Document.parseHTML() does not change default base configuration
+Fail A modified Sanitizer used in setHTML() does not affect default configuration or other Sanitizers
+Fail s.get() is unchanged after Element.prototype.setHTML() when Sanitizer has unsafe allowlist entries
+Fail s.get() is unchanged after Element.prototype.setHTML() when Sanitizer has unsafe remove-list configuration
+Pass s.get() is unchanged after Document.parseHTML() when Sanitizer has unsafe entries
+Fail Sanitization with appendHTML() does not change default base configuration or mutate passed Sanitizer
+Fail Sanitization with prependHTML() does not change default base configuration or mutate passed Sanitizer
+Fail Sanitization with beforeHTML() does not change default base configuration or mutate passed Sanitizer
+Fail Sanitization with afterHTML() does not change default base configuration or mutate passed Sanitizer
+Fail Sanitization with replaceWithHTML() does not change default base configuration or mutate passed Sanitizer
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-basic-filtering.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-basic-filtering.txt
new file mode 100644
index 00000000000..52d563f6aa1
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-basic-filtering.txt
@@ -0,0 +1,22 @@
+Harness status: Error
+
+Found 16 tests
+
+6 Pass
+10 Fail
+Fail setHTML testcase text/0, "text"
+Pass setHTMLUnsafe testcase text/0, "text"
+Fail ShadowRoot.setHTML testcase text/0, "text"
+Pass ShadowRoot.setHTMLUnsafe testcase text/0, "text"
+Fail parseHTML testcase text/0, "text"
+Pass parseHTMLUnsafe testcase text/0, "text"
+Fail setHTML testcase elements/0, "<div><p>Hello <b>World!</b>"
+Pass setHTMLUnsafe testcase elements/0, "<div><p>Hello <b>World!</b>"
+Fail ShadowRoot.setHTML testcase elements/0, "<div><p>Hello <b>World!</b>"
+Pass ShadowRoot.setHTMLUnsafe testcase elements/0, "<div><p>Hello <b>World!</b>"
+Fail parseHTML testcase elements/0, "<div><p>Hello <b>World!</b>"
+Pass parseHTMLUnsafe testcase elements/0, "<div><p>Hello <b>World!</b>"
+Fail setHTML testcase elements/1, "<div><p>Hello <b>World!</b>"
+Fail setHTMLUnsafe testcase elements/1, "<div><p>Hello <b>World!</b>"
+Fail ShadowRoot.setHTML testcase elements/1, "<div><p>Hello <b>World!</b>"
+Fail ShadowRoot.setHTMLUnsafe testcase elements/1, "<div><p>Hello <b>World!</b>"
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-boolean-defaults.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-boolean-defaults.txt
new file mode 100644
index 00000000000..41e8068b714
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-boolean-defaults.txt
@@ -0,0 +1,8 @@
+Harness status: OK
+
+Found 3 tests
+
+3 Fail
+Fail comments
+Fail data attributes
+Fail javascript URLs
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-config.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-config.txt
new file mode 100644
index 00000000000..597e278e762
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-config.txt
@@ -0,0 +1,77 @@
+Harness status: OK
+
+Found 72 tests
+
+72 Fail
+Fail Sanitizer constructor without config.
+Fail Sanitizer constructor with empty config.
+Fail Sanitizer constructor with null as config.
+Fail Sanitizer constructor with undefined as config.
+Fail Sanitizer constructor with config ignore unknown values.
+Fail SanitizerConfig comments field.
+Fail SanitizerConfig dataAttributes field.
+Fail SanitizerConfig javascriptURLs field.
+Fail SanitizerConfig, normalization: elements: ["div"]
+Fail SanitizerConfig, normalization: elements: [{"name":"b"}]
+Fail SanitizerConfig, normalization: elements: [{"name":"b","namespace":null}]
+Fail SanitizerConfig, normalization: elements: [{"name":"b","namespace":""}]
+Fail SanitizerConfig, normalization: elements: [{"name":"p","namespace":"http://www.w3.org/1999/xhtml"}]
+Fail SanitizerConfig, normalization: elements: [{"name":"bla","namespace":"http://fantasy.org/namespace"}]
+Fail SanitizerConfig, normalization: removeElements: ["div"]
+Fail SanitizerConfig, normalization: removeElements: [{"name":"b"}]
+Fail SanitizerConfig, normalization: removeElements: [{"name":"b","namespace":null}]
+Fail SanitizerConfig, normalization: removeElements: [{"name":"b","namespace":""}]
+Fail SanitizerConfig, normalization: removeElements: [{"name":"p","namespace":"http://www.w3.org/1999/xhtml"}]
+Fail SanitizerConfig, normalization: removeElements: [{"name":"bla","namespace":"http://fantasy.org/namespace"}]
+Fail SanitizerConfig, normalization: replaceWithChildrenElements: ["div"]
+Fail SanitizerConfig, normalization: replaceWithChildrenElements: [{"name":"b"}]
+Fail SanitizerConfig, normalization: replaceWithChildrenElements: [{"name":"b","namespace":null}]
+Fail SanitizerConfig, normalization: replaceWithChildrenElements: [{"name":"b","namespace":""}]
+Fail SanitizerConfig, normalization: replaceWithChildrenElements: [{"name":"p","namespace":"http://www.w3.org/1999/xhtml"}]
+Fail SanitizerConfig, normalization: replaceWithChildrenElements: [{"name":"bla","namespace":"http://fantasy.org/namespace"}]
+Fail SanitizerConfig, normalization: processingInstructions: ["target-1"]
+Fail SanitizerConfig, normalization: processingInstructions: [{"target":"target-1"}]
+Fail SanitizerConfig, normalization: removeProcessingInstructions: ["target-1"]
+Fail SanitizerConfig, normalization: removeProcessingInstructions: [{"target":"target-1"}]
+Fail SanitizerConfig, normalization: attributes: ["href"]
+Fail SanitizerConfig, normalization: attributes: [{"name":"href","namespace":null}]
+Fail SanitizerConfig, normalization: attributes: [{"name":"href","namespace":""}]
+Fail SanitizerConfig, normalization: attributes: [{"name":"href","namespace":"https://www.w3.org/1999/xlink"}]
+Fail SanitizerConfig, normalization: removeAttributes: ["href"]
+Fail SanitizerConfig, normalization: removeAttributes: [{"name":"href","namespace":null}]
+Fail SanitizerConfig, normalization: removeAttributes: [{"name":"href","namespace":""}]
+Fail SanitizerConfig, normalization: removeAttributes: [{"name":"href","namespace":"https://www.w3.org/1999/xlink"}]
+Fail Test elements addition.
+Fail Test elements removal.
+Fail Test elements replacewithchildren.
+Fail Test processingInstructions addition.
+Fail Test processingInstructions removal.
+Fail Test attribute addition.
+Fail Test attribute removal.
+Fail Test attribute-per-element sets (i.e. overwrites).
+Fail Test removeAttribute-per-element sets (i.e. overwrites).
+Fail Both elements and removeElements should not be allowed.
+Fail Both attributes and removeAttributes should not be allowed.
+Fail Both processingInstructions and removeProcessingInstructions should not be allowed.
+Fail config[elements] should not allow duplicates
+Fail config[removeElements] should not allow duplicates
+Fail config[replaceWithChildrenElements] should not allow duplicates
+Fail config[attributes] should not allow duplicates
+Fail config[removeAttributes] should not allow duplicates
+Fail config[processingInstructions] should not allow duplicate targets
+Fail config[removeProcessingInstructions] should not allow duplicate targets
+Fail config[replaceWithChildrenElements] should not allow non-replaceable elements
+Fail config[elements] and config[replaceWithChildrenElements] should not intersect
+Fail config[removeElements] and config[replaceWithChildrenElements] should not intersect
+Fail Duplicates in element[attributes] with config[attributes] should not be allowed.
+Fail Duplicates in element[removeAttributes] with config[attributes] should not be allowed.
+Fail config[attributes] and element[attributes] should not intersect.
+Fail element[removeAttributes] should be a subset of config[attributes]
+Fail element[attributes] with a data attribute must not co-exist with config[dataAttributes] set to true.
+Fail config[attributes] with a data attribute must not co-exist with config[dataAttributes] set to true.
+Fail element[attributes] and element[removeAttributes] should not both exist with config[removeAttributes].
+Fail Duplicates in element[attributes] with config[removeAttributes] should not be allowed.
+Fail Duplicates in element[removeAttributes] with config[removeAttributes] should not be allowed.
+Fail config[removeAttributes] and element[attributes] should not intersect.
+Fail config[removeAttributes] and element[removeAttributes] should not intersect.
+Fail Can not use config[dataAttributes] and config[removeAttributes] together.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-custom-elements-constructor.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-custom-elements-constructor.txt
new file mode 100644
index 00000000000..2f260a7666e
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-custom-elements-constructor.txt
@@ -0,0 +1,20 @@
+Harness status: OK
+
+Found 14 tests
+
+1 Pass
+13 Fail
+Fail setHTML blocks CE constructor when element is dropped by explicit sanitizer config (removeElements)
+Fail setHTML blocks CE constructor in scoped registry when element is dropped by explicit sanitizer config (removeElements)
+Fail setHTML blocks CE constructor when element is dropped by explicit sanitizer config (allowElements)
+Fail setHTML blocks CE constructor in scoped registry when element is dropped by explicit sanitizer config (allowElements)
+Fail setHTML blocks CE constructor when element is dropped by explicit sanitizer config (replaceWithChildrenElements)
+Fail setHTML blocks CE constructor in scoped registry when element is dropped by explicit sanitizer config (replaceWithChildrenElements)
+Fail setHTMLUnsafe blocks CE constructor when element is dropped by explicit sanitizer config (removeElements)
+Fail setHTMLUnsafe blocks CE constructor in scoped registry when element is dropped by explicit sanitizer config (removeElements)
+Fail setHTMLUnsafe blocks CE constructor when element is dropped by explicit sanitizer config (allowElements)
+Fail setHTMLUnsafe blocks CE constructor in scoped registry when element is dropped by explicit sanitizer config (allowElements)
+Fail setHTMLUnsafe blocks CE constructor when element is dropped by explicit sanitizer config (replaceWithChildrenElements)
+Fail setHTMLUnsafe blocks CE constructor in scoped registry when element is dropped by explicit sanitizer config (replaceWithChildrenElements)
+Fail setHTML constructs an allowed CE from the scoped registry
+Pass setHTMLUnsafe constructs an allowed CE from the scoped registry
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-custom-elements-is.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-custom-elements-is.txt
new file mode 100644
index 00000000000..533408355be
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-custom-elements-is.txt
@@ -0,0 +1,13 @@
+Harness status: OK
+
+Found 8 tests
+
+8 Fail
+Fail The is= attribute is removed by the default sanitizer config.
+Fail The is= attribute is removed by the global removeAttributes
+Fail The is= attribute is removed by the local removeAttributes
+Fail The is= attribute is removed by the local missing attributes
+Fail The is= attribute is kept when allowed with an empty config.
+Fail The is= attribute is kept when allowed by global attributes.
+Fail The is= attribute is kept when allowed by global removeAttributes.
+Fail The is= attribute is kept when allowed by local attributes.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-default-config.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-default-config.txt
new file mode 100644
index 00000000000..8b0c615560a
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-default-config.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Fail
+Fail Get the expected default config
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-duplicate-html-body.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-duplicate-html-body.txt
new file mode 100644
index 00000000000..d84b48f86c2
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-duplicate-html-body.txt
@@ -0,0 +1,17 @@
+Harness status: OK
+
+Found 12 tests
+
+12 Fail
+Fail Document.parseHTML testcase 0, "<body><body onload="alert(1)" onclick="alert(2)" class="safe-body" data-test="val"></body>"
+Fail Document.parseHTML testcase 1, "<body id="initial" class="initial"><body id="duplicate" class="duplicate" dir="rtl" onclick="alert(1)"></body>"
+Fail Document.parseHTML testcase 2, "<html lang="en" id="root"><html id="duplicate" dir="rtl" onclick="alert(1)"><body></body>"
+Fail Document.parseHTML testcase 3, "<body><body class="allowed" title="forbidden"></body>"
+Fail Document.parseHTML testcase 4, "<html lang="en" dir="ltr" class="html-cls"><body id="main" class="body-cls" dir="ltr"></body>"
+Fail Document.parseHTML testcase 5, "<html><body><body class="body-cls" data-foo="bar"></body>"
+Fail Document.parseHTMLUnsafe testcase 0, "<body><body data-bad="strip-me" data-good="keep-me"></body>"
+Fail Document.parseHTMLUnsafe testcase 1, "<html data-bad-html="1" data-good-html="2"><body data-bad-body="3" data-good-body="4"></body>"
+Fail Document.parseHTMLUnsafe testcase 2, "<html><body><html data-dup-bad-html="1" data-dup-good-html="2"><body data-dup-bad-body="3" data-dup-good-body="4"></body>"
+Fail Document.parseHTMLUnsafe testcase 3, "<html title="html-title"><body title="body-title"><div title="div-title"></div></body>"
+Fail Fragment setHTML testcase 0, "<body id="test-body" onclick="alert(1)" class="safe-body"></body>"
+Fail Fragment setHTML testcase 1, "<body id="first" class="first"><body id="second" dir="rtl" onclick="alert(1)"></body>"
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-get.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-get.txt
new file mode 100644
index 00000000000..bc80fc30214
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-get.txt
@@ -0,0 +1,14 @@
+Harness status: OK
+
+Found 9 tests
+
+9 Fail
+Fail Sorting of attributes
+Fail Sorting of removeAttributes
+Fail Sorting of elements
+Fail Sorting of removeElements
+Fail Sorting of replaceWithChildrenElements
+Fail Sorting of element's attributes
+Fail Sorting of element's removeAttributes
+Fail Sorting of processingInstructions
+Fail Sorting of removeProcessingInstructions
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-in-adoption-agency.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-in-adoption-agency.txt
new file mode 100644
index 00000000000..11332c61830
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-in-adoption-agency.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Fail
+Fail Sanitizer Adoption Agency Algorithm testcases
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-in-noahs-ark.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-in-noahs-ark.txt
new file mode 100644
index 00000000000..14d09bba1f2
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-in-noahs-ark.txt
@@ -0,0 +1,27 @@
+Harness status: OK
+
+Found 22 tests
+
+22 Fail
+Fail Testcase #0, "<p><b title=1>1<b title=2>2<b title=3>3<b title=4>4</p>x", config: "{ "removeAttributes": ["title"] }", with setHTML()
+Fail Testcase #0, "<p><b title=1>1<b title=2>2<b title=3>3<b title=4>4</p>x", config: "{ "removeAttributes": ["title"] }", with setHTMLUnsafe()
+Fail Testcase #0, "<p><b title=1>1<b title=2>2<b title=3>3<b title=4>4</p>x", config: "{ "removeAttributes": ["title"] }", with Document.parseHTML()
+Fail Testcase #1, "<p><b title=1>1<b title=1>2<b title=1>3<b title=1>4</p>x", config: "{ "removeAttributes": ["title"] }", with setHTML()
+Fail Testcase #1, "<p><b title=1>1<b title=1>2<b title=1>3<b title=1>4</p>x", config: "{ "removeAttributes": ["title"] }", with setHTMLUnsafe()
+Fail Testcase #1, "<p><b title=1>1<b title=1>2<b title=1>3<b title=1>4</p>x", config: "{ "removeAttributes": ["title"] }", with Document.parseHTML()
+Fail Testcase #2, "<p><b>1<b>2<b>3<b title=1>4</p>x", config: "{ "removeAttributes": ["title"] }", with setHTML()
+Fail Testcase #2, "<p><b>1<b>2<b>3<b title=1>4</p>x", config: "{ "removeAttributes": ["title"] }", with setHTMLUnsafe()
+Fail Testcase #2, "<p><b>1<b>2<b>3<b title=1>4</p>x", config: "{ "removeAttributes": ["title"] }", with Document.parseHTML()
+Fail Testcase #3, "<p><b title=1>1<b>2<b>3<b>4</p>x", config: "{ "removeAttributes": ["title"] }", with setHTML()
+Fail Testcase #3, "<p><b title=1>1<b>2<b>3<b>4</p>x", config: "{ "removeAttributes": ["title"] }", with setHTMLUnsafe()
+Fail Testcase #3, "<p><b title=1>1<b>2<b>3<b>4</p>x", config: "{ "removeAttributes": ["title"] }", with Document.parseHTML()
+Fail Testcase #4, "<p><b class=c title=1>1<b class=c title=2>2<b class=c title=3>3<b class=c title=4>4</p>x", config: "{ "removeAttributes": ["title"] }", with setHTML()
+Fail Testcase #4, "<p><b class=c title=1>1<b class=c title=2>2<b class=c title=3>3<b class=c title=4>4</p>x", config: "{ "removeAttributes": ["title"] }", with setHTMLUnsafe()
+Fail Testcase #4, "<p><b class=c title=1>1<b class=c title=2>2<b class=c title=3>3<b class=c title=4>4</p>x", config: "{ "removeAttributes": ["title"] }", with Document.parseHTML()
+Fail Testcase #5, "<p><b class=c title=1>1<b class=c title=2>2<b class=c title=3>3<b class=c title=4>4</p>x", config: "{ "attributes": ["class"] }", with setHTML()
+Fail Testcase #5, "<p><b class=c title=1>1<b class=c title=2>2<b class=c title=3>3<b class=c title=4>4</p>x", config: "{ "attributes": ["class"] }", with setHTMLUnsafe()
+Fail Testcase #5, "<p><b class=c title=1>1<b class=c title=2>2<b class=c title=3>3<b class=c title=4>4</p>x", config: "{ "attributes": ["class"] }", with Document.parseHTML()
+Fail Testcase #6, "<p><b onclick=1>1<b onclick=2>2<b onclick=3>3<b onclick=4>4</p>x", config: "undefined", with setHTML()
+Fail Testcase #6, "<p><b onclick=1>1<b onclick=2>2<b onclick=3>3<b onclick=4>4</p>x", config: "undefined", with Document.parseHTML()
+Fail Testcase #7, "<p><b onclick=1>1<b onclick=1>2<b onclick=1>3<b onclick=1>4</p>x", config: "undefined", with setHTML()
+Fail Testcase #7, "<p><b onclick=1>1<b onclick=1>2<b onclick=1>3<b onclick=1>4</p>x", config: "undefined", with Document.parseHTML()
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-javascript-url.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-javascript-url.txt
new file mode 100644
index 00000000000..6055c864758
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-javascript-url.txt
@@ -0,0 +1,3 @@
+Harness status: Error
+
+Found 0 tests
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-modifiers.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-modifiers.txt
new file mode 100644
index 00000000000..2e21f6d2233
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-modifiers.txt
@@ -0,0 +1,27 @@
+Harness status: OK
+
+Found 22 tests
+
+22 Fail
+Fail sanitizer.allowAttribute() with global attributes
+Fail sanitizer.allowAttribute() with global removeAttributes
+Fail sanitizer.allowAttribute() with global attributes and elements
+Fail sanitizer.allowAttribute() with global removeAttributes and element's attributes
+Fail sanitizer.allowAttribute() with global removeAttributes and element's removeAttributes
+Fail sanitizer.removeAttribute() with global attributes
+Fail sanitizer.removeAttribute() with global removeAttributes
+Fail sanitizer.removeAttribute() with global attributes and elements
+Fail sanitizer.removeAttribute() with global removeAttributes and element's attributes
+Fail sanitizer.removeAttribute() with global removeAttributes and element's removeAttributes
+Fail sanitizer.removeElement() with global elements
+Fail sanitizer.removeElement() with global removeElements
+Fail sanitizer.replaceElementWithChildren() with global elements
+Fail sanitizer.replaceElementWithChildren() with global removeElements
+Fail sanitizer.allowElement() with global elements
+Fail sanitizer.allowElement() with global removeElements
+Fail sanitizer.allowElement() with global elements and attributes
+Fail sanitizer.allowElement() with global elements and removeAttributes
+Fail sanitizer.replaceElementWithChildren() does not allow non-replaceable elements.
+Fail sanitizer.setJavascriptURLs()
+Fail sanitizer.setComments()
+Fail sanitizer.setDataAttributes()
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-parseHTML.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-parseHTML.txt
new file mode 100644
index 00000000000..f50c0ec5f36
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-parseHTML.txt
@@ -0,0 +1,57 @@
+Harness status: OK
+
+Found 49 tests
+
+14 Pass
+35 Fail
+Fail parseHTML testcase 0, "text"
+Fail parseHTML testcase 1, "<div>text"
+Fail parseHTML testcase 2, "<div>text"
+Fail parseHTML testcase 3, "<div>text"
+Pass parseHTML testcase 4, "<html onload="3 + 3"><div>a"
+Fail parseHTML testcase 5, "<body><body onload="alert(1)">Hello"
+Fail parseHTML testcase 6, "<!-- a --><html><body>x<!-- b --></body></html><!-- c -->"
+Fail parseHTML testcase 7, "<?a b?><html><body>x<?c d?></body></html><?e f?>"
+Fail parseHTML testcase 8, "x<p>y"
+Fail parseHTML testcase 9, "<noscript><p>x</noscript>y"
+Fail parseHTML testcase 10, "<noscript><p>x</noscript>y"
+Fail parseHTML testcase 11, "<script>hello"
+Fail parseHTML testcase 12, "<html onload="2+2"><body onload="3+3"><div>hello"
+Fail parseHTML testcase 13, "<div data-xyz="1" id="2" title="3">"
+Fail parseHTML testcase 14, "<div>a<!-- xx -->b"
+Pass parseHTML testcase 15, "<html onload="2 + 2"><div>a"
+Fail parseHTML testcase 16, "<br id="document">"
+Fail parseHTML testcase 17, "<br id="document">"
+Fail parseHTML testcase 18, "<p onclick="alert(document.cookie)">Click handler!</p>"
+Fail parseHTML testcase 19, "<p onclick="alert(document.cookie)">Click handler!</p>"
+Fail parseHTML testcase 20, "<noscript><p>x</noscript>y"
+Pass parseHTMLUnsafe testcase 0, "text"
+Fail parseHTMLUnsafe testcase 1, "<div>text"
+Fail parseHTMLUnsafe testcase 2, "<div>text"
+Fail parseHTMLUnsafe testcase 3, "<div>text"
+Fail parseHTMLUnsafe testcase 4, "<html onload="3 + 3"><div>a"
+Fail parseHTMLUnsafe testcase 5, "<body><body onload="alert(1)">Hello"
+Fail parseHTMLUnsafe testcase 6, "<!-- a --><html><body>x<!-- b --></body></html><!-- c -->"
+Fail parseHTMLUnsafe testcase 7, "<?a b?><html><body>x<?c d?></body></html><?e f?>"
+Fail parseHTMLUnsafe testcase 8, "x<p>y"
+Pass parseHTMLUnsafe testcase 9, "<noscript><p>x</noscript>y"
+Pass parseHTMLUnsafe testcase 10, "<noscript><p>x</noscript>y"
+Pass parseHTMLUnsafe testcase 11, "<script>hello"
+Pass parseHTMLUnsafe testcase 12, "<html onload="2+2"><body onload="3+3"><div>hello"
+Fail parseHTMLUnsafe testcase 13, "<div data-xyz="1" id="2" title="3">"
+Pass parseHTMLUnsafe testcase 14, "<div>a<!-- xx -->b"
+Fail parseHTMLUnsafe testcase 15, "<html onload="2 + 2"><div>a"
+Pass parseHTMLUnsafe testcase 16, "<div>a<!-- xx -->b"
+Pass parseHTMLUnsafe testcase 17, "<!-- 1 --><html><body>x<!-- 2 --></body></html><!-- 3 -->"
+Fail parseHTMLUnsafe testcase 18, "a<template>x</template>b"
+Pass parseHTMLUnsafe testcase 19, "<noscript><p>x</noscript>y"
+Fail parseHTMLUnsafe testcase 20, "<head><meta></head><body>x"
+Fail parseHTMLUnsafe testcase 21, "<head></head><body>x<p>y"
+Fail parseHTMLUnsafe testcase 22, "<head></head><meta><body>x"
+Fail parseHTMLUnsafe testcase 23, "<div></div><frameset>"
+Pass parseHTMLUnsafe testcase 24, "<div></div><frameset>"
+Pass parseHTMLUnsafe() without options keeps comments
+Pass parseHTMLUnsafe full document testcase 0, "<!DOCTYPE html>
+text"
+Fail parseHTML full document testcase 0, "<!DOCTYPE html>
+text"
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-processing-instructions.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-processing-instructions.txt
new file mode 100644
index 00000000000..7a28331fdee
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-processing-instructions.txt
@@ -0,0 +1,68 @@
+Harness status: OK
+
+Found 63 tests
+
+63 Fail
+Fail setHTMLUnsafe testcase agnostic/0, "<?target data?>"
+Fail ShadowRoot.setHTMLUnsafe testcase agnostic/0, "<?target data?>"
+Fail setHTML testcase agnostic/0, "<?target data?>"
+Fail ShadowRoot.setHTML testcase agnostic/0, "<?target data?>"
+Fail parseHTML testcase agnostic/0, "<?target data?>"
+Fail parseHTMLUnsafe testcase agnostic/0, "<?target data?>"
+Fail setHTMLUnsafe testcase agnostic/1, "<?target data?>"
+Fail ShadowRoot.setHTMLUnsafe testcase agnostic/1, "<?target data?>"
+Fail setHTML testcase agnostic/1, "<?target data?>"
+Fail ShadowRoot.setHTML testcase agnostic/1, "<?target data?>"
+Fail parseHTML testcase agnostic/1, "<?target data?>"
+Fail parseHTMLUnsafe testcase agnostic/1, "<?target data?>"
+Fail setHTMLUnsafe testcase agnostic/2, "<?Target data?>"
+Fail ShadowRoot.setHTMLUnsafe testcase agnostic/2, "<?Target data?>"
+Fail setHTML testcase agnostic/2, "<?Target data?>"
+Fail ShadowRoot.setHTML testcase agnostic/2, "<?Target data?>"
+Fail parseHTML testcase agnostic/2, "<?Target data?>"
+Fail parseHTMLUnsafe testcase agnostic/2, "<?Target data?>"
+Fail setHTMLUnsafe testcase agnostic/3, "<?target data?>"
+Fail ShadowRoot.setHTMLUnsafe testcase agnostic/3, "<?target data?>"
+Fail setHTML testcase agnostic/3, "<?target data?>"
+Fail ShadowRoot.setHTML testcase agnostic/3, "<?target data?>"
+Fail parseHTML testcase agnostic/3, "<?target data?>"
+Fail parseHTMLUnsafe testcase agnostic/3, "<?target data?>"
+Fail setHTMLUnsafe testcase agnostic/4, "<?target-1 data?><?target-2 data?>"
+Fail ShadowRoot.setHTMLUnsafe testcase agnostic/4, "<?target-1 data?><?target-2 data?>"
+Fail setHTML testcase agnostic/4, "<?target-1 data?><?target-2 data?>"
+Fail ShadowRoot.setHTML testcase agnostic/4, "<?target-1 data?><?target-2 data?>"
+Fail parseHTML testcase agnostic/4, "<?target-1 data?><?target-2 data?>"
+Fail parseHTMLUnsafe testcase agnostic/4, "<?target-1 data?><?target-2 data?>"
+Fail setHTMLUnsafe testcase agnostic/5, "<?target-1 data?><?target-2 data?>"
+Fail ShadowRoot.setHTMLUnsafe testcase agnostic/5, "<?target-1 data?><?target-2 data?>"
+Fail setHTML testcase agnostic/5, "<?target-1 data?><?target-2 data?>"
+Fail ShadowRoot.setHTML testcase agnostic/5, "<?target-1 data?><?target-2 data?>"
+Fail parseHTML testcase agnostic/5, "<?target-1 data?><?target-2 data?>"
+Fail parseHTMLUnsafe testcase agnostic/5, "<?target-1 data?><?target-2 data?>"
+Fail setHTMLUnsafe testcase agnostic/6, "<div><?target data?></div>"
+Fail ShadowRoot.setHTMLUnsafe testcase agnostic/6, "<div><?target data?></div>"
+Fail setHTML testcase agnostic/6, "<div><?target data?></div>"
+Fail ShadowRoot.setHTML testcase agnostic/6, "<div><?target data?></div>"
+Fail parseHTML testcase agnostic/6, "<div><?target data?></div>"
+Fail parseHTMLUnsafe testcase agnostic/6, "<div><?target data?></div>"
+Fail setHTMLUnsafe testcase agnostic/7, "<div><?unlisted-target data?></div>"
+Fail ShadowRoot.setHTMLUnsafe testcase agnostic/7, "<div><?unlisted-target data?></div>"
+Fail setHTML testcase agnostic/7, "<div><?unlisted-target data?></div>"
+Fail ShadowRoot.setHTML testcase agnostic/7, "<div><?unlisted-target data?></div>"
+Fail parseHTML testcase agnostic/7, "<div><?unlisted-target data?></div>"
+Fail parseHTMLUnsafe testcase agnostic/7, "<div><?unlisted-target data?></div>"
+Fail setHTMLUnsafe testcase unsafe-only/0, "<?target data?>"
+Fail ShadowRoot.setHTMLUnsafe testcase unsafe-only/0, "<?target data?>"
+Fail parseHTMLUnsafe testcase unsafe-only/0, "<?target data?>"
+Fail setHTMLUnsafe testcase unsafe-only/1, "<?target data?>"
+Fail ShadowRoot.setHTMLUnsafe testcase unsafe-only/1, "<?target data?>"
+Fail parseHTMLUnsafe testcase unsafe-only/1, "<?target data?>"
+Fail setHTMLUnsafe testcase unsafe-only/2, "<div><?target data?></div>"
+Fail ShadowRoot.setHTMLUnsafe testcase unsafe-only/2, "<div><?target data?></div>"
+Fail parseHTMLUnsafe testcase unsafe-only/2, "<div><?target data?></div>"
+Fail setHTMLUnsafe testcase unsafe-only/3, "<div><?target data?></div>"
+Fail ShadowRoot.setHTMLUnsafe testcase unsafe-only/3, "<div><?target data?></div>"
+Fail parseHTMLUnsafe testcase unsafe-only/3, "<div><?target data?></div>"
+Fail setHTML testcase safe-only/0, "<div><?target data?></div>"
+Fail ShadowRoot.setHTML testcase safe-only/0, "<div><?target data?></div>"
+Fail parseHTML testcase safe-only/0, "<div><?target data?></div>"
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-removeUnsafe.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-removeUnsafe.txt
new file mode 100644
index 00000000000..c9715f29c8b
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-removeUnsafe.txt
@@ -0,0 +1,13 @@
+Harness status: OK
+
+Found 8 tests
+
+8 Fail
+Fail removeUnsafe removes the right elements and attributes
+Fail removeUnsafe with default config
+Fail removeUnsafe sets javascriptURLs to false
+Fail Baseline remove list is namespace specific #0: {"name":"script","namespace":"http://www.w3.org/1999/xhtml"}
+Fail Baseline remove list is namespace specific #1: {"name":"script","namespace":"http://www.w3.org/2000/svg"}
+Fail Baseline remove list is namespace specific #2: {"name":"use","namespace":"http://www.w3.org/2000/svg"}
+Fail Baseline remove list is namespace specific #3: {"name":"use","namespace":"http://www.w3.org/1999/xhtml"}
+Fail Baseline remove list is namespace specific #4: {"name":"script","namespace":"http://www.w3.org/1998/Math/MathML"}
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-script-tokenizer.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-script-tokenizer.txt
new file mode 100644
index 00000000000..3fec0aca53c
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sanitizer-script-tokenizer.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Fail
+Fail Sanitizer script and raw text tokenizer testcases from sub.dat
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-custom-element-reactions.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-custom-element-reactions.txt
new file mode 100644
index 00000000000..4670436034e
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-custom-element-reactions.txt
@@ -0,0 +1,14 @@
+Harness status: OK
+
+Found 8 tests
+
+4 Pass
+4 Fail
+Fail Element.setHTML with a sanitizer runs custom element reactions before returning
+Fail Element.setHTML with a sanitizer runs disconnectedCallback for the replaced children before returning
+Pass Element.setHTMLUnsafe with a sanitizer runs custom element reactions before returning
+Pass Element.setHTMLUnsafe with a sanitizer runs disconnectedCallback for the replaced children before returning
+Fail ShadowRoot.setHTML with a sanitizer runs custom element reactions before returning
+Fail ShadowRoot.setHTML with a sanitizer runs disconnectedCallback for the replaced children before returning
+Pass ShadowRoot.setHTMLUnsafe with a sanitizer runs custom element reactions before returning
+Pass ShadowRoot.setHTMLUnsafe with a sanitizer runs disconnectedCallback for the replaced children before returning
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-form-owner.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-form-owner.txt
new file mode 100644
index 00000000000..4bd978f15d6
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-form-owner.txt
@@ -0,0 +1,10 @@
+Harness status: OK
+
+Found 4 tests
+
+2 Pass
+2 Fail
+Pass Without a sanitizer, the input's form owner is the parsed form
+Fail With the form replaced with its children, the input has no form owner
+Pass parseHTMLUnsafe(): without a sanitizer, the input's form owner is the parsed form
+Fail parseHTMLUnsafe(): with the form replaced with its children, the input has no form owner
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-noscript.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-noscript.txt
new file mode 100644
index 00000000000..c7d8322193f
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-noscript.txt
@@ -0,0 +1,12 @@
+Harness status: OK
+
+Found 6 tests
+
+4 Pass
+2 Fail
+Pass setHTMLUnsafe() parses noscript as raw text (no options)
+Pass setHTMLUnsafe() parses noscript as raw text (empty options)
+Pass setHTMLUnsafe() parses noscript as raw text (sanitizer: undefined)
+Pass setHTMLUnsafe() parses noscript as raw text (empty sanitizer config)
+Fail setHTML() parses noscript as raw text when noscript is allowed
+Fail setHTML() removes noscript with its raw text content by default
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-replace-with-children.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-replace-with-children.txt
new file mode 100644
index 00000000000..37760fdc868
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-replace-with-children.txt
@@ -0,0 +1,11 @@
+Harness status: OK
+
+Found 6 tests
+
+6 Fail
+Fail setHTML: children of a replaced element get the target's node document
+Fail setHTML: a declarative shadow root inside a replaced element is not attached
+Fail setHTMLUnsafe: children of a replaced element get the target's node document
+Fail setHTMLUnsafe: a declarative shadow root inside a replaced element is not attached
+Fail setHTMLUnsafe: a custom element inside a replaced element is constructed and connected to the target
+Fail setHTMLUnsafe: a custom element inside a foster-parented replaced element is connected before the table
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-safety.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-safety.txt
new file mode 100644
index 00000000000..23f79868c71
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-safety.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Fail
+Fail wrapper
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-scoped-custom-element-registry.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-scoped-custom-element-registry.txt
new file mode 100644
index 00000000000..4ab1f860257
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-scoped-custom-element-registry.txt
@@ -0,0 +1,15 @@
+Harness status: OK
+
+Found 9 tests
+
+4 Pass
+5 Fail
+Fail setHTML uses the target's scoped custom element registry
+Fail setHTML with replaceWithChildrenElements preserves the scoped custom element registry for children
+Fail setHTML on a shadow root uses the shadow root's registry, not the host's
+Fail setHTML constructs nested custom elements with the scoped registry
+Pass setHTMLUnsafe uses the target's scoped custom element registry
+Pass setHTMLUnsafe with a sanitizer uses the target's scoped custom element registry
+Fail setHTMLUnsafe with replaceWithChildrenElements preserves the scoped custom element registry for children
+Pass setHTMLUnsafe on a shadow root uses the shadow root's registry, not the host's
+Pass setHTMLUnsafe constructs nested custom elements with the scoped registry
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-tree-construction.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-tree-construction.txt
new file mode 100644
index 00000000000..9c79f0e5995
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-tree-construction.txt
@@ -0,0 +1,11 @@
+Harness status: OK
+
+Found 6 tests
+
+6 Fail
+Fail wrapper
+Fail Non-string input: empty object.
+Fail Non-string input: number.
+Fail Non-string input: octal number.
+Fail Non-string input: expression.
+Fail Non-string input: undefined.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-with-custom-elements.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-with-custom-elements.txt
new file mode 100644
index 00000000000..c27eabfc481
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-with-custom-elements.txt
@@ -0,0 +1,30 @@
+Harness status: OK
+
+Found 24 tests
+
+2 Pass
+22 Fail
+Fail Custom element that is removed during sanitization.
+Fail Custom element that is allowed.
+Fail Custom element that is allowed, on a disconnected element.
+Pass Custom element on a disconnected element, setHTMLUnsafe().
+Fail Custom element inside an element that is replaced with its children, on a disconnected element, setHTML().
+Fail Custom element inside nested elements that are replaced with their children, setHTML().
+Fail Custom element inside an element that is replaced with its children uses the target's scoped registry, setHTML().
+Fail Custom element inside an element that is replaced with its children, on a disconnected element, setHTMLUnsafe().
+Fail Custom element inside nested elements that are replaced with their children, setHTMLUnsafe().
+Fail Custom element inside an element that is replaced with its children uses the target's scoped registry, setHTMLUnsafe().
+Fail Custom element in a declarative shadow root on a removed host is not constructed.
+Fail Custom element inside a removed element is not constructed.
+Fail attributeChangedCallback only fires for attributes the sanitizer keeps.
+Fail Custom element via is-attribute, where is attribute is not default-allowed.
+Fail Custom element via is-attribute, where is attribute is removed.
+Fail Custom element via is-attribute, where is attribute is removed but the custom element would have been allowed.
+Fail Custom element with an is-attribute, where the is=-attribute is blocked.
+Fail Custom element via is-attribute, where is attribute is allowed, but the element is not.
+Fail Custom element via is-attribute, where is attribute is allowed, but the element is removed.
+Fail Custom element via is-attribute, where is attribute is allowed, but the element is replaced.
+Fail Custom element via is-attribute with unsafe, where is attribute is not default-allowed.
+Fail Sanity check, that is= processing still works when allowed.
+Fail Custom element via is-attribute on script element, where is attribute is not allowed.
+Pass Custom element via is-attribute on html element, where is attribute is not default-allowed.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-with-declarative-shadow-root.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-with-declarative-shadow-root.txt
new file mode 100644
index 00000000000..36327452d68
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-with-declarative-shadow-root.txt
@@ -0,0 +1,20 @@
+Harness status: OK
+
+Found 14 tests
+
+1 Pass
+13 Fail
+Fail template with shadowrootmode should be removed by safe default
+Pass template with shadowrootmode should not be removed in unsafe mode
+Fail template with shadowrootmode should not be processed when <template> is forbidden
+Fail template with shadowrootmode should be processed as a normal template when the shadowRootMode attribute is forbidden
+Fail template with shadowrootmode replaced with its children has no children in the tree
+Fail declarative shadow root on a host replaced with its children is not attached to the parent; the template is kept as a regular template
+Fail declarative shadow root on a removed host is dropped with it
+Fail template with shadowrootmode in removeElements does not attach a shadow root (setHTMLUnsafe)
+Fail shadowRoot.delegatesFocus does not propagate to the shadow root when shadowrootdelegatesfocus is removed by sanitizer
+Fail shadowRoot.serializable does not propagate to the shadow root when shadowrootserializable is removed by sanitizer
+Fail shadowRoot.clonable does not propagate to the shadow root when shadowrootclonable is removed by sanitizer
+Fail shadowRoot.referenceTarget does not propagate to the shadow root when shadowrootreferencetarget is removed by sanitizer
+Fail shadowRoot.customElementRegistry does not propagate to the shadow root when shadowrootcustomelementregistry is removed by sanitizer
+Fail shadowRoot.adoptedStyleSheets does not propagate to the shadow root when shadowrootadoptedstylesheets is removed by sanitizer
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-with-trustedhtml-createParserOptions.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-with-trustedhtml-createParserOptions.txt
new file mode 100644
index 00000000000..082abdb7901
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-with-trustedhtml-createParserOptions.txt
@@ -0,0 +1,172 @@
+Harness status: OK
+
+Found 166 tests
+
+32 Pass
+134 Fail
+Fail ShadowRoot.setHTMLUnsafe: sending TrustedHTML applies sanitizer in default policy createParserOptions
+Pass ShadowRoot.setHTMLUnsafe: sending TrustedHTML does not call default policy createHTML
+Fail ShadowRoot.setHTMLUnsafe: exception in default createParserOptions rethrows when TrustedHTML is passed
+Fail ShadowRoot.setHTMLUnsafe: default createParserOptions returning null throws TypeError when TrustedHTML is passed
+Fail ShadowRoot.setHTMLUnsafe: default createParserOptions returning undefined throws TypeError when TrustedHTML is passed
+Fail ShadowRoot.appendHTMLUnsafe: sending TrustedHTML applies sanitizer in default policy createParserOptions
+Fail ShadowRoot.appendHTMLUnsafe: sending TrustedHTML does not call default policy createHTML
+Fail ShadowRoot.appendHTMLUnsafe: exception in default createParserOptions rethrows when TrustedHTML is passed
+Pass ShadowRoot.appendHTMLUnsafe: default createParserOptions returning null throws TypeError when TrustedHTML is passed
+Pass ShadowRoot.appendHTMLUnsafe: default createParserOptions returning undefined throws TypeError when TrustedHTML is passed
+Fail ShadowRoot.prependHTMLUnsafe: sending TrustedHTML applies sanitizer in default policy createParserOptions
+Fail ShadowRoot.prependHTMLUnsafe: sending TrustedHTML does not call default policy createHTML
+Fail ShadowRoot.prependHTMLUnsafe: exception in default createParserOptions rethrows when TrustedHTML is passed
+Pass ShadowRoot.prependHTMLUnsafe: default createParserOptions returning null throws TypeError when TrustedHTML is passed
+Pass ShadowRoot.prependHTMLUnsafe: default createParserOptions returning undefined throws TypeError when TrustedHTML is passed
+Fail ShadowRoot.innerHTML: sending TrustedHTML applies sanitizer in default policy createParserOptions
+Pass ShadowRoot.innerHTML: sending TrustedHTML does not call default policy createHTML
+Fail ShadowRoot.innerHTML: exception in default createParserOptions rethrows when TrustedHTML is passed
+Fail ShadowRoot.innerHTML: default createParserOptions returning null throws TypeError when TrustedHTML is passed
+Fail ShadowRoot.innerHTML: default createParserOptions returning undefined throws TypeError when TrustedHTML is passed
+Fail ShadowRoot.setHTMLUnsafe: default policy createParserOptions sanitizer overrides caller sanitizer dictionary with TrustedHTML
+Fail ShadowRoot.setHTMLUnsafe: caller-provided sanitizer dictionary is applied with TrustedHTML when default policy passes it through
+Fail ShadowRoot.setHTMLUnsafe: caller-provided TrustedHTMLParserOptions sanitizer is applied with TrustedHTML while default policy is bypassed
+Pass ShadowRoot.setHTMLUnsafe: default policy createParserOptions can disable runScripts
+Fail ShadowRoot.setHTMLUnsafe: default policy createParserOptions can enable runScripts
+Fail ShadowRoot.setHTMLUnsafe: TrustedHTML runs scripts when caller requests runScripts and default policy allows it
+Fail ShadowRoot.appendHTMLUnsafe: default policy createParserOptions sanitizer overrides caller sanitizer dictionary with TrustedHTML
+Fail ShadowRoot.appendHTMLUnsafe: caller-provided sanitizer dictionary is applied with TrustedHTML when default policy passes it through
+Fail ShadowRoot.appendHTMLUnsafe: caller-provided TrustedHTMLParserOptions sanitizer is applied with TrustedHTML while default policy is bypassed
+Fail ShadowRoot.appendHTMLUnsafe: default policy createParserOptions can disable runScripts
+Fail ShadowRoot.appendHTMLUnsafe: default policy createParserOptions can enable runScripts
+Fail ShadowRoot.appendHTMLUnsafe: TrustedHTML runs scripts when caller requests runScripts and default policy allows it
+Fail ShadowRoot.prependHTMLUnsafe: default policy createParserOptions sanitizer overrides caller sanitizer dictionary with TrustedHTML
+Fail ShadowRoot.prependHTMLUnsafe: caller-provided sanitizer dictionary is applied with TrustedHTML when default policy passes it through
+Fail ShadowRoot.prependHTMLUnsafe: caller-provided TrustedHTMLParserOptions sanitizer is applied with TrustedHTML while default policy is bypassed
+Fail ShadowRoot.prependHTMLUnsafe: default policy createParserOptions can disable runScripts
+Fail ShadowRoot.prependHTMLUnsafe: default policy createParserOptions can enable runScripts
+Fail ShadowRoot.prependHTMLUnsafe: TrustedHTML runs scripts when caller requests runScripts and default policy allows it
+Fail ShadowRoot.innerHTML: default policy createParserOptions returning {runScripts: true} enables script execution with TrustedHTML
+Fail Element.setHTMLUnsafe: sending TrustedHTML applies sanitizer in default policy createParserOptions
+Pass Element.setHTMLUnsafe: sending TrustedHTML does not call default policy createHTML
+Fail Element.setHTMLUnsafe: exception in default createParserOptions rethrows when TrustedHTML is passed
+Fail Element.setHTMLUnsafe: default createParserOptions returning null throws TypeError when TrustedHTML is passed
+Fail Element.setHTMLUnsafe: default createParserOptions returning undefined throws TypeError when TrustedHTML is passed
+Fail Element.appendHTMLUnsafe: sending TrustedHTML applies sanitizer in default policy createParserOptions
+Fail Element.appendHTMLUnsafe: sending TrustedHTML does not call default policy createHTML
+Fail Element.appendHTMLUnsafe: exception in default createParserOptions rethrows when TrustedHTML is passed
+Pass Element.appendHTMLUnsafe: default createParserOptions returning null throws TypeError when TrustedHTML is passed
+Pass Element.appendHTMLUnsafe: default createParserOptions returning undefined throws TypeError when TrustedHTML is passed
+Fail Element.prependHTMLUnsafe: sending TrustedHTML applies sanitizer in default policy createParserOptions
+Fail Element.prependHTMLUnsafe: sending TrustedHTML does not call default policy createHTML
+Fail Element.prependHTMLUnsafe: exception in default createParserOptions rethrows when TrustedHTML is passed
+Pass Element.prependHTMLUnsafe: default createParserOptions returning null throws TypeError when TrustedHTML is passed
+Pass Element.prependHTMLUnsafe: default createParserOptions returning undefined throws TypeError when TrustedHTML is passed
+Fail Element.beforeHTMLUnsafe: sending TrustedHTML applies sanitizer in default policy createParserOptions
+Fail Element.beforeHTMLUnsafe: sending TrustedHTML does not call default policy createHTML
+Fail Element.beforeHTMLUnsafe: exception in default createParserOptions rethrows when TrustedHTML is passed
+Pass Element.beforeHTMLUnsafe: default createParserOptions returning null throws TypeError when TrustedHTML is passed
+Pass Element.beforeHTMLUnsafe: default createParserOptions returning undefined throws TypeError when TrustedHTML is passed
+Fail Element.afterHTMLUnsafe: sending TrustedHTML applies sanitizer in default policy createParserOptions
+Fail Element.afterHTMLUnsafe: sending TrustedHTML does not call default policy createHTML
+Fail Element.afterHTMLUnsafe: exception in default createParserOptions rethrows when TrustedHTML is passed
+Pass Element.afterHTMLUnsafe: default createParserOptions returning null throws TypeError when TrustedHTML is passed
+Pass Element.afterHTMLUnsafe: default createParserOptions returning undefined throws TypeError when TrustedHTML is passed
+Fail Element.replaceWithHTMLUnsafe: sending TrustedHTML applies sanitizer in default policy createParserOptions
+Fail Element.replaceWithHTMLUnsafe: sending TrustedHTML does not call default policy createHTML
+Fail Element.replaceWithHTMLUnsafe: exception in default createParserOptions rethrows when TrustedHTML is passed
+Pass Element.replaceWithHTMLUnsafe: default createParserOptions returning null throws TypeError when TrustedHTML is passed
+Pass Element.replaceWithHTMLUnsafe: default createParserOptions returning undefined throws TypeError when TrustedHTML is passed
+Fail Element.innerHTML: sending TrustedHTML applies sanitizer in default policy createParserOptions
+Pass Element.innerHTML: sending TrustedHTML does not call default policy createHTML
+Fail Element.innerHTML: exception in default createParserOptions rethrows when TrustedHTML is passed
+Fail Element.innerHTML: default createParserOptions returning null throws TypeError when TrustedHTML is passed
+Fail Element.innerHTML: default createParserOptions returning undefined throws TypeError when TrustedHTML is passed
+Fail Element.outerHTML: sending TrustedHTML applies sanitizer in default policy createParserOptions
+Pass Element.outerHTML: sending TrustedHTML does not call default policy createHTML
+Fail Element.outerHTML: exception in default createParserOptions rethrows when TrustedHTML is passed
+Fail Element.outerHTML: default createParserOptions returning null throws TypeError when TrustedHTML is passed
+Fail Element.outerHTML: default createParserOptions returning undefined throws TypeError when TrustedHTML is passed
+Fail Element.createContextualFragment: sending TrustedHTML applies sanitizer in default policy createParserOptions
+Pass Element.createContextualFragment: sending TrustedHTML does not call default policy createHTML
+Fail Element.createContextualFragment: exception in default createParserOptions rethrows when TrustedHTML is passed
+Fail Element.createContextualFragment: default createParserOptions returning null throws TypeError when TrustedHTML is passed
+Fail Element.createContextualFragment: default createParserOptions returning undefined throws TypeError when TrustedHTML is passed
+Fail Element.afterbegin: sending TrustedHTML applies sanitizer in default policy createParserOptions
+Pass Element.afterbegin: sending TrustedHTML does not call default policy createHTML
+Fail Element.afterbegin: exception in default createParserOptions rethrows when TrustedHTML is passed
+Fail Element.afterbegin: default createParserOptions returning null throws TypeError when TrustedHTML is passed
+Fail Element.afterbegin: default createParserOptions returning undefined throws TypeError when TrustedHTML is passed
+Fail Element.beforeend: sending TrustedHTML applies sanitizer in default policy createParserOptions
+Pass Element.beforeend: sending TrustedHTML does not call default policy createHTML
+Fail Element.beforeend: exception in default createParserOptions rethrows when TrustedHTML is passed
+Fail Element.beforeend: default createParserOptions returning null throws TypeError when TrustedHTML is passed
+Fail Element.beforeend: default createParserOptions returning undefined throws TypeError when TrustedHTML is passed
+Fail Element.beforebegin: sending TrustedHTML applies sanitizer in default policy createParserOptions
+Pass Element.beforebegin: sending TrustedHTML does not call default policy createHTML
+Fail Element.beforebegin: exception in default createParserOptions rethrows when TrustedHTML is passed
+Fail Element.beforebegin: default createParserOptions returning null throws TypeError when TrustedHTML is passed
+Fail Element.beforebegin: default createParserOptions returning undefined throws TypeError when TrustedHTML is passed
+Fail Element.afterend: sending TrustedHTML applies sanitizer in default policy createParserOptions
+Pass Element.afterend: sending TrustedHTML does not call default policy createHTML
+Fail Element.afterend: exception in default createParserOptions rethrows when TrustedHTML is passed
+Fail Element.afterend: default createParserOptions returning null throws TypeError when TrustedHTML is passed
+Fail Element.afterend: default createParserOptions returning undefined throws TypeError when TrustedHTML is passed
+Fail Element.parseHTMLUnsafe: sending TrustedHTML applies sanitizer in default policy createParserOptions
+Pass Element.parseHTMLUnsafe: sending TrustedHTML does not call default policy createHTML
+Fail Element.parseHTMLUnsafe: exception in default createParserOptions rethrows when TrustedHTML is passed
+Fail Element.parseHTMLUnsafe: default createParserOptions returning null throws TypeError when TrustedHTML is passed
+Fail Element.parseHTMLUnsafe: default createParserOptions returning undefined throws TypeError when TrustedHTML is passed
+Fail Element.setHTMLUnsafe: default policy createParserOptions sanitizer overrides caller sanitizer dictionary with TrustedHTML
+Fail Element.setHTMLUnsafe: caller-provided sanitizer dictionary is applied with TrustedHTML when default policy passes it through
+Fail Element.setHTMLUnsafe: caller-provided TrustedHTMLParserOptions sanitizer is applied with TrustedHTML while default policy is bypassed
+Pass Element.setHTMLUnsafe: default policy createParserOptions can disable runScripts
+Fail Element.setHTMLUnsafe: default policy createParserOptions can enable runScripts
+Fail Element.setHTMLUnsafe: TrustedHTML runs scripts when caller requests runScripts and default policy allows it
+Fail Element.appendHTMLUnsafe: default policy createParserOptions sanitizer overrides caller sanitizer dictionary with TrustedHTML
+Fail Element.appendHTMLUnsafe: caller-provided sanitizer dictionary is applied with TrustedHTML when default policy passes it through
+Fail Element.appendHTMLUnsafe: caller-provided TrustedHTMLParserOptions sanitizer is applied with TrustedHTML while default policy is bypassed
+Fail Element.appendHTMLUnsafe: default policy createParserOptions can disable runScripts
+Fail Element.appendHTMLUnsafe: default policy createParserOptions can enable runScripts
+Fail Element.appendHTMLUnsafe: TrustedHTML runs scripts when caller requests runScripts and default policy allows it
+Fail Element.prependHTMLUnsafe: default policy createParserOptions sanitizer overrides caller sanitizer dictionary with TrustedHTML
+Fail Element.prependHTMLUnsafe: caller-provided sanitizer dictionary is applied with TrustedHTML when default policy passes it through
+Fail Element.prependHTMLUnsafe: caller-provided TrustedHTMLParserOptions sanitizer is applied with TrustedHTML while default policy is bypassed
+Fail Element.prependHTMLUnsafe: default policy createParserOptions can disable runScripts
+Fail Element.prependHTMLUnsafe: default policy createParserOptions can enable runScripts
+Fail Element.prependHTMLUnsafe: TrustedHTML runs scripts when caller requests runScripts and default policy allows it
+Fail Element.beforeHTMLUnsafe: default policy createParserOptions sanitizer overrides caller sanitizer dictionary with TrustedHTML
+Fail Element.beforeHTMLUnsafe: caller-provided sanitizer dictionary is applied with TrustedHTML when default policy passes it through
+Fail Element.beforeHTMLUnsafe: caller-provided TrustedHTMLParserOptions sanitizer is applied with TrustedHTML while default policy is bypassed
+Fail Element.beforeHTMLUnsafe: default policy createParserOptions can disable runScripts
+Fail Element.beforeHTMLUnsafe: default policy createParserOptions can enable runScripts
+Fail Element.beforeHTMLUnsafe: TrustedHTML runs scripts when caller requests runScripts and default policy allows it
+Fail Element.afterHTMLUnsafe: default policy createParserOptions sanitizer overrides caller sanitizer dictionary with TrustedHTML
+Fail Element.afterHTMLUnsafe: caller-provided sanitizer dictionary is applied with TrustedHTML when default policy passes it through
+Fail Element.afterHTMLUnsafe: caller-provided TrustedHTMLParserOptions sanitizer is applied with TrustedHTML while default policy is bypassed
+Fail Element.afterHTMLUnsafe: default policy createParserOptions can disable runScripts
+Fail Element.afterHTMLUnsafe: default policy createParserOptions can enable runScripts
+Fail Element.afterHTMLUnsafe: TrustedHTML runs scripts when caller requests runScripts and default policy allows it
+Fail Element.replaceWithHTMLUnsafe: default policy createParserOptions sanitizer overrides caller sanitizer dictionary with TrustedHTML
+Fail Element.replaceWithHTMLUnsafe: caller-provided sanitizer dictionary is applied with TrustedHTML when default policy passes it through
+Fail Element.replaceWithHTMLUnsafe: caller-provided TrustedHTMLParserOptions sanitizer is applied with TrustedHTML while default policy is bypassed
+Fail Element.replaceWithHTMLUnsafe: default policy createParserOptions can disable runScripts
+Fail Element.replaceWithHTMLUnsafe: default policy createParserOptions can enable runScripts
+Fail Element.replaceWithHTMLUnsafe: TrustedHTML runs scripts when caller requests runScripts and default policy allows it
+Fail Element.innerHTML: default policy createParserOptions returning {runScripts: true} enables script execution with TrustedHTML
+Fail Element.outerHTML: default policy createParserOptions returning {runScripts: true} enables script execution with TrustedHTML
+Fail Element.afterbegin: default policy createParserOptions returning {runScripts: true} enables script execution with TrustedHTML
+Fail Element.beforeend: default policy createParserOptions returning {runScripts: true} enables script execution with TrustedHTML
+Fail Element.beforebegin: default policy createParserOptions returning {runScripts: true} enables script execution with TrustedHTML
+Fail Element.afterend: default policy createParserOptions returning {runScripts: true} enables script execution with TrustedHTML
+Pass Element: createContextualFragment with TrustedHTML and createParserOptions(runScripts=false) does not run scripts
+Fail Element: createContextualFragment with TrustedHTML runs scripts by default
+Fail Document.parseHTMLUnsafe: default policy createParserOptions sanitizer overrides caller sanitizer dictionary with TrustedHTML
+Fail Document.parseHTMLUnsafe: caller-provided sanitizer dictionary is applied with TrustedHTML when default policy passes it through
+Fail Document.parseHTMLUnsafe: caller-provided TrustedHTMLParserOptions sanitizer is applied with TrustedHTML while default policy is bypassed
+Pass innerHTML on XML document does not call createParserOptions or throw TypeError when TrustedHTML is passed
+Pass outerHTML on XML document does not call createParserOptions or throw TypeError when TrustedHTML is passed
+Pass insertAdjacentHTML on XML document does not call createParserOptions or throw TypeError when TrustedHTML is passed
+Pass createContextualFragment on XML document does not call createParserOptions or throw TypeError when TrustedHTML is passed
+Fail setHTMLUnsafe on XML document calls createParserOptions and applies sanitizer when TrustedHTML is passed
+Fail appendHTMLUnsafe on XML document calls createParserOptions and applies sanitizer when TrustedHTML is passed
+Fail prependHTMLUnsafe on XML document calls createParserOptions and applies sanitizer when TrustedHTML is passed
+Fail beforeHTMLUnsafe on XML document calls createParserOptions and applies sanitizer when TrustedHTML is passed
+Fail afterHTMLUnsafe on XML document calls createParserOptions and applies sanitizer when TrustedHTML is passed
+Fail replaceWithHTMLUnsafe on XML document calls createParserOptions and applies sanitizer when TrustedHTML is passed
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-with-trustedtypes-createParserOptions-null.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-with-trustedtypes-createParserOptions-null.txt
new file mode 100644
index 00000000000..296fdb73424
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-with-trustedtypes-createParserOptions-null.txt
@@ -0,0 +1,7 @@
+Harness status: OK
+
+Found 2 tests
+
+2 Pass
+Pass Named policy createParserOptions returning null throws TypeError
+Pass Named policy createParserOptions returning undefined throws TypeError
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-with-trustedtypes-createParserOptions.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-with-trustedtypes-createParserOptions.txt
new file mode 100644
index 00000000000..375efa19ac7
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-with-trustedtypes-createParserOptions.txt
@@ -0,0 +1,103 @@
+Harness status: OK
+
+Found 97 tests
+
+8 Pass
+89 Fail
+Fail ShadowRoot.setHTMLUnsafe: passing a TrustedHTMLParserOptions overrides default policy
+Fail ShadowRoot.setHTMLUnsafe: policy with only createParserOptions allows raw strings when sanitizer is present
+Fail ShadowRoot.setHTMLUnsafe: policy with only createParserOptions allows raw strings without sanitizer
+Fail ShadowRoot.setHTMLUnsafe: TrustedHTMLParserOptions without sanitizer satisfies Trusted Types and does not require createHTML
+Fail ShadowRoot.setHTMLUnsafe: exception in default createParserOptions prevents createHTML from running
+Fail ShadowRoot.setHTMLUnsafe: default policy createParserOptions with sanitizer prevents createHTML from running
+Fail ShadowRoot.setHTMLUnsafe: default policy createParserOptions without sanitizer prevents createHTML from running
+Fail ShadowRoot.setHTMLUnsafe: default policy createParserOptions can override runScripts from false to true
+Pass ShadowRoot.setHTMLUnsafe: default policy createParserOptions can override runScripts from true to false
+Fail ShadowRoot.appendHTMLUnsafe: passing a TrustedHTMLParserOptions overrides default policy
+Fail ShadowRoot.appendHTMLUnsafe: policy with only createParserOptions allows raw strings when sanitizer is present
+Fail ShadowRoot.appendHTMLUnsafe: policy with only createParserOptions allows raw strings without sanitizer
+Fail ShadowRoot.appendHTMLUnsafe: TrustedHTMLParserOptions without sanitizer satisfies Trusted Types and does not require createHTML
+Fail ShadowRoot.appendHTMLUnsafe: exception in default createParserOptions prevents createHTML from running
+Fail ShadowRoot.appendHTMLUnsafe: default policy createParserOptions with sanitizer prevents createHTML from running
+Fail ShadowRoot.appendHTMLUnsafe: default policy createParserOptions without sanitizer prevents createHTML from running
+Fail ShadowRoot.appendHTMLUnsafe: default policy createParserOptions can override runScripts from false to true
+Fail ShadowRoot.appendHTMLUnsafe: default policy createParserOptions can override runScripts from true to false
+Fail ShadowRoot.prependHTMLUnsafe: passing a TrustedHTMLParserOptions overrides default policy
+Fail ShadowRoot.prependHTMLUnsafe: policy with only createParserOptions allows raw strings when sanitizer is present
+Fail ShadowRoot.prependHTMLUnsafe: policy with only createParserOptions allows raw strings without sanitizer
+Fail ShadowRoot.prependHTMLUnsafe: TrustedHTMLParserOptions without sanitizer satisfies Trusted Types and does not require createHTML
+Fail ShadowRoot.prependHTMLUnsafe: exception in default createParserOptions prevents createHTML from running
+Fail ShadowRoot.prependHTMLUnsafe: default policy createParserOptions with sanitizer prevents createHTML from running
+Fail ShadowRoot.prependHTMLUnsafe: default policy createParserOptions without sanitizer prevents createHTML from running
+Fail ShadowRoot.prependHTMLUnsafe: default policy createParserOptions can override runScripts from false to true
+Fail ShadowRoot.prependHTMLUnsafe: default policy createParserOptions can override runScripts from true to false
+Fail Element.setHTMLUnsafe: passing a TrustedHTMLParserOptions overrides default policy
+Fail Element.setHTMLUnsafe: policy with only createParserOptions allows raw strings when sanitizer is present
+Fail Element.setHTMLUnsafe: policy with only createParserOptions allows raw strings without sanitizer
+Fail Element.setHTMLUnsafe: TrustedHTMLParserOptions without sanitizer satisfies Trusted Types and does not require createHTML
+Fail Element.setHTMLUnsafe: exception in default createParserOptions prevents createHTML from running
+Fail Element.setHTMLUnsafe: default policy createParserOptions with sanitizer prevents createHTML from running
+Fail Element.setHTMLUnsafe: default policy createParserOptions without sanitizer prevents createHTML from running
+Fail Element.setHTMLUnsafe: default policy createParserOptions can override runScripts from false to true
+Pass Element.setHTMLUnsafe: default policy createParserOptions can override runScripts from true to false
+Fail Element.appendHTMLUnsafe: passing a TrustedHTMLParserOptions overrides default policy
+Fail Element.appendHTMLUnsafe: policy with only createParserOptions allows raw strings when sanitizer is present
+Fail Element.appendHTMLUnsafe: policy with only createParserOptions allows raw strings without sanitizer
+Fail Element.appendHTMLUnsafe: TrustedHTMLParserOptions without sanitizer satisfies Trusted Types and does not require createHTML
+Fail Element.appendHTMLUnsafe: exception in default createParserOptions prevents createHTML from running
+Fail Element.appendHTMLUnsafe: default policy createParserOptions with sanitizer prevents createHTML from running
+Fail Element.appendHTMLUnsafe: default policy createParserOptions without sanitizer prevents createHTML from running
+Fail Element.appendHTMLUnsafe: default policy createParserOptions can override runScripts from false to true
+Fail Element.appendHTMLUnsafe: default policy createParserOptions can override runScripts from true to false
+Fail Element.prependHTMLUnsafe: passing a TrustedHTMLParserOptions overrides default policy
+Fail Element.prependHTMLUnsafe: policy with only createParserOptions allows raw strings when sanitizer is present
+Fail Element.prependHTMLUnsafe: policy with only createParserOptions allows raw strings without sanitizer
+Fail Element.prependHTMLUnsafe: TrustedHTMLParserOptions without sanitizer satisfies Trusted Types and does not require createHTML
+Fail Element.prependHTMLUnsafe: exception in default createParserOptions prevents createHTML from running
+Fail Element.prependHTMLUnsafe: default policy createParserOptions with sanitizer prevents createHTML from running
+Fail Element.prependHTMLUnsafe: default policy createParserOptions without sanitizer prevents createHTML from running
+Fail Element.prependHTMLUnsafe: default policy createParserOptions can override runScripts from false to true
+Fail Element.prependHTMLUnsafe: default policy createParserOptions can override runScripts from true to false
+Fail Element.beforeHTMLUnsafe: passing a TrustedHTMLParserOptions overrides default policy
+Fail Element.beforeHTMLUnsafe: policy with only createParserOptions allows raw strings when sanitizer is present
+Fail Element.beforeHTMLUnsafe: policy with only createParserOptions allows raw strings without sanitizer
+Fail Element.beforeHTMLUnsafe: TrustedHTMLParserOptions without sanitizer satisfies Trusted Types and does not require createHTML
+Fail Element.beforeHTMLUnsafe: exception in default createParserOptions prevents createHTML from running
+Fail Element.beforeHTMLUnsafe: default policy createParserOptions with sanitizer prevents createHTML from running
+Fail Element.beforeHTMLUnsafe: default policy createParserOptions without sanitizer prevents createHTML from running
+Fail Element.beforeHTMLUnsafe: default policy createParserOptions can override runScripts from false to true
+Fail Element.beforeHTMLUnsafe: default policy createParserOptions can override runScripts from true to false
+Fail Element.afterHTMLUnsafe: passing a TrustedHTMLParserOptions overrides default policy
+Fail Element.afterHTMLUnsafe: policy with only createParserOptions allows raw strings when sanitizer is present
+Fail Element.afterHTMLUnsafe: policy with only createParserOptions allows raw strings without sanitizer
+Fail Element.afterHTMLUnsafe: TrustedHTMLParserOptions without sanitizer satisfies Trusted Types and does not require createHTML
+Fail Element.afterHTMLUnsafe: exception in default createParserOptions prevents createHTML from running
+Fail Element.afterHTMLUnsafe: default policy createParserOptions with sanitizer prevents createHTML from running
+Fail Element.afterHTMLUnsafe: default policy createParserOptions without sanitizer prevents createHTML from running
+Fail Element.afterHTMLUnsafe: default policy createParserOptions can override runScripts from false to true
+Fail Element.afterHTMLUnsafe: default policy createParserOptions can override runScripts from true to false
+Fail Element.replaceWithHTMLUnsafe: passing a TrustedHTMLParserOptions overrides default policy
+Fail Element.replaceWithHTMLUnsafe: policy with only createParserOptions allows raw strings when sanitizer is present
+Fail Element.replaceWithHTMLUnsafe: policy with only createParserOptions allows raw strings without sanitizer
+Fail Element.replaceWithHTMLUnsafe: TrustedHTMLParserOptions without sanitizer satisfies Trusted Types and does not require createHTML
+Fail Element.replaceWithHTMLUnsafe: exception in default createParserOptions prevents createHTML from running
+Fail Element.replaceWithHTMLUnsafe: default policy createParserOptions with sanitizer prevents createHTML from running
+Fail Element.replaceWithHTMLUnsafe: default policy createParserOptions without sanitizer prevents createHTML from running
+Fail Element.replaceWithHTMLUnsafe: default policy createParserOptions can override runScripts from false to true
+Fail Element.replaceWithHTMLUnsafe: default policy createParserOptions can override runScripts from true to false
+Fail TrustedTypePolicy.createParserOptions forwards extra arguments to callback
+Fail TrustedTypePolicy.createParserOptions callback receives converted options dictionary
+Fail TrustedHTMLParserOptions applies runScripts option without exposing public members
+Pass TrustedTypePolicy.createParserOptions returning something other than an object (number: 0) throws a TypeError
+Fail Element.setHTMLUnsafe: default policy createParserOptions returning something other than an object (number: 0) throws a TypeError
+Pass TrustedTypePolicy.createParserOptions returning something other than an object (number: 123) throws a TypeError
+Fail Element.setHTMLUnsafe: default policy createParserOptions returning something other than an object (number: 123) throws a TypeError
+Pass TrustedTypePolicy.createParserOptions returning something other than an object (boolean: true) throws a TypeError
+Fail Element.setHTMLUnsafe: default policy createParserOptions returning something other than an object (boolean: true) throws a TypeError
+Pass TrustedTypePolicy.createParserOptions returning something other than an object (boolean: false) throws a TypeError
+Fail Element.setHTMLUnsafe: default policy createParserOptions returning something other than an object (boolean: false) throws a TypeError
+Pass TrustedTypePolicy.createParserOptions returning something other than an object (string: "string") throws a TypeError
+Fail Element.setHTMLUnsafe: default policy createParserOptions returning something other than an object (string: "string") throws a TypeError
+Fail Document.parseHTMLUnsafe: TrustedHTMLParserOptions without sanitizer satisfies Trusted Types and does not require createHTML
+Fail Document.parseHTMLUnsafe: default policy createParserOptions without sanitizer prevents createHTML from running
+Pass Element.setHTMLUnsafe: default policy without createParserOptions falls back to createHTML
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-with-trustedtypes-immutable.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-with-trustedtypes-immutable.txt
new file mode 100644
index 00000000000..c8817beacf5
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-with-trustedtypes-immutable.txt
@@ -0,0 +1,21 @@
+Harness status: OK
+
+Found 16 tests
+
+16 Fail
+Fail setHTMLUnsafe: createParserOptions doesn't mutate original object
+Fail setHTMLUnsafe: createParserOptions doesn't mutate sanitizer object
+Fail appendHTMLUnsafe: createParserOptions doesn't mutate original object
+Fail appendHTMLUnsafe: createParserOptions doesn't mutate sanitizer object
+Fail prependHTMLUnsafe: createParserOptions doesn't mutate original object
+Fail prependHTMLUnsafe: createParserOptions doesn't mutate sanitizer object
+Fail beforeHTMLUnsafe: createParserOptions doesn't mutate original object
+Fail beforeHTMLUnsafe: createParserOptions doesn't mutate sanitizer object
+Fail afterHTMLUnsafe: createParserOptions doesn't mutate original object
+Fail afterHTMLUnsafe: createParserOptions doesn't mutate sanitizer object
+Fail replaceWithHTMLUnsafe: createParserOptions doesn't mutate original object
+Fail replaceWithHTMLUnsafe: createParserOptions doesn't mutate sanitizer object
+Fail TrustedHTMLParserOptions interface has no public members
+Fail TrustedHTMLParserOptions with config input applies sanitization without public members
+Fail TrustedHTMLParserOptions clone testing with Sanitizer object input
+Fail TrustedHTMLParserOptions with Preset string input
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-with-trustedtypes.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-with-trustedtypes.txt
new file mode 100644
index 00000000000..bffddc4eff8
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-with-trustedtypes.txt
@@ -0,0 +1,259 @@
+Harness status: OK
+
+Found 253 tests
+
+55 Pass
+198 Fail
+Fail ShadowRoot.setHTMLUnsafe: createParserOptions can inject a sanitizer config
+Fail ShadowRoot.setHTMLUnsafe: createParserOptions receives correct type and sink name
+Fail ShadowRoot.setHTMLUnsafe: createParserOptions can inject a sanitizer
+Fail ShadowRoot.setHTMLUnsafe: createParserOptions can override a sanitizer config
+Pass ShadowRoot.setHTMLUnsafe: createParserOptions can remove a sanitizer
+Fail ShadowRoot.setHTMLUnsafe: createParserOptions returning null fails
+Fail ShadowRoot.setHTMLUnsafe: createParserOptions returning undefined fails
+Fail ShadowRoot.setHTMLUnsafe: createParserOptions returning 0 fails
+Fail ShadowRoot.setHTMLUnsafe: createParserOptions returning 123 fails
+Fail ShadowRoot.setHTMLUnsafe: createParserOptions returning "foo" fails
+Fail ShadowRoot.setHTMLUnsafe: createParserOptions returning true fails
+Fail ShadowRoot.setHTMLUnsafe: createParserOptions returning false fails
+Fail ShadowRoot.appendHTMLUnsafe: createParserOptions can inject a sanitizer config
+Fail ShadowRoot.appendHTMLUnsafe: createParserOptions receives correct type and sink name
+Fail ShadowRoot.appendHTMLUnsafe: createParserOptions can inject a sanitizer
+Fail ShadowRoot.appendHTMLUnsafe: createParserOptions can override a sanitizer config
+Fail ShadowRoot.appendHTMLUnsafe: createParserOptions can remove a sanitizer
+Pass ShadowRoot.appendHTMLUnsafe: createParserOptions returning null fails
+Pass ShadowRoot.appendHTMLUnsafe: createParserOptions returning undefined fails
+Pass ShadowRoot.appendHTMLUnsafe: createParserOptions returning 0 fails
+Pass ShadowRoot.appendHTMLUnsafe: createParserOptions returning 123 fails
+Pass ShadowRoot.appendHTMLUnsafe: createParserOptions returning "foo" fails
+Pass ShadowRoot.appendHTMLUnsafe: createParserOptions returning true fails
+Pass ShadowRoot.appendHTMLUnsafe: createParserOptions returning false fails
+Fail ShadowRoot.prependHTMLUnsafe: createParserOptions can inject a sanitizer config
+Fail ShadowRoot.prependHTMLUnsafe: createParserOptions receives correct type and sink name
+Fail ShadowRoot.prependHTMLUnsafe: createParserOptions can inject a sanitizer
+Fail ShadowRoot.prependHTMLUnsafe: createParserOptions can override a sanitizer config
+Fail ShadowRoot.prependHTMLUnsafe: createParserOptions can remove a sanitizer
+Pass ShadowRoot.prependHTMLUnsafe: createParserOptions returning null fails
+Pass ShadowRoot.prependHTMLUnsafe: createParserOptions returning undefined fails
+Pass ShadowRoot.prependHTMLUnsafe: createParserOptions returning 0 fails
+Pass ShadowRoot.prependHTMLUnsafe: createParserOptions returning 123 fails
+Pass ShadowRoot.prependHTMLUnsafe: createParserOptions returning "foo" fails
+Pass ShadowRoot.prependHTMLUnsafe: createParserOptions returning true fails
+Pass ShadowRoot.prependHTMLUnsafe: createParserOptions returning false fails
+Fail ShadowRoot.innerHTML: createParserOptions can inject a sanitizer config
+Fail ShadowRoot.innerHTML: createParserOptions receives correct type and sink name
+Fail ShadowRoot.innerHTML: createParserOptions can inject a sanitizer
+Fail ShadowRoot.innerHTML: createParserOptions returning null fails
+Fail ShadowRoot.innerHTML: createParserOptions returning undefined fails
+Fail ShadowRoot.innerHTML: createParserOptions returning 0 fails
+Fail ShadowRoot.innerHTML: createParserOptions returning 123 fails
+Fail ShadowRoot.innerHTML: createParserOptions returning "foo" fails
+Fail ShadowRoot.innerHTML: createParserOptions returning true fails
+Fail ShadowRoot.innerHTML: createParserOptions returning false fails
+Pass ShadowRoot.setHTMLUnsafe: createParserOptions can override runScripts from true to false
+Fail ShadowRoot.setHTMLUnsafe: createParserOptions can override runScripts from false to true
+Fail ShadowRoot.setHTMLUnsafe: createParserOptions with sanitizer prevents createHTML from running
+Fail ShadowRoot.appendHTMLUnsafe: createParserOptions can override runScripts from true to false
+Fail ShadowRoot.appendHTMLUnsafe: createParserOptions can override runScripts from false to true
+Fail ShadowRoot.appendHTMLUnsafe: createParserOptions with sanitizer prevents createHTML from running
+Fail ShadowRoot.prependHTMLUnsafe: createParserOptions can override runScripts from true to false
+Fail ShadowRoot.prependHTMLUnsafe: createParserOptions can override runScripts from false to true
+Fail ShadowRoot.prependHTMLUnsafe: createParserOptions with sanitizer prevents createHTML from running
+Fail ShadowRoot.innerHTML: createParserOptions returning {runScripts: true} enables script execution
+Fail ShadowRoot.setHTMLUnsafe: exception in createParserOptions is rethrown and prevents createHTML
+Fail ShadowRoot.appendHTMLUnsafe: exception in createParserOptions is rethrown and prevents createHTML
+Fail ShadowRoot.prependHTMLUnsafe: exception in createParserOptions is rethrown and prevents createHTML
+Fail ShadowRoot.innerHTML: exception in createParserOptions is rethrown and prevents createHTML
+Fail Element.setHTMLUnsafe: createParserOptions can inject a sanitizer config
+Fail Element.setHTMLUnsafe: createParserOptions receives correct type and sink name
+Fail Element.setHTMLUnsafe: createParserOptions can inject a sanitizer
+Fail Element.setHTMLUnsafe: createParserOptions can override a sanitizer config
+Pass Element.setHTMLUnsafe: createParserOptions can remove a sanitizer
+Fail Element.setHTMLUnsafe: createParserOptions returning null fails
+Fail Element.setHTMLUnsafe: createParserOptions returning undefined fails
+Fail Element.setHTMLUnsafe: createParserOptions returning 0 fails
+Fail Element.setHTMLUnsafe: createParserOptions returning 123 fails
+Fail Element.setHTMLUnsafe: createParserOptions returning "foo" fails
+Fail Element.setHTMLUnsafe: createParserOptions returning true fails
+Fail Element.setHTMLUnsafe: createParserOptions returning false fails
+Fail Element.appendHTMLUnsafe: createParserOptions can inject a sanitizer config
+Fail Element.appendHTMLUnsafe: createParserOptions receives correct type and sink name
+Fail Element.appendHTMLUnsafe: createParserOptions can inject a sanitizer
+Fail Element.appendHTMLUnsafe: createParserOptions can override a sanitizer config
+Fail Element.appendHTMLUnsafe: createParserOptions can remove a sanitizer
+Pass Element.appendHTMLUnsafe: createParserOptions returning null fails
+Pass Element.appendHTMLUnsafe: createParserOptions returning undefined fails
+Pass Element.appendHTMLUnsafe: createParserOptions returning 0 fails
+Pass Element.appendHTMLUnsafe: createParserOptions returning 123 fails
+Pass Element.appendHTMLUnsafe: createParserOptions returning "foo" fails
+Pass Element.appendHTMLUnsafe: createParserOptions returning true fails
+Pass Element.appendHTMLUnsafe: createParserOptions returning false fails
+Fail Element.prependHTMLUnsafe: createParserOptions can inject a sanitizer config
+Fail Element.prependHTMLUnsafe: createParserOptions receives correct type and sink name
+Fail Element.prependHTMLUnsafe: createParserOptions can inject a sanitizer
+Fail Element.prependHTMLUnsafe: createParserOptions can override a sanitizer config
+Fail Element.prependHTMLUnsafe: createParserOptions can remove a sanitizer
+Pass Element.prependHTMLUnsafe: createParserOptions returning null fails
+Pass Element.prependHTMLUnsafe: createParserOptions returning undefined fails
+Pass Element.prependHTMLUnsafe: createParserOptions returning 0 fails
+Pass Element.prependHTMLUnsafe: createParserOptions returning 123 fails
+Pass Element.prependHTMLUnsafe: createParserOptions returning "foo" fails
+Pass Element.prependHTMLUnsafe: createParserOptions returning true fails
+Pass Element.prependHTMLUnsafe: createParserOptions returning false fails
+Fail Element.beforeHTMLUnsafe: createParserOptions can inject a sanitizer config
+Fail Element.beforeHTMLUnsafe: createParserOptions receives correct type and sink name
+Fail Element.beforeHTMLUnsafe: createParserOptions can inject a sanitizer
+Fail Element.beforeHTMLUnsafe: createParserOptions can override a sanitizer config
+Fail Element.beforeHTMLUnsafe: createParserOptions can remove a sanitizer
+Pass Element.beforeHTMLUnsafe: createParserOptions returning null fails
+Pass Element.beforeHTMLUnsafe: createParserOptions returning undefined fails
+Pass Element.beforeHTMLUnsafe: createParserOptions returning 0 fails
+Pass Element.beforeHTMLUnsafe: createParserOptions returning 123 fails
+Pass Element.beforeHTMLUnsafe: createParserOptions returning "foo" fails
+Pass Element.beforeHTMLUnsafe: createParserOptions returning true fails
+Pass Element.beforeHTMLUnsafe: createParserOptions returning false fails
+Fail Element.afterHTMLUnsafe: createParserOptions can inject a sanitizer config
+Fail Element.afterHTMLUnsafe: createParserOptions receives correct type and sink name
+Fail Element.afterHTMLUnsafe: createParserOptions can inject a sanitizer
+Fail Element.afterHTMLUnsafe: createParserOptions can override a sanitizer config
+Fail Element.afterHTMLUnsafe: createParserOptions can remove a sanitizer
+Pass Element.afterHTMLUnsafe: createParserOptions returning null fails
+Pass Element.afterHTMLUnsafe: createParserOptions returning undefined fails
+Pass Element.afterHTMLUnsafe: createParserOptions returning 0 fails
+Pass Element.afterHTMLUnsafe: createParserOptions returning 123 fails
+Pass Element.afterHTMLUnsafe: createParserOptions returning "foo" fails
+Pass Element.afterHTMLUnsafe: createParserOptions returning true fails
+Pass Element.afterHTMLUnsafe: createParserOptions returning false fails
+Fail Element.replaceWithHTMLUnsafe: createParserOptions can inject a sanitizer config
+Fail Element.replaceWithHTMLUnsafe: createParserOptions receives correct type and sink name
+Fail Element.replaceWithHTMLUnsafe: createParserOptions can inject a sanitizer
+Fail Element.replaceWithHTMLUnsafe: createParserOptions can override a sanitizer config
+Fail Element.replaceWithHTMLUnsafe: createParserOptions can remove a sanitizer
+Pass Element.replaceWithHTMLUnsafe: createParserOptions returning null fails
+Pass Element.replaceWithHTMLUnsafe: createParserOptions returning undefined fails
+Pass Element.replaceWithHTMLUnsafe: createParserOptions returning 0 fails
+Pass Element.replaceWithHTMLUnsafe: createParserOptions returning 123 fails
+Pass Element.replaceWithHTMLUnsafe: createParserOptions returning "foo" fails
+Pass Element.replaceWithHTMLUnsafe: createParserOptions returning true fails
+Pass Element.replaceWithHTMLUnsafe: createParserOptions returning false fails
+Fail Element.innerHTML: createParserOptions can inject a sanitizer config
+Fail Element.innerHTML: createParserOptions receives correct type and sink name
+Fail Element.innerHTML: createParserOptions can inject a sanitizer
+Fail Element.innerHTML: createParserOptions returning null fails
+Fail Element.innerHTML: createParserOptions returning undefined fails
+Fail Element.innerHTML: createParserOptions returning 0 fails
+Fail Element.innerHTML: createParserOptions returning 123 fails
+Fail Element.innerHTML: createParserOptions returning "foo" fails
+Fail Element.innerHTML: createParserOptions returning true fails
+Fail Element.innerHTML: createParserOptions returning false fails
+Fail Element.outerHTML: createParserOptions can inject a sanitizer config
+Fail Element.outerHTML: createParserOptions receives correct type and sink name
+Fail Element.outerHTML: createParserOptions can inject a sanitizer
+Fail Element.outerHTML: createParserOptions returning null fails
+Fail Element.outerHTML: createParserOptions returning undefined fails
+Fail Element.outerHTML: createParserOptions returning 0 fails
+Fail Element.outerHTML: createParserOptions returning 123 fails
+Fail Element.outerHTML: createParserOptions returning "foo" fails
+Fail Element.outerHTML: createParserOptions returning true fails
+Fail Element.outerHTML: createParserOptions returning false fails
+Fail Element.createContextualFragment: createParserOptions can inject a sanitizer config
+Fail Element.createContextualFragment: createParserOptions receives correct type and sink name
+Fail Element.createContextualFragment: createParserOptions can inject a sanitizer
+Fail Element.createContextualFragment: createParserOptions returning null fails
+Fail Element.createContextualFragment: createParserOptions returning undefined fails
+Fail Element.createContextualFragment: createParserOptions returning 0 fails
+Fail Element.createContextualFragment: createParserOptions returning 123 fails
+Fail Element.createContextualFragment: createParserOptions returning "foo" fails
+Fail Element.createContextualFragment: createParserOptions returning true fails
+Fail Element.createContextualFragment: createParserOptions returning false fails
+Fail Element.afterbegin: createParserOptions can inject a sanitizer config
+Fail Element.afterbegin: createParserOptions receives correct type and sink name
+Fail Element.afterbegin: createParserOptions can inject a sanitizer
+Fail Element.afterbegin: createParserOptions returning null fails
+Fail Element.afterbegin: createParserOptions returning undefined fails
+Fail Element.afterbegin: createParserOptions returning 0 fails
+Fail Element.afterbegin: createParserOptions returning 123 fails
+Fail Element.afterbegin: createParserOptions returning "foo" fails
+Fail Element.afterbegin: createParserOptions returning true fails
+Fail Element.afterbegin: createParserOptions returning false fails
+Fail Element.beforeend: createParserOptions can inject a sanitizer config
+Fail Element.beforeend: createParserOptions receives correct type and sink name
+Fail Element.beforeend: createParserOptions can inject a sanitizer
+Fail Element.beforeend: createParserOptions returning null fails
+Fail Element.beforeend: createParserOptions returning undefined fails
+Fail Element.beforeend: createParserOptions returning 0 fails
+Fail Element.beforeend: createParserOptions returning 123 fails
+Fail Element.beforeend: createParserOptions returning "foo" fails
+Fail Element.beforeend: createParserOptions returning true fails
+Fail Element.beforeend: createParserOptions returning false fails
+Fail Element.beforebegin: createParserOptions can inject a sanitizer config
+Fail Element.beforebegin: createParserOptions receives correct type and sink name
+Fail Element.beforebegin: createParserOptions can inject a sanitizer
+Fail Element.beforebegin: createParserOptions returning null fails
+Fail Element.beforebegin: createParserOptions returning undefined fails
+Fail Element.beforebegin: createParserOptions returning 0 fails
+Fail Element.beforebegin: createParserOptions returning 123 fails
+Fail Element.beforebegin: createParserOptions returning "foo" fails
+Fail Element.beforebegin: createParserOptions returning true fails
+Fail Element.beforebegin: createParserOptions returning false fails
+Fail Element.afterend: createParserOptions can inject a sanitizer config
+Fail Element.afterend: createParserOptions receives correct type and sink name
+Fail Element.afterend: createParserOptions can inject a sanitizer
+Fail Element.afterend: createParserOptions returning null fails
+Fail Element.afterend: createParserOptions returning undefined fails
+Fail Element.afterend: createParserOptions returning 0 fails
+Fail Element.afterend: createParserOptions returning 123 fails
+Fail Element.afterend: createParserOptions returning "foo" fails
+Fail Element.afterend: createParserOptions returning true fails
+Fail Element.afterend: createParserOptions returning false fails
+Fail Element.parseHTMLUnsafe: createParserOptions can inject a sanitizer config
+Fail Element.parseHTMLUnsafe: createParserOptions receives correct type and sink name
+Fail Element.parseHTMLUnsafe: createParserOptions can inject a sanitizer
+Fail Element.parseHTMLUnsafe: createParserOptions can override a sanitizer config
+Pass Element.parseHTMLUnsafe: createParserOptions can remove a sanitizer
+Fail Element.parseHTMLUnsafe: createParserOptions returning null fails
+Fail Element.parseHTMLUnsafe: createParserOptions returning undefined fails
+Fail Element.parseHTMLUnsafe: createParserOptions returning 0 fails
+Fail Element.parseHTMLUnsafe: createParserOptions returning 123 fails
+Fail Element.parseHTMLUnsafe: createParserOptions returning "foo" fails
+Fail Element.parseHTMLUnsafe: createParserOptions returning true fails
+Fail Element.parseHTMLUnsafe: createParserOptions returning false fails
+Pass Element.setHTMLUnsafe: createParserOptions can override runScripts from true to false
+Fail Element.setHTMLUnsafe: createParserOptions can override runScripts from false to true
+Fail Element.setHTMLUnsafe: createParserOptions with sanitizer prevents createHTML from running
+Fail Element.appendHTMLUnsafe: createParserOptions can override runScripts from true to false
+Fail Element.appendHTMLUnsafe: createParserOptions can override runScripts from false to true
+Fail Element.appendHTMLUnsafe: createParserOptions with sanitizer prevents createHTML from running
+Fail Element.prependHTMLUnsafe: createParserOptions can override runScripts from true to false
+Fail Element.prependHTMLUnsafe: createParserOptions can override runScripts from false to true
+Fail Element.prependHTMLUnsafe: createParserOptions with sanitizer prevents createHTML from running
+Fail Element.beforeHTMLUnsafe: createParserOptions can override runScripts from true to false
+Fail Element.beforeHTMLUnsafe: createParserOptions can override runScripts from false to true
+Fail Element.beforeHTMLUnsafe: createParserOptions with sanitizer prevents createHTML from running
+Fail Element.afterHTMLUnsafe: createParserOptions can override runScripts from true to false
+Fail Element.afterHTMLUnsafe: createParserOptions can override runScripts from false to true
+Fail Element.afterHTMLUnsafe: createParserOptions with sanitizer prevents createHTML from running
+Fail Element.replaceWithHTMLUnsafe: createParserOptions can override runScripts from true to false
+Fail Element.replaceWithHTMLUnsafe: createParserOptions can override runScripts from false to true
+Fail Element.replaceWithHTMLUnsafe: createParserOptions with sanitizer prevents createHTML from running
+Fail Element.innerHTML: createParserOptions returning {runScripts: true} enables script execution
+Fail Element.outerHTML: createParserOptions returning {runScripts: true} enables script execution
+Fail Element.afterbegin: createParserOptions returning {runScripts: true} enables script execution
+Fail Element.beforeend: createParserOptions returning {runScripts: true} enables script execution
+Fail Element.beforebegin: createParserOptions returning {runScripts: true} enables script execution
+Fail Element.afterend: createParserOptions returning {runScripts: true} enables script execution
+Pass Element: createContextualFragment with createParserOptions(runScripts=false) does not run scripts
+Fail Element: createContextualFragment runs scripts by default
+Fail Element.setHTMLUnsafe: exception in createParserOptions is rethrown and prevents createHTML
+Fail Element.appendHTMLUnsafe: exception in createParserOptions is rethrown and prevents createHTML
+Fail Element.prependHTMLUnsafe: exception in createParserOptions is rethrown and prevents createHTML
+Fail Element.beforeHTMLUnsafe: exception in createParserOptions is rethrown and prevents createHTML
+Fail Element.afterHTMLUnsafe: exception in createParserOptions is rethrown and prevents createHTML
+Fail Element.replaceWithHTMLUnsafe: exception in createParserOptions is rethrown and prevents createHTML
+Fail Element.innerHTML: exception in createParserOptions is rethrown and prevents createHTML
+Fail Element.outerHTML: exception in createParserOptions is rethrown and prevents createHTML
+Fail Element.createContextualFragment: exception in createParserOptions is rethrown and prevents createHTML
+Fail Element.afterbegin: exception in createParserOptions is rethrown and prevents createHTML
+Fail Element.beforeend: exception in createParserOptions is rethrown and prevents createHTML
+Fail Element.beforebegin: exception in createParserOptions is rethrown and prevents createHTML
+Fail Element.afterend: exception in createParserOptions is rethrown and prevents createHTML
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-xml-document-sanitizer.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-xml-document-sanitizer.txt
new file mode 100644
index 00000000000..369744c0983
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-xml-document-sanitizer.txt
@@ -0,0 +1,32 @@
+Harness status: OK
+
+Found 26 tests
+
+14 Pass
+12 Fail
+Pass innerHTML on XML document throws TypeError without calling createParserOptions if default policy provides only a sanitizer without createHTML
+Pass outerHTML on XML document throws TypeError without calling createParserOptions if default policy provides only a sanitizer without createHTML
+Pass insertAdjacentHTML on XML document throws TypeError without calling createParserOptions if default policy provides only a sanitizer without createHTML
+Pass createContextualFragment on XML document throws TypeError without calling createParserOptions if default policy provides only a sanitizer without createHTML
+Pass innerHTML on XML document created by DOMParser throws TypeError without calling createParserOptions if default policy provides only a sanitizer without createHTML
+Pass innerHTML on XML document from XHR response throws TypeError without calling createParserOptions if default policy provides only a sanitizer without createHTML
+Fail setHTMLUnsafe on XML document does not throw TypeError and applies createParserOptions sanitizer
+Fail setHTMLUnsafe on XML document does not throw TypeError when createParserOptions has no sanitizer
+Fail appendHTMLUnsafe on XML document does not throw TypeError and applies createParserOptions sanitizer
+Fail appendHTMLUnsafe on XML document does not throw TypeError when createParserOptions has no sanitizer
+Fail prependHTMLUnsafe on XML document does not throw TypeError and applies createParserOptions sanitizer
+Fail prependHTMLUnsafe on XML document does not throw TypeError when createParserOptions has no sanitizer
+Fail beforeHTMLUnsafe on XML document does not throw TypeError and applies createParserOptions sanitizer
+Fail beforeHTMLUnsafe on XML document does not throw TypeError when createParserOptions has no sanitizer
+Fail afterHTMLUnsafe on XML document does not throw TypeError and applies createParserOptions sanitizer
+Fail afterHTMLUnsafe on XML document does not throw TypeError when createParserOptions has no sanitizer
+Fail replaceWithHTMLUnsafe on XML document does not throw TypeError and applies createParserOptions sanitizer
+Fail replaceWithHTMLUnsafe on XML document does not throw TypeError when createParserOptions has no sanitizer
+Pass innerHTML on XML document executes createHTML and does not call createParserOptions when default policy provides both
+Pass outerHTML on XML document executes createHTML and does not call createParserOptions when default policy provides both
+Pass insertAdjacentHTML on XML document executes createHTML and does not call createParserOptions when default policy provides both
+Pass createContextualFragment on XML document executes createHTML and does not call createParserOptions when default policy provides both
+Pass innerHTML on XML document created by DOMParser executes createHTML and does not call createParserOptions when default policy provides both
+Pass innerHTML on XML document from XHR response executes createHTML and does not call createParserOptions when default policy provides both
+Pass innerHTML on XML document does not invoke throwing createParserOptions
+Pass innerHTML on XML document accepts TrustedHTML without calling createParserOptions or throwing even if createHTML is missing
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-xml-document.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-xml-document.txt
new file mode 100644
index 00000000000..25b4640635f
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtml-xml-document.txt
@@ -0,0 +1,13 @@
+Harness status: OK
+
+Found 8 tests
+
+8 Fail
+Fail Testcase #0 with xmlDoc.setHTML("Hello!")
+Fail Testcase #0, shadow inside xmlDoc, shadowroot.setHTML("Hello!")
+Fail Testcase #1 with xmlDoc.setHTML("<br>")
+Fail Testcase #1, shadow inside xmlDoc, shadowroot.setHTML("<br>")
+Fail Testcase #2 with xmlDoc.setHTML("<p>Hi</p>")
+Fail Testcase #2, shadow inside xmlDoc, shadowroot.setHTML("<p>Hi</p>")
+Fail Testcase #3 with xmlDoc.setHTML("<iframe></iframe><p>text</p>")
+Fail Testcase #3, shadow inside xmlDoc, shadowroot.setHTML("<iframe></iframe><p>text</p>")
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtmlunsafe-toplevel-template-script.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtmlunsafe-toplevel-template-script.txt
new file mode 100644
index 00000000000..26501bf0243
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/sethtmlunsafe-toplevel-template-script.txt
@@ -0,0 +1,9 @@
+Harness status: OK
+
+Found 3 tests
+
+1 Pass
+2 Fail
+Fail Top-level template and script testcases from sub.dat
+Pass Top-level <script> parsed through setHTMLUnsafe() without runScripts does not execute
+Fail Top-level <script> parsed through setHTMLUnsafe() with runScripts: true executes
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/trustedhtml-unvetted-parser-options-no-enforcement.txt b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/trustedhtml-unvetted-parser-options-no-enforcement.txt
new file mode 100644
index 00000000000..1a2c72ba0da
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/sanitizer-api/trustedhtml-unvetted-parser-options-no-enforcement.txt
@@ -0,0 +1,34 @@
+Harness status: OK
+
+Found 29 tests
+
+29 Fail
+Fail Element.setHTMLUnsafe: TrustedHTML with a sanitizer config is allowed
+Fail Element.setHTMLUnsafe: string with a sanitizer config is allowed
+Fail Element.setHTMLUnsafe: TrustedHTML with runScripts true is allowed
+Fail Element.appendHTMLUnsafe: TrustedHTML with a sanitizer config is allowed
+Fail Element.appendHTMLUnsafe: string with a sanitizer config is allowed
+Fail Element.appendHTMLUnsafe: TrustedHTML with runScripts true is allowed
+Fail Element.prependHTMLUnsafe: TrustedHTML with a sanitizer config is allowed
+Fail Element.prependHTMLUnsafe: string with a sanitizer config is allowed
+Fail Element.prependHTMLUnsafe: TrustedHTML with runScripts true is allowed
+Fail ShadowRoot.setHTMLUnsafe: TrustedHTML with a sanitizer config is allowed
+Fail ShadowRoot.setHTMLUnsafe: string with a sanitizer config is allowed
+Fail ShadowRoot.setHTMLUnsafe: TrustedHTML with runScripts true is allowed
+Fail ShadowRoot.appendHTMLUnsafe: TrustedHTML with a sanitizer config is allowed
+Fail ShadowRoot.appendHTMLUnsafe: string with a sanitizer config is allowed
+Fail ShadowRoot.appendHTMLUnsafe: TrustedHTML with runScripts true is allowed
+Fail ShadowRoot.prependHTMLUnsafe: TrustedHTML with a sanitizer config is allowed
+Fail ShadowRoot.prependHTMLUnsafe: string with a sanitizer config is allowed
+Fail ShadowRoot.prependHTMLUnsafe: TrustedHTML with runScripts true is allowed
+Fail Node.beforeHTMLUnsafe: TrustedHTML with a sanitizer config is allowed
+Fail Node.beforeHTMLUnsafe: string with a sanitizer config is allowed
+Fail Node.beforeHTMLUnsafe: TrustedHTML with runScripts true is allowed
+Fail Node.afterHTMLUnsafe: TrustedHTML with a sanitizer config is allowed
+Fail Node.afterHTMLUnsafe: string with a sanitizer config is allowed
+Fail Node.afterHTMLUnsafe: TrustedHTML with runScripts true is allowed
+Fail Node.replaceWithHTMLUnsafe: TrustedHTML with a sanitizer config is allowed
+Fail Node.replaceWithHTMLUnsafe: string with a sanitizer config is allowed
+Fail Node.replaceWithHTMLUnsafe: TrustedHTML with runScripts true is allowed
+Fail Document.parseHTMLUnsafe: TrustedHTML with a sanitizer config is allowed
+Fail Document.parseHTMLUnsafe: string with a sanitizer config is allowed
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/html5lib-basics.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/html5lib-basics.html
new file mode 100644
index 00000000000..08b398408c6
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/html5lib-basics.html
@@ -0,0 +1,117 @@
+<!DOCTYPE html>
+<head>
+<title>Basic setHTMLUnsafe test cases</title>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="support/html5lib-testcase-support.js"></script
+</head>
+<body>
+<script type="html5lib-tests">
+#data
+Hello!
+#document
+| "Hello!"
+
+#data
+<p>bla
+#document
+| <p>
+| "bla"
+
+#data
+<p id=abc def='123'>texty<!-- xxx -->textz
+#document
+| <p>
+| def="123"
+| id="abc"
+| "texty"
+| <!-- xxx -->
+| "textz"
+
+#data
+<p>Hello <b>World</b><span>!
+#document
+| <p>
+| "Hello "
+| <b>
+| "World"
+| <span>
+| "!"
+
+#data
+<p>A template example.<template>Hello <b>World</b></template>!
+#document
+| <p>
+| "A template example."
+| <template>
+| content
+| "Hello "
+| <b>
+| "World"
+| "!"
+
+#data
+<td>Interesting parse context.</td>
+#document-fragment
+table
+#document
+| <tbody>
+| <tr>
+| <td>
+| "Interesting parse context."
+
+#data
+<p>A rather boring parse context.
+#document-fragment
+p
+#document
+| <p>
+| "A rather boring parse context."
+
+#data
+<table><b>a</b>bb<tr><td>y
+#document
+| <b>
+| "a"
+| "bb"
+| <table>
+| <tbody>
+| <tr>
+| <td>
+| "y"
+
+#data
+<table><div>d</div><td>
+#document
+| <div>
+| "d"
+| <table>
+| <tbody>
+| <tr>
+| <td>
+
+</script>
+<script>
+// This runs a number of simple test cases that test setHTMLUnsafe, and
+// setHTMLUnsafe vs innerHTML. This purposely doesn't include "advanced" test
+// cases where the behaviours of those two methodsis supposed to differ.
+//
+// This sort of also doubles as unit tests for html5lib-testcase-support.js
+html5lib_testcases_from_script().forEach((testcase, index) => {
+ test(_ => {
+ const context = document.createElement(testcase["document-fragment"] ?? "div");
+ context.setHTMLUnsafe(testcase.data);
+ assert_testcase(context, testcase);
+ }, `Testcase #${index} with .setHTMLUnsafe("${testcase.data}")`);
+
+ test(_ => {
+ const context_element = testcase["document-fragment"] ?? "div";
+ const context = document.createElement(context_element);
+ const context2 = document.createElement(context_element);
+
+ context.setHTMLUnsafe(testcase.data);
+ context2.innerHTML = testcase.data;
+ assert_subtree_equals(context, context2);
+ }, `Testcase #${index}, .innerHTML matches .setHTMLUnsafe`);
+});
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/parsehtmlunsafe-with-trustedtypes.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/parsehtmlunsafe-with-trustedtypes.html
new file mode 100644
index 00000000000..d45e38d1883
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/parsehtmlunsafe-with-trustedtypes.html
@@ -0,0 +1,77 @@
+<!doctype html>
+<html>
+ <head>
+ <script src="../resources/testharness.js"></script>
+ <script src="../resources/testharnessreport.js"></script>
+ <script src="../trusted-types/support/helper.sub.js"></script>
+
+ <meta http-equiv="Content-Security-Policy" content="require-trusted-types-for 'script';">
+ </head>
+ <body>
+ <div id="container"></div>
+ <script>
+ const container = document.querySelector("#container");
+ let createParserOptions = (options) => options;
+
+ trustedTypes.createPolicy("default", {
+ createHTML: (html) => html,
+ createParserOptions: (options) => createParserOptions(options),
+ });
+
+ test((t) => {
+ t.add_cleanup(() => {
+ createParserOptions = (options) => options;
+ });
+
+ createParserOptions = (options) => ({
+ ...options,
+ sanitizer: { removeElements: ["span"] },
+ });
+
+ const doc = Document.parseHTMLUnsafe(
+ "<div id='allowed'><span id=forbidden></span></div>",
+ );
+ assert_equals(doc.querySelector("#forbidden"), null);
+ assert_not_equals(doc.querySelector("#allowed"), null);
+ }, "Document.parseHTMLUnsafe: createParserOptions can inject a sanitizer config");
+
+ test((t) => {
+ t.add_cleanup(() => {
+ createParserOptions = (options) => options;
+ });
+
+ createParserOptions = (options) => ({
+ ...options,
+ sanitizer: { removeElements: ["span"] },
+ });
+
+ // Pass a TrustedHTMLParserOptions object directly
+ const policy = trustedTypes.createPolicy("test", {
+ createParserOptions: (options) => options,
+ });
+ const options = policy.createParserOptions({ sanitizer: { removeElements: ["span"] } });
+
+ const doc = Document.parseHTMLUnsafe(
+ "<div id='allowed'><span id=forbidden></span></div>",
+ options,
+ );
+ assert_equals(doc.querySelector("#forbidden"), null);
+ assert_not_equals(doc.querySelector("#allowed"), null);
+ }, "Document.parseHTMLUnsafe: passing TrustedHTMLParserOptions directly works");
+
+ for (const value of [null, undefined, 0, 123, "foo"]) {
+ test((t) => {
+ t.add_cleanup(() => {
+ createParserOptions = (options) => options;
+ });
+ createParserOptions = (options) => value;
+ assert_throws_js(TypeError, () => {
+ Document.parseHTMLUnsafe(
+ "<div id='allowed'><span id=forbidden></span></div>",
+ );
+ });
+ }, `Document.parseHTMLUnsafe: createParserOptions returning ${JSON.stringify(value)} fails`);
+ }
+ </script>
+ </body>
+</html>
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-base-immutable.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-base-immutable.html
new file mode 100644
index 00000000000..bb443db185b
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-base-immutable.html
@@ -0,0 +1,522 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <meta charset="utf-8">
+ <title>Sanitizer API: default and base configuration immutability</title>
+ <script src="../resources/testharness.js"></script>
+ <script src="../resources/testharnessreport.js"></script>
+ <script src="./support/util.js"></script>
+</head>
+<body>
+<div id="container"></div>
+<script>
+function assert_object_equals(a, b, description) {
+ assert_equals(JSON.stringify(a), JSON.stringify(b), description);
+}
+
+test(t => {
+ const initialDefault = new Sanitizer().get();
+ const s = new Sanitizer();
+
+ // Apply all modifier methods to mutate s.
+ s.allowElement("custom-elem");
+ s.removeElement("div");
+ s.replaceElementWithChildren("p");
+ s.allowAttribute("custom-attr");
+ s.removeAttribute("dir");
+ s.allowProcessingInstruction("custom-pi");
+ s.removeProcessingInstruction("target-1");
+ s.setComments(true);
+ s.setDataAttributes(true);
+ s.removeUnsafe();
+
+ assert_not_equals(
+ JSON.stringify(s.get()),
+ JSON.stringify(initialDefault),
+ "Sanitizer instance should be modified"
+ );
+
+ // Subsequent instances must have the untouched default configuration.
+ const sAfterNoArg = new Sanitizer();
+ assert_object_equals(
+ sAfterNoArg.get(),
+ initialDefault,
+ "new Sanitizer() configuration must remain unchanged"
+ );
+
+ const sAfterDefault = new Sanitizer("default");
+ assert_object_equals(
+ sAfterDefault.get(),
+ initialDefault,
+ "new Sanitizer('default') configuration must remain unchanged"
+ );
+
+ assert_true(
+ sAfterNoArg.get().elements.some(e => e.name === "div"),
+ "div must still be in default configuration"
+ );
+ assert_false(
+ sAfterNoArg.get().elements.some(e => e.name === "custom-elem"),
+ "custom-elem must not be in default configuration"
+ );
+ assert_false(
+ "replaceWithChildrenElements" in sAfterNoArg.get(),
+ "replaceWithChildrenElements must not be in default configuration"
+ );
+ assert_true(
+ sAfterNoArg.get().attributes.some(a => a.name === "dir"),
+ "dir attribute must still be in default configuration"
+ );
+ assert_false(
+ sAfterNoArg.get().attributes.some(a => a.name === "custom-attr"),
+ "custom-attr must not be in default configuration"
+ );
+ assert_false(
+ sAfterNoArg.get().comments,
+ "comments must remain false in default configuration"
+ );
+ assert_false(
+ sAfterNoArg.get().dataAttributes,
+ "dataAttributes must remain false in default configuration"
+ );
+}, "Modifying a Sanitizer instance does not change subsequent new Sanitizer() instances");
+
+const MODIFIER_TESTS = [
+ {
+ name: "allowElement",
+ modify: s => s.allowElement("my-custom-elem"),
+ verify: config => assert_false(config.elements.some(e => e.name === "my-custom-elem"))
+ },
+ {
+ name: "removeElement",
+ modify: s => s.removeElement("div"),
+ verify: config => assert_true(config.elements.some(e => e.name === "div"))
+ },
+ {
+ name: "replaceElementWithChildren",
+ modify: s => s.replaceElementWithChildren("p"),
+ verify: config => assert_false("replaceWithChildrenElements" in config)
+ },
+ {
+ name: "allowAttribute",
+ modify: s => s.allowAttribute("my-custom-attr"),
+ verify: config => assert_false(config.attributes.some(a => a.name === "my-custom-attr"))
+ },
+ {
+ name: "removeAttribute",
+ modify: s => s.removeAttribute("dir"),
+ verify: config => assert_true(config.attributes.some(a => a.name === "dir"))
+ },
+ {
+ name: "allowProcessingInstruction",
+ modify: s => s.allowProcessingInstruction("custom-target"),
+ verify: config => assert_false(config.processingInstructions.some(pi => pi.target === "custom-target"))
+ },
+ {
+ name: "removeProcessingInstruction",
+ modify: s => s.removeProcessingInstruction("custom-target"),
+ verify: config => assert_false("removeProcessingInstructions" in config)
+ },
+ {
+ name: "setComments",
+ modify: s => s.setComments(true),
+ verify: config => assert_false(config.comments)
+ },
+ {
+ name: "setDataAttributes",
+ modify: s => s.setDataAttributes(true),
+ verify: config => assert_false(config.dataAttributes)
+ },
+ {
+ name: "removeUnsafe",
+ modify: s => s.removeUnsafe(),
+ verify: config => {
+ assert_true(config.elements.length > 0);
+ assert_true(config.attributes.length > 0);
+ assert_false("removeElements" in config);
+ assert_false("removeAttributes" in config);
+ }
+ }
+];
+
+for (const { name, modify, verify } of MODIFIER_TESTS) {
+ test(() => {
+ const s = new Sanitizer();
+ modify(s);
+ const fresh = new Sanitizer();
+ verify(fresh.get());
+ }, `${name}() on new Sanitizer() does not affect subsequent instances`);
+}
+
+test(() => {
+ const s = new Sanitizer();
+ const initial = s.get();
+ const config = s.get();
+
+ // Mutate array members.
+ config.elements.push({ name: "evil-element", namespace: "http://www.w3.org/1999/xhtml" });
+ config.attributes.push({ name: "evil-attr", namespace: null });
+ config.comments = true;
+ config.dataAttributes = true;
+
+ // Mutate nested element properties.
+ if (config.elements.length > 0) {
+ config.elements[0].name = "mutated-tag";
+ if (config.elements[0].attributes) {
+ config.elements[0].attributes.push({ name: "mutated-attr", namespace: null });
+ }
+ }
+
+ // The instance itself must not be affected.
+ assert_object_equals(
+ s.get(),
+ initial,
+ "sanitizer.get() must not be affected by mutations to previously returned config"
+ );
+
+ // Future instances must not be affected.
+ const fresh = new Sanitizer();
+ assert_object_equals(
+ fresh.get(),
+ initial,
+ "new Sanitizer().get() must not be affected by mutations to previously returned config"
+ );
+}, "Mutating the object returned by sanitizer.get() does not affect the Sanitizer or default configuration");
+
+test(() => {
+ const s = new Sanitizer();
+ const c1 = s.get();
+ const c2 = s.get();
+
+ assert_not_equals(c1, c2, "get() must return distinct objects");
+ assert_not_equals(c1.elements, c2.elements, "get().elements must return distinct arrays");
+ assert_not_equals(c1.attributes, c2.attributes, "get().attributes must return distinct arrays");
+ if (c1.elements.length > 0 && c2.elements.length > 0) {
+ assert_not_equals(
+ c1.elements[0],
+ c2.elements[0],
+ "nested element configuration dictionaries must be distinct objects"
+ );
+ }
+}, "Repeated calls to sanitizer.get() return distinct object copies");
+
+test(() => {
+ const sInit = new Sanitizer({});
+ sInit.removeUnsafe();
+ const initialBaseline = sInit.get();
+
+ // Verify baseline configuration actually has removeElements and removeAttributes.
+ assert_true(initialBaseline.removeElements.length > 0, "baseline removeElements should not be empty");
+ assert_true(initialBaseline.removeAttributes.length > 0, "baseline removeAttributes should not be empty");
+
+ // Create s1, apply baseline, then mutate s1.
+ const s1 = new Sanitizer({});
+ s1.removeUnsafe();
+ s1.allowElement("script");
+ s1.allowElement("iframe");
+ s1.allowElement({ name: "script", namespace: "http://www.w3.org/2000/svg" });
+ s1.allowElement({ name: "use", namespace: "http://www.w3.org/2000/svg" });
+ s1.allowAttribute("onclick");
+ s1.allowAttribute("onload");
+
+ // A new sanitizer invoking removeUnsafe() must still receive the complete baseline configuration.
+ const s2 = new Sanitizer({});
+ s2.removeUnsafe();
+ assert_object_equals(
+ s2.get(),
+ initialBaseline,
+ "Baseline configuration must not be changed by modifying previous instances"
+ );
+ assert_true(
+ s2.get().removeElements.some(e => e.name === "script" && e.namespace === "http://www.w3.org/1999/xhtml"),
+ "script must still be in removeElements"
+ );
+ assert_true(
+ s2.get().removeElements.some(e => e.name === "iframe" && e.namespace === "http://www.w3.org/1999/xhtml"),
+ "iframe must still be in removeElements"
+ );
+ assert_true(
+ s2.get().removeAttributes.some(a => a.name === "onclick"),
+ "onclick must still be in removeAttributes"
+ );
+}, "Modifying a Sanitizer after removeUnsafe() does not change the built-in safe baseline configuration");
+
+test(() => {
+ const s1 = new Sanitizer({});
+ s1.removeUnsafe();
+ const baselineConfig = s1.get();
+
+ // Clear lists in returned baseline config.
+ baselineConfig.removeElements.length = 0;
+ baselineConfig.removeAttributes.length = 0;
+
+ const s2 = new Sanitizer({});
+ s2.removeUnsafe();
+ assert_true(s2.get().removeElements.length > 0, "removeElements must not be emptied");
+ assert_true(s2.get().removeAttributes.length > 0, "removeAttributes must not be emptied");
+}, "Mutating config returned from baseline sanitizer does not affect subsequent removeUnsafe() calls");
+
+test(() => {
+ const inputConfig = {
+ elements: ["div", "span"],
+ attributes: ["title"]
+ };
+ const s = new Sanitizer(inputConfig);
+
+ // Mutate input dictionary after construction.
+ inputConfig.elements.push("script");
+ inputConfig.attributes.push("onclick");
+ inputConfig.elements[0] = "iframe";
+
+ const current = s.get();
+ assert_equals(current.elements.length, 2);
+ assert_false(current.elements.some(e => e.name === "script" || e.name === "iframe"));
+ assert_equals(current.attributes.length, 1);
+ assert_false(current.attributes.some(a => a.name === "onclick"));
+}, "Modifying input configuration dictionary after new Sanitizer(config) does not affect the Sanitizer");
+
+test(t => {
+ const initialDefault = new Sanitizer().get();
+ const div = document.createElement("div");
+ document.querySelector("#container").appendChild(div);
+ t.add_cleanup(() => div.remove());
+
+ // Perform sanitization using default preset implicitly and explicitly.
+ div.setHTML("<div><script>alert(1)<\/script><p onclick='alert(2)'>test</p><custom-el></custom-el></div>");
+ assert_equals(div.querySelector("script"), null, "script must be stripped by setHTML()");
+
+ assert_object_equals(
+ new Sanitizer().get(),
+ initialDefault,
+ "default configuration must be unchanged after setHTML()"
+ );
+
+ div.setHTML("<div><script>alert(1)<\/script></div>", { sanitizer: "default" });
+ assert_equals(div.querySelector("script"), null, "script must be stripped by setHTML(..., { sanitizer: 'default' })");
+
+ assert_object_equals(
+ new Sanitizer().get(),
+ initialDefault,
+ "default configuration must be unchanged after setHTML(..., { sanitizer: 'default' })"
+ );
+
+ const sInst = new Sanitizer();
+ div.setHTML("<div><script>alert(1)<\/script></div>", { sanitizer: sInst });
+ assert_object_equals(
+ sInst.get(),
+ initialDefault,
+ "Sanitizer instance passed to setHTML() must not be mutated"
+ );
+}, "Sanitization with Element.prototype.setHTML() does not change default base configuration");
+
+test(t => {
+ if (!("parseHTML" in Document)) {
+ return;
+ }
+ const initialDefault = new Sanitizer().get();
+
+ const doc = Document.parseHTML("<div><script>alert(1)<\/script><span onclick='alert(2)'>text</span></div>");
+ assert_equals(doc.querySelector("script"), null, "script must be stripped by Document.parseHTML()");
+
+ assert_object_equals(
+ new Sanitizer().get(),
+ initialDefault,
+ "default configuration must be unchanged after Document.parseHTML()"
+ );
+
+ const doc2 = Document.parseHTML("<div><script>alert(1)<\/script></div>", { sanitizer: "default" });
+ assert_equals(doc2.querySelector("script"), null);
+
+ assert_object_equals(
+ new Sanitizer().get(),
+ initialDefault,
+ "default configuration must be unchanged after Document.parseHTML(..., { sanitizer: 'default' })"
+ );
+}, "Sanitization with Document.parseHTML() does not change default base configuration");
+
+test(t => {
+ const initialDefault = new Sanitizer().get();
+ const modified = new Sanitizer();
+ modified.removeElement("div");
+ modified.allowElement("custom-tag");
+
+ const div = document.createElement("div");
+ document.querySelector("#container").appendChild(div);
+ t.add_cleanup(() => div.remove());
+
+ div.setHTML("<div>hello</div><custom-tag>world</custom-tag>", { sanitizer: modified });
+ assert_equals(div.querySelector("div"), null, "div is removed by modified sanitizer");
+ assert_not_equals(div.querySelector("custom-tag"), null, "custom-tag is allowed by modified sanitizer");
+
+ // Subsequent default setHTML() operations must use the untouched default configuration.
+ const fresh = new Sanitizer();
+ assert_object_equals(fresh.get(), initialDefault, "default configuration must remain untouched");
+
+ div.setHTML("<div>hello</div><custom-tag>world</custom-tag>");
+ assert_not_equals(div.querySelector("div"), null, "div is allowed by default setHTML()");
+ assert_equals(div.querySelector("custom-tag"), null, "custom-tag is stripped by default setHTML()");
+}, "A modified Sanitizer used in setHTML() does not affect default configuration or other Sanitizers");
+
+test(t => {
+ const s = new Sanitizer({
+ elements: [
+ { name: "div", attributes: ["id", "onclick"] },
+ "script",
+ "iframe",
+ "a"
+ ],
+ attributes: ["title", "onload"],
+ javascriptURLs: true
+ });
+ const beforeConfig = s.get();
+ assert_true(beforeConfig.elements.some(e => e.name === "script"), "script is in initial config");
+ assert_true(beforeConfig.elements.some(e => e.name === "iframe"), "iframe is in initial config");
+ assert_true(beforeConfig.attributes.some(a => a.name === "onload"), "onload is in initial config");
+ assert_true(beforeConfig.javascriptURLs, "javascriptURLs is true in initial config");
+
+ const div = document.createElement("div");
+ document.querySelector("#container").appendChild(div);
+ t.add_cleanup(() => div.remove());
+
+ div.setHTML(
+ "<div id='d' onclick='alert(1)' onload='alert(2)'><script>alert(3)<\/script><iframe id='f'></iframe><a id='link' href='javascript:alert(4)'>link</a></div>",
+ { sanitizer: s }
+ );
+
+ // setHTML() must enforce safe sanitization on the output DOM:
+ assert_not_equals(div.querySelector("#d"), null, "div is allowed");
+ assert_equals(div.querySelector("#d").getAttribute("id"), "d", "id attribute is allowed");
+ assert_false(div.querySelector("#d").hasAttribute("onclick"), "onclick must be stripped by setHTML()");
+ assert_false(div.querySelector("#d").hasAttribute("onload"), "onload must be stripped by setHTML()");
+ assert_equals(div.querySelector("script"), null, "script must be stripped by setHTML()");
+ assert_equals(div.querySelector("iframe"), null, "iframe must be stripped by setHTML()");
+
+ // s.get() must remain completely unchanged after setHTML():
+ const afterConfig = s.get();
+ assert_object_equals(
+ afterConfig,
+ beforeConfig,
+ "s.get() must be unchanged after setHTML() even when s contains unsafe entries"
+ );
+ assert_true(afterConfig.elements.some(e => e.name === "script"), "script must still be in s.get()");
+ assert_true(afterConfig.elements.some(e => e.name === "iframe"), "iframe must still be in s.get()");
+ assert_true(afterConfig.attributes.some(a => a.name === "onload"), "onload must still be in s.get()");
+ const divEntry = afterConfig.elements.find(e => e.name === "div");
+ assert_true(divEntry.attributes.some(a => a.name === "onclick"), "per-element onclick must still be in s.get()");
+ assert_true(afterConfig.javascriptURLs, "javascriptURLs must still be true in s.get()");
+}, "s.get() is unchanged after Element.prototype.setHTML() when Sanitizer has unsafe allowlist entries");
+
+test(t => {
+ const s = new Sanitizer({
+ removeElements: ["span"],
+ removeAttributes: ["data-drop"],
+ javascriptURLs: true
+ });
+ const beforeConfig = s.get();
+
+ const div = document.createElement("div");
+ document.querySelector("#container").appendChild(div);
+ t.add_cleanup(() => div.remove());
+
+ div.setHTML(
+ "<div onclick='alert(1)'><span>dropped</span><script>alert(2)<\/script><p>kept</p></div>",
+ { sanitizer: s }
+ );
+
+ assert_equals(div.querySelector("span"), null, "span is removed");
+ assert_equals(div.querySelector("script"), null, "script is stripped by setHTML()");
+ assert_false(div.querySelector("div").hasAttribute("onclick"), "onclick is stripped by setHTML()");
+ assert_not_equals(div.querySelector("p"), null, "p is kept");
+
+ assert_object_equals(
+ s.get(),
+ beforeConfig,
+ "s.get() must be unchanged after setHTML() when Sanitizer uses removeElements/removeAttributes"
+ );
+}, "s.get() is unchanged after Element.prototype.setHTML() when Sanitizer has unsafe remove-list configuration");
+
+test(t => {
+ if (!("parseHTML" in Document)) {
+ return;
+ }
+ const s = new Sanitizer({
+ elements: [
+ "html",
+ "head",
+ "body",
+ { name: "div", attributes: ["id", "onclick"] },
+ "script"
+ ],
+ attributes: ["onload"],
+ javascriptURLs: true
+ });
+ const beforeConfig = s.get();
+
+ const doc = Document.parseHTML(
+ "<div id='d' onclick='alert(1)' onload='alert(2)'><script>alert(3)<\/script></div>",
+ { sanitizer: s }
+ );
+ assert_equals(doc.querySelector("script"), null, "script is stripped by Document.parseHTML()");
+ assert_false(doc.querySelector("#d").hasAttribute("onclick"), "onclick is stripped by Document.parseHTML()");
+
+ assert_object_equals(
+ s.get(),
+ beforeConfig,
+ "s.get() must be unchanged after Document.parseHTML() when s contains unsafe entries"
+ );
+}, "s.get() is unchanged after Document.parseHTML() when Sanitizer has unsafe entries");
+
+for (const method of ["appendHTML", "prependHTML", "beforeHTML", "afterHTML", "replaceWithHTML"]) {
+ test(t => {
+ const initialDefault = new Sanitizer().get();
+ const s = new Sanitizer({
+ elements: [
+ { name: "div", attributes: ["id", "onclick"] },
+ "script",
+ "p"
+ ],
+ attributes: ["onload"]
+ });
+ const beforeConfig = s.get();
+
+ const parent = document.createElement("div");
+ document.querySelector("#container").appendChild(parent);
+ t.add_cleanup(() => parent.remove());
+
+ function getReceiver() {
+ parent.replaceChildren();
+ if (["beforeHTML", "afterHTML", "replaceWithHTML"].includes(method)) {
+ const ref = document.createElement("div");
+ parent.appendChild(ref);
+ return ref;
+ }
+ return parent;
+ }
+
+ getReceiver()[method]("<div id='d'><script>alert(1)<\/script><p onclick='alert(2)'>test</p></div>");
+ assert_equals(parent.querySelector("script"), null, `script must be stripped by ${method}()`);
+ assert_object_equals(
+ new Sanitizer().get(),
+ initialDefault,
+ `default configuration must be unchanged after ${method}()`
+ );
+
+ getReceiver()[method](
+ "<div id='d' onclick='alert(1)' onload='alert(2)'><script>alert(3)<\/script><p>kept</p></div>",
+ { sanitizer: s }
+ );
+ assert_not_equals(parent.querySelector("#d"), null, "div is allowed");
+ assert_false(parent.querySelector("#d").hasAttribute("onclick"), `onclick must be stripped by ${method}()`);
+ assert_false(parent.querySelector("#d").hasAttribute("onload"), `onload must be stripped by ${method}()`);
+ assert_equals(parent.querySelector("script"), null, `script must be stripped by ${method}()`);
+
+ assert_object_equals(
+ s.get(),
+ beforeConfig,
+ `s.get() must be unchanged after ${method}() when s contains unsafe entries`
+ );
+ }, `Sanitization with ${method}() does not change default base configuration or mutate passed Sanitizer`);
+}
+</script>
+</body>
+</html>
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-basic-filtering.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-basic-filtering.html
new file mode 100644
index 00000000000..50d036fdd7a
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-basic-filtering.html
@@ -0,0 +1,663 @@
+<!DOCTYPE html>
+<head>
+<title>Testcases from the previous Sanitizer API</title>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="support/html5lib-testcase-support.js"></script>
+<!--
+ This is a set of basic Sanitizer test cases that will use every feature in
+ the configuration at least once. This suite tries to go for completeness, and
+ not so much for tricky edge cases.
+
+ These tests deliberately stay clear of any "unsafe" features, so that we can
+ use the same test data with safe and unsafe methods.
+
+ The testcases are grouped into several groups (one group per <script> element)
+ to make them easier to use when debugging.
+-->
+<script id="text" type="html5lib-testcases">
+#data
+text
+#document
+| "text"
+
+</script>
+<script id="elements" type="html5lib-testcases">
+#data
+<div><p>Hello <b>World!</b>
+#config
+{}
+#document
+| <div>
+| <p>
+| "Hello "
+| <b>
+| "World!"
+
+#data
+<div><p>Hello <b>World!</b>
+#config
+{ "elements": ["div", "p"]}
+#document
+| <div>
+| <p>
+| "Hello "
+
+#data
+<div><p>Hello <b>World!</b>
+#config
+{ "elements": ["div", "b"]}
+#document
+| <div>
+
+#data
+<div><p>Hello <b>World!</b>
+#config
+{ "removeElements": ["b"]}
+#document
+| <div>
+| <p>
+| "Hello "
+
+#data
+<div><p>Hello <b>World!</b>
+#config
+{ "replaceWithChildrenElements": ["p"]}
+#document
+| <div>
+| "Hello "
+| <b>
+| "World!"
+
+</script>
+<script id="attributes" type="html5lib-testcases">
+#data
+<p id="hello" style="font-weight: bold">x
+#config
+{}
+#document
+| <p>
+| id="hello"
+| style="font-weight: bold"
+| "x"
+
+#data
+<p id="hello" style="font-weight: bold">x
+#config
+{ "attributes": ["style"]}
+#document
+| <p>
+| style="font-weight: bold"
+| "x"
+
+#data
+<p id="hello" style="font-weight: bold">x
+#config
+{ "removeAttributes": ["style"]}
+#document
+| <p>
+| id="hello"
+| "x"
+
+</script>
+<script id="attributes-per-element" type="html5lib-testcases">
+#data
+<div style="font-weight: bold" class="bourgeoisie">
+#config
+{ "elements": [{ "name": "div", "attributes": ["style"]}]}
+#document
+| <div>
+| style="font-weight: bold"
+
+#data
+<div style="font-weight: bold" class="bourgeoisie">
+#config
+{ "elements": [{ "name": "div", "removeAttributes": ["style"]}]}
+#document
+| <div>
+| class="bourgeoisie"
+
+</script>
+<script id="comments" type="html5lib-testcases">
+#data
+a <!-- comment --> b
+#config
+{ "comments": true}
+#document
+| "a "
+| <!-- comment -->
+| " b"
+
+#data
+a <!-- comment --> b
+#config
+{ "comments": false}
+#document
+| "a b"
+
+</script>
+<script id="dataAttributes" type="html5lib-testcases">
+#data
+<p data-x="1" data-y="2" data-z="3">
+#config
+{
+ "attributes": [],
+ "dataAttributes": true
+}
+#document
+| <p>
+| data-x="1"
+| data-y="2"
+| data-z="3"
+
+#data
+<p data-x="1" data-y="2" data-z="3">
+#config
+{
+ "attributes": [],
+ "dataAttributes": false
+}
+#document
+| <p>
+
+#data
+<p data-x="1" data-y="2" data-z="3">
+#config
+{
+ "attributes": [ "data-x" ],
+ "dataAttributes": false
+}
+#document
+| <p>
+| data-x="1"
+
+#description
+"data-" prefix with an empty suffix is still covered by dataAttributes
+#data
+<div data-="x"></div>
+#config
+{
+ "attributes": [],
+ "dataAttributes": true
+}
+#document
+| <div>
+| data-="x"
+
+#description
+"data-" prefix with an empty suffix is still covered by dataAttributes
+#data
+<div data-="x"></div>
+#config
+{
+ "attributes": [],
+ "dataAttributes": false
+}
+#document
+| <div>
+
+</script>
+<script id="namespaces" type="html5lib-testcases">
+#data
+<svg><rect></svg><math><mi>x
+#document
+| <svg svg>
+| <svg rect>
+| <math math>
+| <math mi>
+| "x"
+
+#data
+<svg><rect>
+#config
+{ "elements": [{ "name": "svg", "namespace": "http://www.w3.org/2000/svg" }]}
+#document
+| <svg svg>
+
+#data
+<svg><rect>
+#config
+{ "elements": [{ "name": "svg", "namespace": "http://www.w3.org/2000/svg" },
+ { "name": "rect", "namespace": "http://www.w3.org/2000/svg" }]}
+#document
+| <svg svg>
+| <svg rect>
+
+#data
+<svg><rect>
+#config
+{ "removeElements": [{ "name": "rect", "namespace": "http://www.w3.org/2000/svg" }]}
+#document
+| <svg svg>
+
+#data
+<math><mi>x
+#config
+{ "elements": [{ "name": "math", "namespace": "http://www.w3.org/1998/Math/MathML" }]}
+#document
+| <math math>
+
+#data
+<math><mi>x
+#config
+{ "elements": [{ "name": "math", "namespace": "http://www.w3.org/1998/Math/MathML" },
+ { "name": "mi", "namespace": "http://www.w3.org/1998/Math/MathML" }]}
+#document
+| <math math>
+| <math mi>
+| "x"
+
+#data
+<math><mi>x
+#config
+{ "removeElements": [{ "name": "mi", "namespace": "http://www.w3.org/1998/Math/MathML" }] }
+#document
+| <math math>
+
+#data
+<svg xml:space="default" xlink:href="about:blank" xmlns:foo="barspace">
+#config
+{ "elements": [{ "name": "svg", "namespace": "http://www.w3.org/2000/svg" }]}
+#document
+| <svg svg>
+| xml space="default"
+| xlink href="about:blank"
+| xmlns:foo="barspace"
+
+#data
+<svg xml:space="default" xlink:href="about:blank" xmlns:foo="barspace">
+#config
+{ "elements": [{ "name": "svg", "namespace": "http://www.w3.org/2000/svg" }],
+ "attributes": [{"name": "space", "namespace": "http://www.w3.org/XML/1998/namespace" }] }
+#document
+| <svg svg>
+| xml space="default"
+
+#data
+<svg xml:space="default" xlink:href="about:blank" xmlns:foo="barspace">
+#config
+{ "elements": [{ "name": "svg", "namespace": "http://www.w3.org/2000/svg" }],
+ "attributes": [{"name": "href", "namespace": "http://www.w3.org/1999/xlink" }] }
+#document
+| <svg svg>
+| xlink href="about:blank"
+
+#data
+<svg>Hello</svg>
+#config
+{ "elements": ["svg"] }
+#document
+
+#data
+<svg>Hello</svg>
+#config
+{ "elements": [{ "name": "svg", "namespace": "http://www.w3.org/2000/svg" }] }
+#document
+| <svg svg>
+| "Hello"
+
+#data
+<math>Hello</math>
+#config
+{ "elements": ["math"] }
+#document
+
+#data
+<math>Hello</math>
+#config
+{ "elements": [{ "name": "math", "namespace": "http://www.w3.org/2000/svg" }] }
+#document
+
+#data
+<math>Hello</math>
+#config
+{ "elements": [{ "name": "math", "namespace": "http://www.w3.org/1998/Math/MathML" }] }
+#document
+| <math math>
+| "Hello"
+
+#data
+<p style="bla"></p>
+#config
+{ "attributes": [{ "name": "style" }],
+ "elements": ["p", { "name": "svg", "namespace": "http://www.w3.org/2000/svg" }] }
+#document
+| <p>
+| style="bla"
+
+#data
+<p href="bla"></p>
+#config
+{ "attributes": [{ "name": "href" }],
+ "elements": ["p", { "name": "svg", "namespace": "http://www.w3.org/2000/svg" }] }
+#document
+| <p>
+| href="bla"
+
+</script>
+<!--
+ In HTML content, the HTML parser parses "xlink:href" as an attribute named
+ "xlink:href" in the null namespace.
+-->
+<script id="xlink-href-html-content" type="html5lib-testcases">
+#data
+<p xlink:href="bla"></p>
+#config
+{ "attributes": [{ "name": "xlink:href" }],
+ "elements": ["p", { "name": "svg", "namespace": "http://www.w3.org/2000/svg" }] }
+#document
+| <p>
+| xlink:href="bla"
+
+#data
+<p xlink:href="bla"></p>
+#config
+{ "attributes": [{ "name": "href", "namespace": "http://www.w3.org/1999/xlink" }],
+ "elements": ["p", { "name": "svg", "namespace": "http://www.w3.org/2000/svg" }] }
+#document
+| <p>
+
+#data
+<p href='bla'></p>
+#config
+{ "attributes": [{ "name": "href", "namespace": "http://www.w3.org/1999/xlink" }],
+ "elements": ["p", { "name": "svg", "namespace": "http://www.w3.org/2000/svg" }] }
+#document
+| <p>
+
+#data
+<p xlink:href='bla'></p>
+#config
+{ "attributes": [{ "name": "href" }],
+ "elements": ["p", { "name": "svg", "namespace": "http://www.w3.org/2000/svg" }] }
+#document
+| <p>
+
+</script>
+<!--
+ For "foreign elements" like <svg>, the HTML parser parses "xlink:href" as an
+ attribute named "href" in the XLink namespace.
+-->
+<script id="xlink-href-foreign-content" type="html5lib-testcases">
+#data
+<svg xlink:href="bla"></svg>
+#config
+{ "attributes": [{ "name": "xlink:href" }],
+ "elements": ["p", { "name": "svg", "namespace": "http://www.w3.org/2000/svg" }] }
+#document
+| <svg svg>
+
+#data
+<svg xlink:href="bla"></svg>
+#config
+{ "attributes": [{ "name": "href", "namespace": "http://www.w3.org/1999/xlink" }],
+ "elements": ["p", { "name": "svg", "namespace": "http://www.w3.org/2000/svg" }] }
+#document
+| <svg svg>
+| xlink href="bla"
+
+#data
+<svg href='bla'></svg>
+#config
+{ "attributes": [{ "name": "href", "namespace": "http://www.w3.org/1999/xlink" }],
+ "elements": ["p", { "name": "svg", "namespace": "http://www.w3.org/2000/svg" }] }
+#document
+| <svg svg>
+
+#data
+<svg xlink:href='bla'></svg>
+#config
+{ "attributes": [{ "name": "href" }],
+ "elements": ["p", { "name": "svg", "namespace": "http://www.w3.org/2000/svg" }] }
+#document
+| <svg svg>
+
+#description
+Namespaced attribute xlink:href inside SVG tree
+#data
+<svg><a xlink:href="bla"></a></svg>
+#config
+{ "elements": [
+ { "name": "svg", "namespace": "http://www.w3.org/2000/svg" },
+ { "name": "a", "namespace": "http://www.w3.org/2000/svg",
+ "attributes": [{ "name": "href", "namespace": "http://www.w3.org/1999/xlink" }] }] }
+#document
+| <svg svg>
+| <svg a>
+| xlink href="bla"
+
+</script>
+<script id="defaults-with-attributes-per-element" type="html5lib-testcases">
+#data
+<div start=1 value=5 lang=en><ol start=1 value=5 lang=en><li start=1 value=5 lang=en>xx
+#config
+"default"
+#document
+| <div>
+| lang="en"
+| <ol>
+| lang="en"
+| start="1"
+| <li>
+| lang="en"
+| value="5"
+| "xx"
+
+</script>
+<!--
+ Names are case-sensitive. Most element and attribute names are lower-cased,
+ but "foreign content" like SVG and MathML have some mixed-cased names. Check
+ this is supported.
+-->
+<script id="mixed-case-element-names" type="html5lib-testcases">
+#data
+<svg><feBlend></feBlend></svg>
+#config
+{ "elements": [{ "name": "svg", "namespace": "http://www.w3.org/2000/svg" },
+ { "name": "feBlend", "namespace": "http://www.w3.org/2000/svg" }] }
+#document
+| <svg svg>
+| <svg feBlend>
+
+#data
+<svg><feColorMatrix></feColorMatrix></svg>
+#config
+{ "elements": [{ "name": "svg", "namespace": "http://www.w3.org/2000/svg" },
+ { "name": "feColorMatrix", "namespace": "http://www.w3.org/2000/svg" }] }
+#document
+| <svg svg>
+| <svg feColorMatrix>
+
+#data
+<svg><textPath></textPath></svg>
+#config
+{ "elements": [{ "name": "svg", "namespace": "http://www.w3.org/2000/svg" },
+ { "name": "textPath", "namespace": "http://www.w3.org/2000/svg" }] }
+#document
+| <svg svg>
+| <svg textPath>
+
+</script>
+<!--
+ A name whose case does not match the parsed name matches nothing.
+ Configurations are never case-folded.
+ https://html.spec.whatwg.org/#parsing-main-inforeign
+-->
+<script id="element-name-case-mismatch" type="html5lib-testcases">
+#data
+<div>text</div>
+#config
+{ "elements": [{ "name": "svg", "namespace": "http://www.w3.org/2000/svg" },
+ { "name": "DIV", "namespace": "http://www.w3.org/2000/svg" },
+ { "name": "DIV" }] }
+#document
+
+#data
+<svg><feBlend></feBlend></svg>
+#config
+{ "elements": [{ "name": "svg", "namespace": "http://www.w3.org/2000/svg" },
+ { "name": "feblend", "namespace": "http://www.w3.org/2000/svg" },
+ { "name": "feblend" }] }
+#document
+| <svg svg>
+
+#data
+<svg><feBlend></feBlend></svg>
+#config
+{ "elements": [{ "name": "svg", "namespace": "http://www.w3.org/2000/svg" },
+ { "name": "FEBLEND", "namespace": "http://www.w3.org/2000/svg" },
+ { "name": "FEBLEND" }] }
+#document
+| <svg svg>
+
+</script>
+<!--
+ Attribute names are not case folded. The parser adjusts "viewbox" to
+ "viewBox" in foreign content, so only the adjusted name matches.
+ https://html.spec.whatwg.org/#adjust-svg-attributes
+
+ The default configuration lists <marker> and the adjusted attribute names,
+ so they survive.
+-->
+<script id="adjusted-svg-attribute-names" type="html5lib-testcases">
+#data
+<svg><marker viewbox="0 0 1 1"></marker></svg>
+#config
+{ "elements": [{ "name": "svg", "namespace": "http://www.w3.org/2000/svg" },
+ { "name": "marker", "namespace": "http://www.w3.org/2000/svg" }],
+ "attributes": ["viewBox"] }
+#document
+| <svg svg>
+| <svg marker>
+| viewBox="0 0 1 1"
+
+#data
+<svg><marker viewbox="0 0 1 1"></marker></svg>
+#config
+{ "elements": [{ "name": "svg", "namespace": "http://www.w3.org/2000/svg" },
+ { "name": "marker", "namespace": "http://www.w3.org/2000/svg" }],
+ "attributes": ["viewbox"] }
+#document
+| <svg svg>
+| <svg marker>
+
+#data
+<svg><marker viewbox="0 0 1 1"></marker></svg>
+#config
+{ "elements": [{ "name": "svg", "namespace": "http://www.w3.org/2000/svg" },
+ { "name": "marker", "namespace": "http://www.w3.org/2000/svg" }],
+ "attributes": ["VIEWBOX"] }
+#document
+| <svg svg>
+| <svg marker>
+
+#description
+Default config keeps case-adjusted SVG attribute names
+#data
+<svg><marker viewbox="0 0 1 1" refx="1" markerwidth="2"></marker></svg>
+#document
+| <svg svg>
+| <svg marker>
+| markerWidth="2"
+| refX="1"
+| viewBox="0 0 1 1"
+
+</script>
+<script id="unknown" type="html5lib-testcases">
+#description
+Unknown element names get blocked without being allowed.
+#data
+<hello><world>
+#config
+{ "elements": ["b", "em"] }
+#document
+
+#description
+Unknown element names pass when allowed.
+#data
+<hello><world>
+#config
+{ "elements": ["hello", "world"] }
+#document
+| <hello>
+| <world>
+
+#description
+Unknown attribute names get blocked without being allowed.
+#data
+<b hello='1' world>
+#config
+{ "attributes": ["name", "href"] }
+#document
+| <b>
+
+#description
+Unknown attribute names pass when allowed.
+#data
+<b hello='1' world>
+#config
+{ "attributes": ["hello", "world"] }
+#document
+| <b>
+| hello="1"
+| world=""
+
+</script>
+<script>
+for(const group of
+ document.querySelectorAll("script[type='html5lib-testcases']")) {
+ parse_html5lib_testcases(group.textContent).forEach((testcase, index) => {
+ let config = undefined;
+ if (testcase.config) {
+ config = { sanitizer: JSON.parse(testcase.config) };
+ }
+
+ const name = `${group.id}/${index}, "${testcase.data}"` +
+ (testcase.description ? `: ${testcase.description}` : "");
+
+ test(_ => {
+ const div = document.createElement("div");
+ div.setHTML(testcase.data, config);
+ assert_testcase(div, testcase);
+ }, `setHTML testcase ${name}`);
+ test(_ => {
+ const div = document.createElement("div");
+ div.setHTMLUnsafe(testcase.data, config);
+ assert_testcase(div, testcase);
+ }, `setHTMLUnsafe testcase ${name}`);
+
+ test(_ => {
+ const div = document.createElement("div");
+ const shadowRoot = div.attachShadow({ mode: "open" });
+ shadowRoot .setHTML(testcase.data, config);
+ assert_testcase(shadowRoot, testcase);
+ }, `ShadowRoot.setHTML testcase ${name}`);
+ test(_ => {
+ const div = document.createElement("div");
+ const shadowRoot = div.attachShadow({ mode: "open" });
+ shadowRoot .setHTMLUnsafe(testcase.data, config);
+ assert_testcase(shadowRoot, testcase);
+ }, `ShadowRoot.setHTMLUnsafe testcase ${name}`);
+
+ // parseHTML and parseHTMLUnsafe need to allow "html" and "body" for these
+ // tests to be useful. Update the config, if necessary.
+ if (config && config["sanitizer"] && config["sanitizer"]["elements"]) {
+ config["sanitizer"] = new Sanitizer(config["sanitizer"]);
+ config["sanitizer"].allowElement("body");
+ config["sanitizer"].allowElement("html");
+ }
+
+ test(_ => {
+ assert_testcase(
+ Document.parseHTML(testcase.data, config).body, testcase);
+ }, `parseHTML testcase ${name}`);
+ test(_ => {
+ assert_testcase(
+ Document.parseHTMLUnsafe(testcase.data, config).body, testcase);
+ }, `parseHTMLUnsafe testcase ${name}`);
+ });
+}
+</script>
+</head>
+<body>
+</body>
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-boolean-defaults.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-boolean-defaults.html
new file mode 100644
index 00000000000..73227dd4a55
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-boolean-defaults.html
@@ -0,0 +1,139 @@
+<!DOCTYPE html>
+<html>
+<head>
+<title>Test boolean defaults in config per PR #254</title>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+</head>
+<body>
+<script>
+// Test cases extracted from : https://github.com/WICG/sanitizer-api/pull/254
+//
+// These are somewhat redundant with tests in sanitizer-config.tentative.html,
+// so maybe we can long-term merge them together.
+
+// Comments.
+test(t => {
+ function try_unsafe(config) {
+ const div = document.createElement("div");
+ div.setHTMLUnsafe("<!--bla-->", config)
+ return div.innerHTML.includes("<!--");
+ }
+ function try_safe(config) {
+ const div = document.createElement("div");
+ div.setHTML("<!--bla-->", config)
+ return div.innerHTML.includes("<!--");
+ }
+
+ // Parameter-less constructor.
+ assert_false(new Sanitizer().get().comments);
+ assert_true(try_unsafe());
+ assert_false(try_safe());
+
+ // Constructed from empty dictionary.
+ assert_true(new Sanitizer({}).get().comments);
+ assert_true(try_unsafe({sanitizer:{}}));
+ assert_false(try_safe({sanitizer:{}}));
+
+ // Explicitly set to true.
+ assert_true(new Sanitizer({comments: true}).get().comments);
+ assert_true(try_unsafe({sanitizer:{comments:true}}));
+ assert_true(try_safe({sanitizer:{comments:true}}));
+
+ // Explicitly set to false.
+ assert_false(new Sanitizer({comments: false}).get().comments);
+ assert_false(try_unsafe({sanitizer:{comments:false}}));
+ assert_false(try_safe({sanitizer:{comments:false}}));
+}, "comments");
+
+// Data Attributes:
+test(t => {
+ function try_unsafe(config) {
+ const div = document.createElement("div");
+ div.setHTMLUnsafe("<div data-foo='bar'>", config)
+ return div.innerHTML.includes("data-foo");
+ }
+ function try_safe(config) {
+ const div = document.createElement("div");
+ div.setHTML("<div data-foo='bar'>", config)
+ return div.innerHTML.includes("data-foo");
+ }
+
+ // Parameter-less constructor.
+ assert_false(new Sanitizer().get().dataAttributes);
+ assert_true(try_unsafe());
+ assert_false(try_safe());
+
+ // Constructed from empty dictionary: Canonicalization removes dataAttributes.
+ assert_equals(undefined, new Sanitizer({}).get().dataAttributes);
+ assert_true(try_unsafe({sanitizer:{}}));
+ assert_true(try_safe({sanitizer:{}}));
+
+ // Explicitly set to true.
+ const dataAttributes_is_true = {attributes:[], dataAttributes: true};
+ assert_true(new Sanitizer(dataAttributes_is_true).get().dataAttributes);
+ assert_true(try_unsafe({sanitizer:dataAttributes_is_true}));
+ assert_true(try_safe({sanitizer:dataAttributes_is_true}));
+
+ // Explicitly set to false.
+ const dataAttributes_is_false = {attributes:[], dataAttributes: false};
+ assert_false(new Sanitizer(dataAttributes_is_false).get().dataAttributes);
+ assert_false(try_unsafe({sanitizer:dataAttributes_is_false}));
+ assert_false(try_safe({sanitizer:dataAttributes_is_false}));
+
+ // dataAttributes not set.
+ // (This case is different from the "empty dictionary" case above, because
+ // constructing from an empty dictionary adds a removeAttributes key and thus
+ // dataAttributes is removed, too. But this case has an explicit attributes
+ // key and thus dataAttributes should be added by the canonicalization.)
+ const dataAttributes_is_not_set = {attributes:[]};
+ assert_true(new Sanitizer(dataAttributes_is_not_set).get().dataAttributes);
+ assert_true(try_unsafe({sanitizer:dataAttributes_is_not_set}));
+ assert_false(try_safe({sanitizer:dataAttributes_is_not_set}));
+}, "data attributes");
+
+// Javascript URLs:
+test(t => {
+ function try_unsafe(config) {
+ const div = document.createElement("div");
+ div.setHTMLUnsafe("<a href='javascript:alert(1)'>", config);
+ return div.innerHTML.includes("javascript:");
+ }
+ function try_safe(config) {
+ const div = document.createElement("div");
+ div.setHTML("<a href='javascript:alert(1)'>", config);
+ return div.innerHTML.includes("javascript:");
+ }
+
+ // Parameter-less constructor.
+ assert_false(new Sanitizer().get().javascriptURLs);
+ assert_true(try_unsafe());
+ assert_false(try_safe());
+ assert_false(try_unsafe({sanitizer: new Sanitizer()}));
+ assert_false(try_safe({sanitizer: new Sanitizer()}));
+
+ // Constructed from empty dictionary.
+ assert_true(new Sanitizer({}).get().javascriptURLs);
+ assert_true(try_unsafe({sanitizer:{}}));
+ assert_false(try_safe({sanitizer:{}}));
+ assert_true(try_unsafe({sanitizer: new Sanitizer({})}));
+ assert_false(try_safe({sanitizer: new Sanitizer({})}));
+
+ // Explicitly set to true.
+ assert_true(new Sanitizer({javascriptURLs: true}).get().javascriptURLs);
+ assert_true(try_unsafe({sanitizer:{javascriptURLs:true}}));
+ assert_false(try_safe({sanitizer:{javascriptURLs:true}}));
+ assert_true(try_unsafe({sanitizer: new Sanitizer({javascriptURLs: true})}));
+ assert_false(try_safe({sanitizer: new Sanitizer({javascriptURLs: true})}));
+
+ // Explicitly set to false.
+ assert_false(new Sanitizer({javascriptURLs: false}).get().javascriptURLs);
+ assert_false(try_unsafe({sanitizer:{javascriptURLs:false}}));
+ assert_false(try_safe({sanitizer:{javascriptURLs:false}}));
+ assert_false(try_unsafe({sanitizer: new Sanitizer({javascriptURLs: false})}));
+ assert_false(try_safe({sanitizer: new Sanitizer({javascriptURLs: false})}));
+}, "javascript URLs");
+
+</script>
+</body>
+</html>
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-config.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-config.html
new file mode 100644
index 00000000000..aacfaba1564
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-config.html
@@ -0,0 +1,578 @@
+<!DOCTYPE html>
+<html>
+<head>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="./support/util.js"></script>
+</head>
+<body>
+<script>
+test(t => {
+ let s = new Sanitizer();
+ assert_true(s instanceof Sanitizer);
+}, "Sanitizer constructor without config.");
+
+test(t => {
+ let s = new Sanitizer({});
+ assert_true(s instanceof Sanitizer);
+}, "Sanitizer constructor with empty config.");
+
+test(t => {
+ let s = new Sanitizer(null);
+ assert_true(s instanceof Sanitizer);
+}, "Sanitizer constructor with null as config.");
+
+test(t => {
+ let s = new Sanitizer(undefined);
+ assert_true(s instanceof Sanitizer);
+}, "Sanitizer constructor with undefined as config.");
+
+test(t => {
+ let s = new Sanitizer({testConfig: [1,2,3], attr: ["test", "i", "am"]});
+ assert_true(s instanceof Sanitizer);
+}, "Sanitizer constructor with config ignore unknown values.");
+
+test(t => {
+ assert_false(new Sanitizer().get().comments);
+ assert_true(new Sanitizer({}).get().comments);
+ assert_true(new Sanitizer({comments: true}).get().comments);
+ assert_false(new Sanitizer({comments: false}).get().comments);
+
+ let s = new Sanitizer();
+ s.setComments(true);
+ assert_true(s.get().comments);
+ s.setComments(false);
+ assert_false(s.get().comments);
+ s.setComments("abc");
+ assert_true(s.get().comments);
+}, "SanitizerConfig comments field.");
+
+test(t => {
+ assert_false(new Sanitizer().get().dataAttributes);
+ assert_true(new Sanitizer({ attributes: [] }).get().dataAttributes);
+ assert_false('dataAttributes' in new Sanitizer({}).get());
+ assert_false('dataAttributes' in new Sanitizer({ removeAttributes: [] }).get());
+ assert_true(new Sanitizer({ attributes: [], dataAttributes: true}).get().dataAttributes);
+ assert_false(new Sanitizer({ attributes: [], dataAttributes: false}).get().dataAttributes);
+
+ let s = new Sanitizer();
+ s.setDataAttributes(true);
+ assert_true(s.get().dataAttributes);
+ s.setDataAttributes(false);
+ assert_false(s.get().dataAttributes);
+ s.setDataAttributes("abc");
+ assert_true(s.get().dataAttributes);
+}, "SanitizerConfig dataAttributes field.");
+
+test(t => {
+ assert_false(new Sanitizer().get().javascriptURLs);
+ assert_true(new Sanitizer({}).get().javascriptURLs);
+ assert_true(new Sanitizer({javascriptURLs: true}).get().javascriptURLs);
+ assert_false(new Sanitizer({javascriptURLs: false}).get().javascriptURLs);
+ assert_true(new Sanitizer({javascriptURLs: undefined}).get().javascriptURLs);
+ assert_false(new Sanitizer({javascriptURLs: null}).get().javascriptURLs);
+
+ let s = new Sanitizer();
+ assert_false(s.setJavascriptURLs(false));
+ assert_true(s.setJavascriptURLs(true));
+ assert_true(s.get().javascriptURLs);
+ assert_false(s.setJavascriptURLs(true));
+ assert_true(s.setJavascriptURLs(false));
+ assert_false(s.get().javascriptURLs);
+ assert_true(s.setJavascriptURLs("abc"));
+ assert_true(s.get().javascriptURLs);
+ assert_false(s.setJavascriptURLs(1));
+ assert_true(s.setJavascriptURLs(0));
+ assert_false(s.get().javascriptURLs);
+}, "SanitizerConfig javascriptURLs field.");
+
+function assert_object_equals(a, b, description) {
+ assert_equals(JSON.stringify(a), JSON.stringify(b), description);
+}
+
+function test_normalization(key, value, expected) {
+ test(t => {
+ let config = Object.fromEntries([[key, [value]]]);
+ let s = new Sanitizer(config);
+ assert_equals(s.get()[key].length, 1);
+ assert_object_equals(s.get()[key][0], expected);
+ }, `SanitizerConfig, normalization: ${key}: [${JSON.stringify(value)}]`);
+}
+
+for (key of ["elements", "removeElements", "replaceWithChildrenElements"]) {
+ // The canonical form of elements always includes an empty removeAttributes list.
+ let extra = key == "elements" ? {removeAttributes: []} : {};
+
+ test_normalization(key,
+ "div",
+ {name: "div", namespace: "http://www.w3.org/1999/xhtml", ...extra});
+ test_normalization(key,
+ {name: "b"},
+ {name: "b", namespace: "http://www.w3.org/1999/xhtml", ...extra});
+ test_normalization(key,
+ {name: "b", namespace: null},
+ {name: "b", namespace: null, ...extra});
+ test_normalization(key,
+ {name: "b", namespace: ""},
+ {name: "b", namespace: null, ...extra});
+ test_normalization(key,
+ {name: "p", namespace: "http://www.w3.org/1999/xhtml"},
+ {name: "p", namespace: "http://www.w3.org/1999/xhtml", ...extra});
+ test_normalization(key,
+ {name: "bla", namespace: "http://fantasy.org/namespace"},
+ {name: "bla", namespace: "http://fantasy.org/namespace", ...extra});
+}
+for (key of ["processingInstructions", "removeProcessingInstructions"]) {
+ test_normalization(key,
+ "target-1",
+ {target: "target-1"});
+ test_normalization(key,
+ {target: "target-1"},
+ {target: "target-1"});
+}
+for (key of ["attributes", "removeAttributes"]) {
+ test_normalization(key,
+ "href",
+ {name: "href", namespace: null});
+ test_normalization(key,
+ {name: "href", namespace: null},
+ {name: "href", namespace: null});
+ // https://wicg.github.io/sanitizer-api/#canonicalize-a-sanitizer-name, step 5
+ test_normalization(key,
+ {name: "href", namespace: ""},
+ {name: "href", namespace: null});
+ test_normalization(key,
+ {name: "href", namespace: "https://www.w3.org/1999/xlink"},
+ {name: "href", namespace: "https://www.w3.org/1999/xlink"});
+}
+
+test(t => {
+ let s = new Sanitizer({elements: ["div", "p"]});
+ assert_equals(s.get().elements.length, 2);
+ s.allowElement("bla");
+ assert_equals(s.get().elements.length, 3);
+ s.removeElement({name: "div"});
+ assert_equals(s.get().elements.length, 2);
+ s.replaceElementWithChildren({name: "p", namespace: "http://www.w3.org/1999/xhtml"});
+ assert_equals(s.get().elements.length, 1);
+ assert_object_equals(s.get().elements[0],
+ {name: "bla", namespace: "http://www.w3.org/1999/xhtml", removeAttributes: []});
+}, "Test elements addition.");
+
+test(t => {
+ let s = new Sanitizer({removeElements: ["div", "p"]});
+ assert_equals(s.get().removeElements.length, 2);
+ s.removeElement("bla");
+ assert_equals(s.get().removeElements.length, 3);
+ s.replaceElementWithChildren({name: "div"});
+ assert_equals(s.get().removeElements.length, 2);
+ s.allowElement({name: "p", namespace: "http://www.w3.org/1999/xhtml"});
+ assert_equals(s.get().removeElements.length, 1);
+ assert_object_equals(s.get().removeElements[0],
+ {name: "bla", namespace: "http://www.w3.org/1999/xhtml"});
+}, "Test elements removal.");
+
+test(t => {
+ let s = new Sanitizer({replaceWithChildrenElements: ["div", "p"]});
+ assert_equals(s.get().replaceWithChildrenElements.length, 2);
+ s.replaceElementWithChildren("bla");
+ assert_equals(s.get().replaceWithChildrenElements.length, 3);
+ s.allowElement({name: "div"});
+ assert_equals(s.get().replaceWithChildrenElements.length, 2);
+ s.removeElement({name: "p", namespace: "http://www.w3.org/1999/xhtml"});
+ assert_equals(s.get().replaceWithChildrenElements.length, 1);
+ assert_object_equals(s.get().replaceWithChildrenElements[0],
+ {name: "bla", namespace: "http://www.w3.org/1999/xhtml"});
+}, "Test elements replacewithchildren.");
+
+test(t => {
+ let s = new Sanitizer({processingInstructions: ["target-1", "target-2"]});
+ assert_equals(s.get().processingInstructions.length, 2);
+ s.allowProcessingInstruction("target-3");
+ assert_equals(s.get().processingInstructions.length, 3);
+ s.removeProcessingInstruction({target: "target-4"});
+ assert_equals(s.get().processingInstructions.length, 3);
+ s.removeProcessingInstruction({target: "target-1"});
+ assert_equals(s.get().processingInstructions.length, 2);
+ s.removeProcessingInstruction({target: "target-2"});
+ assert_equals(s.get().processingInstructions.length, 1);
+ assert_object_equals(s.get().processingInstructions[0],
+ {target: "target-3"});
+}, "Test processingInstructions addition.");
+
+test(t => {
+ let s = new Sanitizer({removeProcessingInstructions: ["target-1", "target-2"]});
+ assert_equals(s.get().removeProcessingInstructions.length, 2);
+ s.removeProcessingInstruction("target-3");
+ assert_equals(s.get().removeProcessingInstructions.length, 3);
+ s.allowProcessingInstruction({target: "target-1"});
+ assert_equals(s.get().removeProcessingInstructions.length, 2);
+ s.allowProcessingInstruction({target: "target-2"});
+ assert_equals(s.get().removeProcessingInstructions.length, 1);
+ assert_object_equals(s.get().removeProcessingInstructions[0],
+ {target: "target-3"});
+}, "Test processingInstructions removal.");
+
+test(t => {
+ let s = new Sanitizer({attributes: ["href", "src"]});
+ assert_equals(s.get().attributes.length, 2);
+ s.allowAttribute("id");
+ assert_equals(s.get().attributes.length, 3);
+ s.removeAttribute({name: "href", namespace: "https://www.w3.org/1999/xlink" });
+ assert_equals(s.get().attributes.length, 3);
+ s.removeAttribute({name: "href"});
+ assert_equals(s.get().attributes.length, 2);
+ s.removeAttribute({name: "src", namespace: null});
+ assert_equals(s.get().attributes.length, 1);
+ assert_object_equals(s.get().attributes[0],
+ {name: "id", namespace: null});
+}, "Test attribute addition.");
+
+test(t => {
+ let s = new Sanitizer({removeAttributes: ["href", "src"]});
+ assert_equals(s.get().removeAttributes.length, 2);
+ s.removeAttribute("id");
+ assert_equals(s.get().removeAttributes.length, 3);
+ s.allowAttribute({name: "href", namespace: "https://www.w3.org/1999/xlink" });
+ assert_equals(s.get().removeAttributes.length, 3);
+ s.allowAttribute({name: "href"});
+ assert_equals(s.get().removeAttributes.length, 2);
+ s.allowAttribute({name: "src", namespace: null});
+ assert_equals(s.get().removeAttributes.length, 1);
+ assert_object_equals(s.get().removeAttributes[0],
+ {name: "id", namespace: null});
+}, "Test attribute removal.");
+
+test(t => {
+ let s = new Sanitizer({elements: [{name: "div", attributes: ["href", "src"]}]});
+ assert_equals(s.get().elements.length, 1);
+ assert_true("attributes" in s.get().elements[0]);
+ assert_false("removeAttributes" in s.get().elements[0]);
+ assert_equals(s.get().elements[0].attributes.length, 2);
+
+ s.allowElement({name: "div", namespace: "http://www.w3.org/1999/xhtml",
+ attributes: ["class"]});
+ assert_equals(s.get().elements[0].attributes.length, 1);
+ assert_object_equals(s.get().elements[0].attributes[0],
+ { name: "class", namespace: null });
+}, "Test attribute-per-element sets (i.e. overwrites).");
+
+test(t => {
+ let s = new Sanitizer({elements: [{name: "div", removeAttributes: ["href", "src"]}]});
+ assert_equals(s.get().elements.length, 1);
+ assert_false("attributes" in s.get().elements[0]);
+ assert_true("removeAttributes" in s.get().elements[0]);
+ assert_equals(s.get().elements[0].removeAttributes.length, 2);
+
+ s.allowElement({name: "div", namespace: "http://www.w3.org/1999/xhtml",
+ removeAttributes: ["class"]});
+ assert_equals(s.get().elements[0].removeAttributes.length, 1);
+ assert_object_equals(s.get().elements[0].removeAttributes[0],
+ { name: "class", namespace: null });
+}, "Test removeAttribute-per-element sets (i.e. overwrites).");
+
+// Tests for valid/invalid config parameter combinations.
+// 1. The config has either an elements or a removeElements key, but not both.
+test(() => {
+ assert_throws_js(TypeError, () => {
+ new Sanitizer({ elements: [], removeElements: [] });
+ });
+}, "Both elements and removeElements should not be allowed.");
+
+// 2. The config has either an attributes or a removeAttributes key, but not both.
+test(() => {
+ assert_throws_js(TypeError, () => {
+ new Sanitizer({ attributes: [], removeAttributes: [] });
+ });
+}, "Both attributes and removeAttributes should not be allowed.");
+
+// The config has either a processingInstructions or a removeProcessingInstructions key, but not both.
+test(() => {
+ assert_throws_js(TypeError, () => {
+ new Sanitizer({ processingInstructions: [], removeProcessingInstructions: [] });
+ });
+}, "Both processingInstructions and removeProcessingInstructions should not be allowed.");
+
+// 3. Assert: All SanitizerElementNamespaceWithAttributes, SanitizerElementNamespace, and SanitizerAttributeNamespace items in config are canonical, meaning they have been run through canonicalize a sanitizer element or canonicalize a sanitizer attribute, as appropriate.
+// This is tested in the sanitizer-config test file.
+
+// 4. None of config[elements], config[removeElements], config[replaceWithChildrenElements], config[attributes], or config[removeAttributes], if they exist, has duplicates.
+const DUPLICATE_NAMES = [
+ ["", ""],
+ ["abc", "abc"],
+ ["data-xyz", "data-xyz"],
+ ["abc", {name: "abc"}],
+ [{name: "abc", namespace: "xyz"}, {name: "abc", namespace: "xyz"}],
+ [{name: "abc", namespace: ""}, {name: "abc", namespace: null}]
+];
+
+// NOTE: Elements and attributes have different default namespaces.
+const DUPLICATE_ELEMENT_NAMES = DUPLICATE_NAMES.concat([
+ ["abc", {name: "abc", namespace: "http://www.w3.org/1999/xhtml"}],
+ [{name: "abc"}, {name: "abc", namespace: "http://www.w3.org/1999/xhtml"}]
+]);
+
+const DUPLICATE_ATTRIBUTE_NAMES = DUPLICATE_NAMES.concat([
+ ["abc", {name: "abc", namespace: null}],
+ [{name: "abc"}, {name: "abc", namespace: null}]
+]);
+
+test(() => {
+ for (let names of DUPLICATE_ELEMENT_NAMES) {
+ assert_throws_js(TypeError, () => {
+ new Sanitizer({ elements: names });
+ });
+ }
+}, "config[elements] should not allow duplicates");
+
+test(() => {
+ for (let names of DUPLICATE_ELEMENT_NAMES) {
+ assert_throws_js(TypeError, () => {
+ new Sanitizer({ removeElements: names });
+ });
+ }
+}, "config[removeElements] should not allow duplicates");
+
+test(() => {
+ for (let names of DUPLICATE_ELEMENT_NAMES) {
+ assert_throws_js(TypeError, () => {
+ new Sanitizer({ replaceWithChildrenElements: names });
+ });
+ }
+}, "config[replaceWithChildrenElements] should not allow duplicates");
+
+test(() => {
+ for (let names of DUPLICATE_ATTRIBUTE_NAMES) {
+ assert_throws_js(TypeError, () => {
+ new Sanitizer({ attributes: names });
+ });
+ }
+}, "config[attributes] should not allow duplicates");
+
+test(() => {
+ for (let names of DUPLICATE_ATTRIBUTE_NAMES) {
+ assert_throws_js(TypeError, () => {
+ new Sanitizer({ removeAttributes: names });
+ });
+ }
+}, "config[removeAttributes] should not allow duplicates");
+
+// None of config[processingInstructions] or config[removeProcessingInstructions], if they exist, has duplicate targets.
+const DUPLICATE_TARGETS = [
+ ["", ""],
+ ["abc", "abc"],
+ ["data-xyz", "data-xyz"],
+ ["abc", {target: "abc"}],
+ [{target: "abc"}, {target: "abc"}]
+];
+
+test(() => {
+ for (let targets of DUPLICATE_TARGETS) {
+ assert_throws_js(TypeError, () => {
+ new Sanitizer({ processingInstructions: targets });
+ });
+ }
+}, "config[processingInstructions] should not allow duplicate targets");
+
+test(() => {
+ for (let targets of DUPLICATE_TARGETS) {
+ assert_throws_js(TypeError, () => {
+ new Sanitizer({ removeProcessingInstructions: targets });
+ });
+ }
+}, "config[removeProcessingInstructions] should not allow duplicate targets");
+
+// 11.1. For each element of config["replaceWithChildrenElements"]:
+// 11.1.1. If the built-in non-replaceable elements list contains element, then return false.
+test(() => {
+ for (let element of NON_REPLACEABLE_ELEMENTS) {
+ assert_throws_js(TypeError, () => {
+ new Sanitizer({
+ replaceWithChildrenElements: [element],
+ });
+ });
+ }
+}, "config[replaceWithChildrenElements] should not allow non-replaceable elements");
+
+// 5. If both config[elements] and config[replaceWithChildrenElements] exist, then the intersection of config[elements] and config[replaceWithChildrenElements] is empty.
+test(() => {
+ for (let [a, b] of DUPLICATE_ELEMENT_NAMES) {
+ assert_throws_js(TypeError, () => {
+ new Sanitizer({
+ elements: [a],
+ replaceWithChildrenElements: [b],
+ });
+ });
+ }
+}, "config[elements] and config[replaceWithChildrenElements] should not intersect");
+
+// 6. If both config[removeElements] and config[replaceWithChildrenElements] exist, then the intersection of config[removeElements] and config[replaceWithChildrenElements] is empty.
+test(() => {
+ for (let [a, b] of DUPLICATE_ELEMENT_NAMES) {
+ assert_throws_js(TypeError, () => {
+ new Sanitizer({
+ removeElements: [a],
+ replaceWithChildrenElements: [b],
+ });
+ });
+ }
+}, "config[removeElements] and config[replaceWithChildrenElements] should not intersect");
+
+// 7. If config[attributes] exists:
+// 7.1. If config[elements] exists:
+// 7.1.1. For each element of config[elements]:
+// 7.1.1.1. Neither element[attributes] nor element[removeAttributes], if they exist, has duplicates.
+test(() => {
+ for (let names of DUPLICATE_ATTRIBUTE_NAMES) {
+ assert_throws_js(TypeError, () => {
+ new Sanitizer({
+ attributes: [],
+ elements: [{ name: "div", attributes: names }],
+ });
+ });
+ }
+}, "Duplicates in element[attributes] with config[attributes] should not be allowed.");
+
+test(() => {
+ for (let names of DUPLICATE_ATTRIBUTE_NAMES) {
+ assert_throws_js(TypeError, () => {
+ new Sanitizer({
+ attributes: [],
+ elements: [{ name: "div", removeAttributes: names }],
+ });
+ });
+ }
+}, "Duplicates in element[removeAttributes] with config[attributes] should not be allowed.");
+
+// 7.1.1.2. The intersection of config[attributes] and element[attributes] with default « » is empty.
+test(() => {
+ for (let [a, b] of DUPLICATE_ATTRIBUTE_NAMES) {
+ assert_throws_js(TypeError, () => {
+ new Sanitizer({
+ attributes: [a],
+ elements: [{ name: "div", attributes: [b] }],
+ });
+ });
+ }
+}, "config[attributes] and element[attributes] should not intersect.");
+
+// 7.1.1.3. element[removeAttributes] with default « » is a subset of config[attributes].
+test(() => {
+ assert_throws_js(TypeError, () => {
+ new Sanitizer({
+ attributes: ["class"],
+ elements: [{ name: "div", removeAttributes: ["title"] }],
+ });
+ });
+}, "element[removeAttributes] should be a subset of config[attributes]");
+
+// 7.1.1.4. If dataAttributes exists and dataAttributes is true:
+// 7.1.1.4.1. element[attributes] does not contain a custom data attribute.
+test(() => {
+ assert_throws_js(TypeError, () => {
+ new Sanitizer({
+ attributes: [],
+ dataAttributes: true,
+ elements: [{ name: "div", attributes: ["data-foo"] }],
+ });
+ });
+
+ assert_throws_js(TypeError, () => {
+ new Sanitizer({
+ attributes: [],
+ dataAttributes: true,
+ elements: [{ name: "div", attributes: [{ name: "data-bar", namespace: null }] }],
+ });
+ });
+}, "element[attributes] with a data attribute must not co-exist with config[dataAttributes] set to true.");
+
+// 7.2. If dataAttributes is true:
+// 7.2.1. config[attributes] does not contain a custom data attribute.
+test(() => {
+ assert_throws_js(TypeError, () => {
+ new Sanitizer({
+ attributes: ["data-bar"],
+ dataAttributes: true,
+ });
+ });
+
+ assert_throws_js(TypeError, () => {
+ new Sanitizer({
+ attributes: [{ name: "data-foo", namespace: null }],
+ dataAttributes: true,
+ });
+ });
+}, "config[attributes] with a data attribute must not co-exist with config[dataAttributes] set to true.");
+
+// 8. If config[removeAttributes] exists:
+// 8.1. If config[elements] exists, then for each element of config[elements]:
+// 8.1.1. Not both element[attributes] and element[removeAttributes] exist.
+test(() => {
+ assert_throws_js(TypeError, () => {
+ new Sanitizer({
+ removeAttributes: [],
+ elements: [{ name: "div", attributes: [], removeAttributes: [] }],
+ });
+ });
+}, "element[attributes] and element[removeAttributes] should not both exist with config[removeAttributes].");
+
+// 8.1.2. Neither element[attributes] nor element[removeAttributes], if they exist, has duplicates.
+test(() => {
+ for (let names of DUPLICATE_ATTRIBUTE_NAMES) {
+ assert_throws_js(TypeError, () => {
+ new Sanitizer({
+ removeAttributes: [],
+ elements: [{ name: "div", attributes: names }],
+ });
+ });
+ }
+}, "Duplicates in element[attributes] with config[removeAttributes] should not be allowed.");
+
+test(() => {
+ for (let names of DUPLICATE_ATTRIBUTE_NAMES) {
+ assert_throws_js(TypeError, () => {
+ new Sanitizer({
+ removeAttributes: [],
+ elements: [{ name: "div", removeAttributes: names }],
+ });
+ });
+ }
+}, "Duplicates in element[removeAttributes] with config[removeAttributes] should not be allowed.");
+
+// 8.1.3. The intersection of config[removeAttributes] and element[attributes] with default « » is empty.
+test(() => {
+ for (let [a, b] of DUPLICATE_ATTRIBUTE_NAMES) {
+ assert_throws_js(TypeError, () => {
+ new Sanitizer({
+ removeAttributes: [a],
+ elements: [{ name: "div", attributes: [b] }],
+ });
+ });
+ }
+}, "config[removeAttributes] and element[attributes] should not intersect.");
+
+// 8.1.4. The intersection of config[removeAttributes] and element[removeAttributes] with default « » is empty.
+test(() => {
+ for (let [a, b] of DUPLICATE_ATTRIBUTE_NAMES) {
+ assert_throws_js(TypeError, () => {
+ new Sanitizer({
+ removeAttributes: [a],
+ elements: [{ name: "div", removeAttributes: [b] }],
+ });
+ });
+ }
+}, "config[removeAttributes] and element[removeAttributes] should not intersect.");
+
+// 8.2. config[dataAttributes] does not exist.
+test(() => {
+ assert_throws_js(TypeError, () => {
+ new Sanitizer({ removeAttributes: [], dataAttributes: true });
+ });
+
+ assert_throws_js(TypeError, () => {
+ new Sanitizer({ removeAttributes: [], dataAttributes: false });
+ });
+}, "Can not use config[dataAttributes] and config[removeAttributes] together.");
+</script>
+</body>
+</html>
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-custom-elements-constructor.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-custom-elements-constructor.html
new file mode 100644
index 00000000000..1767ce63a37
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-custom-elements-constructor.html
@@ -0,0 +1,94 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <script src="../resources/testharness.js"></script>
+ <script src="../resources/testharnessreport.js"></script>
+</head>
+<body>
+<div id="container"></div>
+<script>
+let constructor_called = false;
+let connectedCallback_called = false;
+
+class DisallowedElement extends HTMLElement {
+ constructor() {
+ super();
+ constructor_called = true;
+ }
+ connectedCallback() {
+ connectedCallback_called = true;
+ }
+}
+customElements.define("disallowed-element", DisallowedElement);
+
+const registry = new CustomElementRegistry();
+registry.define("disallowed-element-scoped", class extends HTMLElement {
+ constructor() {
+ super();
+ constructor_called = true;
+ }
+ connectedCallback() {
+ connectedCallback_called = true;
+ }
+});
+
+function assert_removed(method, sanitizer, scoped = false) {
+ constructor_called = connectedCallback_called = false;
+
+ let d = document.createElement("div");
+ document.body.append(d);
+
+ let target = d;
+ if (scoped) {
+ target = d.attachShadow({ mode: "open", customElementRegistry: registry });
+ }
+
+ const tag = scoped ? "disallowed-element-scoped" : "disallowed-element";
+
+ if (method === "setHTML") {
+ target.setHTML(`<${tag}></${tag}>`, { sanitizer });
+ } else if (method === "setHTMLUnsafe") {
+ target.setHTMLUnsafe(`<${tag}></${tag}>`, { sanitizer });
+ }
+
+ assert_equals(target.innerHTML, ``);
+ assert_false(constructor_called, "Constructor should not be called");
+ assert_false(connectedCallback_called, "ConnectedCallback should not be called");
+
+ d.remove();
+}
+
+for (const method of ["setHTML", "setHTMLUnsafe"]) {
+ for (const config of [
+ { name: "removeElements", options: { removeElements: ["disallowed-element"] }, scopedOptions: { removeElements: ["disallowed-element-scoped"] } },
+ { name: "allowElements", options: { elements: ["div"] }, scopedOptions: { elements: ["div"] } },
+ { name: "replaceWithChildrenElements", options: { replaceWithChildrenElements: ["disallowed-element"] }, scopedOptions: { replaceWithChildrenElements: ["disallowed-element-scoped"] } }
+ ]) {
+ test(t => {
+ assert_removed(method, config.options, false);
+ }, `${method} blocks CE constructor when element is dropped by explicit sanitizer config (${config.name})`);
+
+ test(t => {
+ assert_removed(method, config.scopedOptions, true);
+ }, `${method} blocks CE constructor in scoped registry when element is dropped by explicit sanitizer config (${config.name})`);
+ }
+}
+
+for (const method of ["setHTML", "setHTMLUnsafe"]) {
+ test(t => {
+ constructor_called = connectedCallback_called = false;
+ const d = document.createElement("div");
+ document.body.append(d);
+ t.add_cleanup(() => d.remove());
+ const shadow = d.attachShadow({ mode: "open", customElementRegistry: registry });
+ shadow[method]("<disallowed-element-scoped></disallowed-element-scoped>",
+ { sanitizer: { elements: ["disallowed-element-scoped"] } });
+ assert_equals(shadow.firstChild.localName, "disallowed-element-scoped");
+ assert_true(constructor_called, "Constructor should be called");
+ assert_true(connectedCallback_called, "ConnectedCallback should be called");
+ }, `${method} constructs an allowed CE from the scoped registry`);
+}
+
+</script>
+</body>
+</html>
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-custom-elements-is.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-custom-elements-is.html
new file mode 100644
index 00000000000..cfffb7c9f28
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-custom-elements-is.html
@@ -0,0 +1,95 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <script src="../resources/testharness.js"></script>
+ <script src="../resources/testharnessreport.js"></script>
+</head>
+<body>
+<script>
+
+let constructor_called = false;
+let connectedCallback_called = false;
+
+class FooBarElement extends HTMLDivElement {
+ constructor() {
+ super();
+ constructor_called = true;
+ }
+
+ connectedCallback() {
+ connectedCallback_called = true;
+ }
+}
+
+customElements.define("foo-bar", FooBarElement, { extends: "div" });
+
+function assert_removed(sanitizer) {
+ constructor_called = connectedCallback_called = false;
+
+ let d = document.createElement("div");
+ document.body.append(d);
+ d.setHTML(`<div is="foo-bar">hello</div>`, { sanitizer } );
+ assert_equals(d.innerHTML, `<div>hello</div>`);
+ assert_false(d.firstChild.hasAttribute("is"));
+ assert_true(d.firstChild.matches(":defined"));
+
+ assert_false(constructor_called);
+ assert_false(connectedCallback_called);
+
+ d.remove();
+}
+
+test(t => {
+ assert_removed("default");
+}, "The is= attribute is removed by the default sanitizer config.");
+
+test(t => {
+ assert_removed({ removeAttributes: ["is"] });
+}, "The is= attribute is removed by the global removeAttributes");
+
+test(t => {
+ assert_removed({ elements: [{ name: "div", removeAttributes: ["is"] }], removeAttributes: [] });
+}, "The is= attribute is removed by the local removeAttributes");
+
+test(t => {
+ assert_removed({ elements: [{ name: "div", attributes: [] }], attributes: [] });
+}, "The is= attribute is removed by the local missing attributes");
+
+function assert_kept(sanitizer) {
+ constructor_called = connectedCallback_called = false;
+
+ let d = document.createElement("div");
+ document.body.append(d);
+ d.setHTML(`<div is="foo-bar">hello</div>`, { sanitizer });
+ assert_equals(d.innerHTML, `<div is="foo-bar">hello</div>`);
+ assert_true(d.firstChild.hasAttribute("is"));
+ assert_true(d.firstChild.matches(":defined"));
+
+ // "is" is re-created even after removing the attribute.
+ d.firstChild.removeAttribute("is");
+ assert_equals(d.innerHTML, `<div is="foo-bar">hello</div>`);
+
+ assert_true(constructor_called);
+ assert_true(connectedCallback_called);
+
+ d.remove();
+}
+
+test(t => {
+ assert_kept({ })
+}, "The is= attribute is kept when allowed with an empty config.");
+
+test(t => {
+ assert_kept({ attributes: ["is"] })
+}, "The is= attribute is kept when allowed by global attributes.");
+
+test(t => {
+ assert_kept({ removeAttributes: [] })
+}, "The is= attribute is kept when allowed by global removeAttributes.");
+
+test(t => {
+ assert_kept({ elements: [{ name: "div", attributes: ["is"] }], attributes: [] });
+}, "The is= attribute is kept when allowed by local attributes.");
+</script>
+</body>
+</html>
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-default-config.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-default-config.html
new file mode 100644
index 00000000000..0c68e30c79e
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-default-config.html
@@ -0,0 +1,1370 @@
+<!DOCTYPE html>
+<html>
+<head>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="./support/util.js"></script>
+</head>
+<body>
+<script>
+test(() => {
+ let d = new Sanitizer();
+
+ // https://wicg.github.io/sanitizer-api/#built-in-safe-default-configuration
+ //
+ assert_config(d.get(), {
+ "elements": [
+ {
+ "name": "math",
+ "namespace": "http://www.w3.org/1998/Math/MathML",
+ "attributes": []
+ },
+ {
+ "name": "merror",
+ "namespace": "http://www.w3.org/1998/Math/MathML",
+ "attributes": []
+ },
+ {
+ "name": "mfrac",
+ "namespace": "http://www.w3.org/1998/Math/MathML",
+ "attributes": []
+ },
+ {
+ "name": "mi",
+ "namespace": "http://www.w3.org/1998/Math/MathML",
+ "attributes": []
+ },
+ {
+ "name": "mmultiscripts",
+ "namespace": "http://www.w3.org/1998/Math/MathML",
+ "attributes": []
+ },
+ {
+ "name": "mn",
+ "namespace": "http://www.w3.org/1998/Math/MathML",
+ "attributes": []
+ },
+ {
+ "name": "mo",
+ "namespace": "http://www.w3.org/1998/Math/MathML",
+ "attributes": [
+ {
+ "name": "fence",
+ "namespace": null
+ },
+ {
+ "name": "form",
+ "namespace": null
+ },
+ {
+ "name": "largeop",
+ "namespace": null
+ },
+ {
+ "name": "lspace",
+ "namespace": null
+ },
+ {
+ "name": "maxsize",
+ "namespace": null
+ },
+ {
+ "name": "minsize",
+ "namespace": null
+ },
+ {
+ "name": "movablelimits",
+ "namespace": null
+ },
+ {
+ "name": "rspace",
+ "namespace": null
+ },
+ {
+ "name": "separator",
+ "namespace": null
+ },
+ {
+ "name": "stretchy",
+ "namespace": null
+ },
+ {
+ "name": "symmetric",
+ "namespace": null
+ }
+ ]
+ },
+ {
+ "name": "mover",
+ "namespace": "http://www.w3.org/1998/Math/MathML",
+ "attributes": [
+ {
+ "name": "accent",
+ "namespace": null
+ }
+ ]
+ },
+ {
+ "name": "mpadded",
+ "namespace": "http://www.w3.org/1998/Math/MathML",
+ "attributes": [
+ {
+ "name": "depth",
+ "namespace": null
+ },
+ {
+ "name": "height",
+ "namespace": null
+ },
+ {
+ "name": "lspace",
+ "namespace": null
+ },
+ {
+ "name": "voffset",
+ "namespace": null
+ },
+ {
+ "name": "width",
+ "namespace": null
+ }
+ ]
+ },
+ {
+ "name": "mphantom",
+ "namespace": "http://www.w3.org/1998/Math/MathML",
+ "attributes": []
+ },
+ {
+ "name": "mprescripts",
+ "namespace": "http://www.w3.org/1998/Math/MathML",
+ "attributes": []
+ },
+ {
+ "name": "mroot",
+ "namespace": "http://www.w3.org/1998/Math/MathML",
+ "attributes": []
+ },
+ {
+ "name": "mrow",
+ "namespace": "http://www.w3.org/1998/Math/MathML",
+ "attributes": []
+ },
+ {
+ "name": "ms",
+ "namespace": "http://www.w3.org/1998/Math/MathML",
+ "attributes": []
+ },
+ {
+ "name": "mspace",
+ "namespace": "http://www.w3.org/1998/Math/MathML",
+ "attributes": [
+ {
+ "name": "depth",
+ "namespace": null
+ },
+ {
+ "name": "height",
+ "namespace": null
+ },
+ {
+ "name": "width",
+ "namespace": null
+ }
+ ]
+ },
+ {
+ "name": "msqrt",
+ "namespace": "http://www.w3.org/1998/Math/MathML",
+ "attributes": []
+ },
+ {
+ "name": "mstyle",
+ "namespace": "http://www.w3.org/1998/Math/MathML",
+ "attributes": []
+ },
+ {
+ "name": "msub",
+ "namespace": "http://www.w3.org/1998/Math/MathML",
+ "attributes": []
+ },
+ {
+ "name": "msubsup",
+ "namespace": "http://www.w3.org/1998/Math/MathML",
+ "attributes": []
+ },
+ {
+ "name": "msup",
+ "namespace": "http://www.w3.org/1998/Math/MathML",
+ "attributes": []
+ },
+ {
+ "name": "mtable",
+ "namespace": "http://www.w3.org/1998/Math/MathML",
+ "attributes": []
+ },
+ {
+ "name": "mtd",
+ "namespace": "http://www.w3.org/1998/Math/MathML",
+ "attributes": [
+ {
+ "name": "columnspan",
+ "namespace": null
+ },
+ {
+ "name": "rowspan",
+ "namespace": null
+ }
+ ]
+ },
+ {
+ "name": "mtext",
+ "namespace": "http://www.w3.org/1998/Math/MathML",
+ "attributes": []
+ },
+ {
+ "name": "mtr",
+ "namespace": "http://www.w3.org/1998/Math/MathML",
+ "attributes": []
+ },
+ {
+ "name": "munder",
+ "namespace": "http://www.w3.org/1998/Math/MathML",
+ "attributes": [
+ {
+ "name": "accentunder",
+ "namespace": null
+ }
+ ]
+ },
+ {
+ "name": "munderover",
+ "namespace": "http://www.w3.org/1998/Math/MathML",
+ "attributes": [
+ {
+ "name": "accent",
+ "namespace": null
+ },
+ {
+ "name": "accentunder",
+ "namespace": null
+ }
+ ]
+ },
+ {
+ "name": "semantics",
+ "namespace": "http://www.w3.org/1998/Math/MathML",
+ "attributes": []
+ },
+ {
+ "name": "a",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": [
+ {
+ "name": "href",
+ "namespace": null
+ },
+ {
+ "name": "hreflang",
+ "namespace": null
+ },
+ {
+ "name": "type",
+ "namespace": null
+ }
+ ]
+ },
+ {
+ "name": "abbr",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "address",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "article",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "aside",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "b",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "bdi",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "bdo",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "blockquote",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": [
+ {
+ "name": "cite",
+ "namespace": null
+ }
+ ]
+ },
+ {
+ "name": "body",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "br",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "caption",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "cite",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "code",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "col",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": [
+ {
+ "name": "span",
+ "namespace": null
+ }
+ ]
+ },
+ {
+ "name": "colgroup",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": [
+ {
+ "name": "span",
+ "namespace": null
+ }
+ ]
+ },
+ {
+ "name": "data",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": [
+ {
+ "name": "value",
+ "namespace": null
+ }
+ ]
+ },
+ {
+ "name": "dd",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "del",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": [
+ {
+ "name": "cite",
+ "namespace": null
+ },
+ {
+ "name": "datetime",
+ "namespace": null
+ }
+ ]
+ },
+ {
+ "name": "dfn",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "div",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "dl",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "dt",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "em",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "figcaption",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "figure",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "footer",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "h1",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "h2",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "h3",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "h4",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "h5",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "h6",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "head",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "header",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "hgroup",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "hr",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "html",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "i",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "ins",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": [
+ {
+ "name": "cite",
+ "namespace": null
+ },
+ {
+ "name": "datetime",
+ "namespace": null
+ }
+ ]
+ },
+ {
+ "name": "kbd",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "li",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": [
+ {
+ "name": "value",
+ "namespace": null
+ }
+ ]
+ },
+ {
+ "name": "main",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "mark",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "menu",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "nav",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "ol",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": [
+ {
+ "name": "reversed",
+ "namespace": null
+ },
+ {
+ "name": "start",
+ "namespace": null
+ },
+ {
+ "name": "type",
+ "namespace": null
+ }
+ ]
+ },
+ {
+ "name": "p",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "pre",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "q",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "rp",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "rt",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "ruby",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "s",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "samp",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "search",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "section",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "small",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "span",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "strong",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "sub",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "sup",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "table",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "tbody",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "td",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": [
+ {
+ "name": "colspan",
+ "namespace": null
+ },
+ {
+ "name": "headers",
+ "namespace": null
+ },
+ {
+ "name": "rowspan",
+ "namespace": null
+ }
+ ]
+ },
+ {
+ "name": "tfoot",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "th",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": [
+ {
+ "name": "abbr",
+ "namespace": null
+ },
+ {
+ "name": "colspan",
+ "namespace": null
+ },
+ {
+ "name": "headers",
+ "namespace": null
+ },
+ {
+ "name": "rowspan",
+ "namespace": null
+ },
+ {
+ "name": "scope",
+ "namespace": null
+ }
+ ]
+ },
+ {
+ "name": "thead",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "time",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": [
+ {
+ "name": "datetime",
+ "namespace": null
+ }
+ ]
+ },
+ {
+ "name": "title",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "tr",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "u",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "ul",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "var",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "wbr",
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "attributes": []
+ },
+ {
+ "name": "a",
+ "namespace": "http://www.w3.org/2000/svg",
+ "attributes": [
+ {
+ "name": "href",
+ "namespace": null
+ },
+ {
+ "name": "hreflang",
+ "namespace": null
+ },
+ {
+ "name": "type",
+ "namespace": null
+ }
+ ]
+ },
+ {
+ "name": "circle",
+ "namespace": "http://www.w3.org/2000/svg",
+ "attributes": [
+ {
+ "name": "cx",
+ "namespace": null
+ },
+ {
+ "name": "cy",
+ "namespace": null
+ },
+ {
+ "name": "pathLength",
+ "namespace": null
+ },
+ {
+ "name": "r",
+ "namespace": null
+ }
+ ]
+ },
+ {
+ "name": "defs",
+ "namespace": "http://www.w3.org/2000/svg",
+ "attributes": []
+ },
+ {
+ "name": "desc",
+ "namespace": "http://www.w3.org/2000/svg",
+ "attributes": []
+ },
+ {
+ "name": "ellipse",
+ "namespace": "http://www.w3.org/2000/svg",
+ "attributes": [
+ {
+ "name": "cx",
+ "namespace": null
+ },
+ {
+ "name": "cy",
+ "namespace": null
+ },
+ {
+ "name": "pathLength",
+ "namespace": null
+ },
+ {
+ "name": "rx",
+ "namespace": null
+ },
+ {
+ "name": "ry",
+ "namespace": null
+ }
+ ]
+ },
+ {
+ "name": "foreignObject",
+ "namespace": "http://www.w3.org/2000/svg",
+ "attributes": [
+ {
+ "name": "height",
+ "namespace": null
+ },
+ {
+ "name": "width",
+ "namespace": null
+ },
+ {
+ "name": "x",
+ "namespace": null
+ },
+ {
+ "name": "y",
+ "namespace": null
+ }
+ ]
+ },
+ {
+ "name": "g",
+ "namespace": "http://www.w3.org/2000/svg",
+ "attributes": []
+ },
+ {
+ "name": "line",
+ "namespace": "http://www.w3.org/2000/svg",
+ "attributes": [
+ {
+ "name": "pathLength",
+ "namespace": null
+ },
+ {
+ "name": "x1",
+ "namespace": null
+ },
+ {
+ "name": "x2",
+ "namespace": null
+ },
+ {
+ "name": "y1",
+ "namespace": null
+ },
+ {
+ "name": "y2",
+ "namespace": null
+ }
+ ]
+ },
+ {
+ "name": "marker",
+ "namespace": "http://www.w3.org/2000/svg",
+ "attributes": [
+ {
+ "name": "markerHeight",
+ "namespace": null
+ },
+ {
+ "name": "markerUnits",
+ "namespace": null
+ },
+ {
+ "name": "markerWidth",
+ "namespace": null
+ },
+ {
+ "name": "orient",
+ "namespace": null
+ },
+ {
+ "name": "preserveAspectRatio",
+ "namespace": null
+ },
+ {
+ "name": "refX",
+ "namespace": null
+ },
+ {
+ "name": "refY",
+ "namespace": null
+ },
+ {
+ "name": "viewBox",
+ "namespace": null
+ }
+ ]
+ },
+ {
+ "name": "metadata",
+ "namespace": "http://www.w3.org/2000/svg",
+ "attributes": []
+ },
+ {
+ "name": "path",
+ "namespace": "http://www.w3.org/2000/svg",
+ "attributes": [
+ {
+ "name": "d",
+ "namespace": null
+ },
+ {
+ "name": "pathLength",
+ "namespace": null
+ }
+ ]
+ },
+ {
+ "name": "polygon",
+ "namespace": "http://www.w3.org/2000/svg",
+ "attributes": [
+ {
+ "name": "pathLength",
+ "namespace": null
+ },
+ {
+ "name": "points",
+ "namespace": null
+ }
+ ]
+ },
+ {
+ "name": "polyline",
+ "namespace": "http://www.w3.org/2000/svg",
+ "attributes": [
+ {
+ "name": "pathLength",
+ "namespace": null
+ },
+ {
+ "name": "points",
+ "namespace": null
+ }
+ ]
+ },
+ {
+ "name": "rect",
+ "namespace": "http://www.w3.org/2000/svg",
+ "attributes": [
+ {
+ "name": "height",
+ "namespace": null
+ },
+ {
+ "name": "pathLength",
+ "namespace": null
+ },
+ {
+ "name": "rx",
+ "namespace": null
+ },
+ {
+ "name": "ry",
+ "namespace": null
+ },
+ {
+ "name": "width",
+ "namespace": null
+ },
+ {
+ "name": "x",
+ "namespace": null
+ },
+ {
+ "name": "y",
+ "namespace": null
+ }
+ ]
+ },
+ {
+ "name": "svg",
+ "namespace": "http://www.w3.org/2000/svg",
+ "attributes": [
+ {
+ "name": "height",
+ "namespace": null
+ },
+ {
+ "name": "preserveAspectRatio",
+ "namespace": null
+ },
+ {
+ "name": "viewBox",
+ "namespace": null
+ },
+ {
+ "name": "width",
+ "namespace": null
+ },
+ {
+ "name": "x",
+ "namespace": null
+ },
+ {
+ "name": "y",
+ "namespace": null
+ }
+ ]
+ },
+ {
+ "name": "text",
+ "namespace": "http://www.w3.org/2000/svg",
+ "attributes": [
+ {
+ "name": "dx",
+ "namespace": null
+ },
+ {
+ "name": "dy",
+ "namespace": null
+ },
+ {
+ "name": "lengthAdjust",
+ "namespace": null
+ },
+ {
+ "name": "rotate",
+ "namespace": null
+ },
+ {
+ "name": "textLength",
+ "namespace": null
+ },
+ {
+ "name": "x",
+ "namespace": null
+ },
+ {
+ "name": "y",
+ "namespace": null
+ }
+ ]
+ },
+ {
+ "name": "textPath",
+ "namespace": "http://www.w3.org/2000/svg",
+ "attributes": [
+ {
+ "name": "lengthAdjust",
+ "namespace": null
+ },
+ {
+ "name": "method",
+ "namespace": null
+ },
+ {
+ "name": "path",
+ "namespace": null
+ },
+ {
+ "name": "side",
+ "namespace": null
+ },
+ {
+ "name": "spacing",
+ "namespace": null
+ },
+ {
+ "name": "startOffset",
+ "namespace": null
+ },
+ {
+ "name": "textLength",
+ "namespace": null
+ }
+ ]
+ },
+ {
+ "name": "title",
+ "namespace": "http://www.w3.org/2000/svg",
+ "attributes": []
+ },
+ {
+ "name": "tspan",
+ "namespace": "http://www.w3.org/2000/svg",
+ "attributes": [
+ {
+ "name": "dx",
+ "namespace": null
+ },
+ {
+ "name": "dy",
+ "namespace": null
+ },
+ {
+ "name": "lengthAdjust",
+ "namespace": null
+ },
+ {
+ "name": "rotate",
+ "namespace": null
+ },
+ {
+ "name": "textLength",
+ "namespace": null
+ },
+ {
+ "name": "x",
+ "namespace": null
+ },
+ {
+ "name": "y",
+ "namespace": null
+ }
+ ]
+ }
+ ],
+ "processingInstructions": [],
+ "attributes": [
+ {
+ "name": "alignment-baseline",
+ "namespace": null
+ },
+ {
+ "name": "baseline-shift",
+ "namespace": null
+ },
+ {
+ "name": "clip-path",
+ "namespace": null
+ },
+ {
+ "name": "clip-rule",
+ "namespace": null
+ },
+ {
+ "name": "color",
+ "namespace": null
+ },
+ {
+ "name": "color-interpolation",
+ "namespace": null
+ },
+ {
+ "name": "cursor",
+ "namespace": null
+ },
+ {
+ "name": "dir",
+ "namespace": null
+ },
+ {
+ "name": "direction",
+ "namespace": null
+ },
+ {
+ "name": "display",
+ "namespace": null
+ },
+ {
+ "name": "displaystyle",
+ "namespace": null
+ },
+ {
+ "name": "dominant-baseline",
+ "namespace": null
+ },
+ {
+ "name": "fill",
+ "namespace": null
+ },
+ {
+ "name": "fill-opacity",
+ "namespace": null
+ },
+ {
+ "name": "fill-rule",
+ "namespace": null
+ },
+ {
+ "name": "font-family",
+ "namespace": null
+ },
+ {
+ "name": "font-size",
+ "namespace": null
+ },
+ {
+ "name": "font-size-adjust",
+ "namespace": null
+ },
+ {
+ "name": "font-stretch",
+ "namespace": null
+ },
+ {
+ "name": "font-style",
+ "namespace": null
+ },
+ {
+ "name": "font-variant",
+ "namespace": null
+ },
+ {
+ "name": "font-weight",
+ "namespace": null
+ },
+ {
+ "name": "lang",
+ "namespace": null
+ },
+ {
+ "name": "letter-spacing",
+ "namespace": null
+ },
+ {
+ "name": "marker-end",
+ "namespace": null
+ },
+ {
+ "name": "marker-mid",
+ "namespace": null
+ },
+ {
+ "name": "marker-start",
+ "namespace": null
+ },
+ {
+ "name": "mathbackground",
+ "namespace": null
+ },
+ {
+ "name": "mathcolor",
+ "namespace": null
+ },
+ {
+ "name": "mathsize",
+ "namespace": null
+ },
+ {
+ "name": "opacity",
+ "namespace": null
+ },
+ {
+ "name": "paint-order",
+ "namespace": null
+ },
+ {
+ "name": "pointer-events",
+ "namespace": null
+ },
+ {
+ "name": "scriptlevel",
+ "namespace": null
+ },
+ {
+ "name": "shape-rendering",
+ "namespace": null
+ },
+ {
+ "name": "stop-color",
+ "namespace": null
+ },
+ {
+ "name": "stop-opacity",
+ "namespace": null
+ },
+ {
+ "name": "stroke",
+ "namespace": null
+ },
+ {
+ "name": "stroke-dasharray",
+ "namespace": null
+ },
+ {
+ "name": "stroke-dashoffset",
+ "namespace": null
+ },
+ {
+ "name": "stroke-linecap",
+ "namespace": null
+ },
+ {
+ "name": "stroke-linejoin",
+ "namespace": null
+ },
+ {
+ "name": "stroke-miterlimit",
+ "namespace": null
+ },
+ {
+ "name": "stroke-opacity",
+ "namespace": null
+ },
+ {
+ "name": "stroke-width",
+ "namespace": null
+ },
+ {
+ "name": "text-anchor",
+ "namespace": null
+ },
+ {
+ "name": "text-decoration",
+ "namespace": null
+ },
+ {
+ "name": "text-overflow",
+ "namespace": null
+ },
+ {
+ "name": "text-rendering",
+ "namespace": null
+ },
+ {
+ "name": "title",
+ "namespace": null
+ },
+ {
+ "name": "transform",
+ "namespace": null
+ },
+ {
+ "name": "transform-origin",
+ "namespace": null
+ },
+ {
+ "name": "unicode-bidi",
+ "namespace": null
+ },
+ {
+ "name": "vector-effect",
+ "namespace": null
+ },
+ {
+ "name": "visibility",
+ "namespace": null
+ },
+ {
+ "name": "white-space",
+ "namespace": null
+ },
+ {
+ "name": "word-spacing",
+ "namespace": null
+ },
+ {
+ "name": "writing-mode",
+ "namespace": null
+ }
+ ],
+ "comments": false,
+ "dataAttributes": false,
+ "javascriptURLs": false
+ })
+}, "Get the expected default config")
+</script>
+</body>
+</html>
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-duplicate-html-body.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-duplicate-html-body.html
new file mode 100644
index 00000000000..fd86e79bbe8
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-duplicate-html-body.html
@@ -0,0 +1,170 @@
+<!DOCTYPE html>
+<html>
+<head>
+<meta charset="utf-8">
+<title>Sanitizer: duplicate &lt;html&gt; and &lt;body&gt; attribute sanitization</title>
+<link rel="help" href="https://github.com/whatwg/html/pull/12756">
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="support/html5lib-testcase-support.js"></script>
+</head>
+<body>
+<script id="safe" type="html5lib-testcases">
+#data
+<body><body onload="alert(1)" onclick="alert(2)" class="safe-body" data-test="val"></body>
+#document
+| <html>
+| <head>
+| <body>
+
+#data
+<body id="initial" class="initial"><body id="duplicate" class="duplicate" dir="rtl" onclick="alert(1)"></body>
+#document
+| <html>
+| <head>
+| <body>
+| dir="rtl"
+
+#data
+<html lang="en" id="root"><html id="duplicate" dir="rtl" onclick="alert(1)"><body></body>
+#document
+| <html>
+| lang="en"
+| dir="rtl"
+| <head>
+| <body>
+
+#data
+<body><body class="allowed" title="forbidden"></body>
+#config
+{ "attributes": ["class"] }
+#document
+| <html>
+| <head>
+| <body>
+| class="allowed"
+
+#data
+<html lang="en" dir="ltr" class="html-cls"><body id="main" class="body-cls" dir="ltr"></body>
+#config
+{ "elements": [{ "name": "html", "attributes": ["lang"] }, { "name": "body", "attributes": ["class"] }] }
+#document
+| <html>
+| lang="en"
+| <body>
+| class="body-cls"
+
+#data
+<html><body><body class="body-cls" data-foo="bar"></body>
+#config
+{ "elements": ["html", { "name": "body", "attributes": ["class"] }] }
+#document
+| <html>
+| <body>
+| class="body-cls"
+
+</script>
+<script id="unsafe" type="html5lib-testcases">
+#data
+<body><body data-bad="strip-me" data-good="keep-me"></body>
+#config
+{ "removeAttributes": ["data-bad"] }
+#document
+| <html>
+| <head>
+| <body>
+| data-good="keep-me"
+
+#data
+<html data-bad-html="1" data-good-html="2"><body data-bad-body="3" data-good-body="4"></body>
+#config
+{ "elements": [{ "name": "html", "removeAttributes": ["data-bad-html"] }, { "name": "body", "removeAttributes": ["data-bad-body"] }] }
+#document
+| <html>
+| data-good-html="2"
+| <body>
+| data-good-body="4"
+
+#data
+<html><body><html data-dup-bad-html="1" data-dup-good-html="2"><body data-dup-bad-body="3" data-dup-good-body="4"></body>
+#config
+{ "elements": [{ "name": "html", "removeAttributes": ["data-dup-bad-html"] }, { "name": "body", "removeAttributes": ["data-dup-bad-body"] }] }
+#document
+| <html>
+| data-dup-good-html="2"
+| <body>
+| data-dup-good-body="4"
+
+#data
+<html title="html-title"><body title="body-title"><div title="div-title"></div></body>
+#config
+{ "elements": ["html", { "name": "body", "removeAttributes": ["title"] }, "div"] }
+#document
+| <html>
+| title="html-title"
+| <body>
+| <div>
+| title="div-title"
+
+</script>
+<script id="fragment" type="html5lib-testcases">
+#document-fragment
+html
+#data
+<body id="test-body" onclick="alert(1)" class="safe-body"></body>
+#document
+| <head>
+| <body>
+
+#document-fragment
+html
+#data
+<body id="first" class="first"><body id="second" dir="rtl" onclick="alert(1)"></body>
+#document
+| <head>
+| <body>
+| dir="rtl"
+
+</script>
+<script>
+const safe = parse_html5lib_testcases(
+ document.getElementById("safe").textContent);
+const unsafe = parse_html5lib_testcases(
+ document.getElementById("unsafe").textContent);
+const fragment = parse_html5lib_testcases(
+ document.getElementById("fragment").textContent);
+
+safe.forEach((testcase, index) => {
+ let config = undefined;
+ if (testcase.config) {
+ config = { sanitizer: JSON.parse(testcase.config) };
+ }
+ test(_ => {
+ assert_testcase(Document.parseHTML(testcase.data, config), testcase);
+ }, `Document.parseHTML testcase ${index}, "${testcase.data}"`);
+});
+
+unsafe.forEach((testcase, index) => {
+ let config = undefined;
+ if (testcase.config) {
+ config = { sanitizer: JSON.parse(testcase.config) };
+ }
+ test(_ => {
+ assert_testcase(Document.parseHTMLUnsafe(testcase.data, config), testcase);
+ }, `Document.parseHTMLUnsafe testcase ${index}, "${testcase.data}"`);
+});
+
+fragment.forEach((testcase, index) => {
+ let config = undefined;
+ if (testcase.config) {
+ config = { sanitizer: JSON.parse(testcase.config) };
+ }
+ test(_ => {
+ const context = document.createElement(testcase["document-fragment"] ?? "div");
+ context.setHTML(testcase.data, config);
+ assert_testcase(context, testcase);
+ }, `Fragment setHTML testcase ${index}, "${testcase.data}"`);
+});
+</script>
+</body>
+</html>
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-get.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-get.html
new file mode 100644
index 00000000000..bb779aadc39
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-get.html
@@ -0,0 +1,98 @@
+<!DOCTYPE html>
+<html>
+<head>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="./support/util.js"></script>
+</head>
+<body>
+<script>
+
+const TEST_CASES = [
+ [
+ ["b", "a"],
+ ["a", "b"]
+ ],
+ [
+ ["c", "b", "a"],
+ ["a", "b", "c"]
+ ],
+ [
+ [{name: "b", namespace: null}, {name: "a", namespace: null}],
+ [{name: "a", namespace: null}, {name: "b", namespace: null}]
+ ],
+ [
+ [{name: "_", namespace: "a"}, {name: "_", namespace: null}],
+ [{name: "_", namespace: null}, {name: "_", namespace: "a"}]
+ ],
+ [
+ [{name: "_", namespace: "b"}, {name: "_", namespace: "a"}],
+ [{name: "_", namespace: "a"}, {name: "_", namespace: "b"}]
+ ],
+ [
+ [{name: "a", namespace: "b"}, {name: "z", namespace: "a"}, {name: "b", namespace: "b"}],
+ [{name: "z", namespace: "a"}, {name: "a", namespace: "b"}, {name: "b", namespace: "b"}],
+ ]
+];
+
+for (const key of ["attributes", "removeAttributes", "elements", "removeElements", "replaceWithChildrenElements"]) {
+ test(() => {
+ for (const [input, expected] of TEST_CASES) {
+ let s = new Sanitizer({
+ [key]: input
+ });
+ assert_config(s.get(), {
+ [key]: expected
+ });
+ }
+ }, `Sorting of ${key}`);
+}
+
+for (const key of ["attributes", "removeAttributes"]) {
+ test(() => {
+ for (const [input, expected] of TEST_CASES) {
+ let s = new Sanitizer({
+ elements: [{name: "_", [key]: input}]
+ });
+ assert_config(s.get(), {
+ elements: [{name: "_", [key]: expected}]
+ });
+ }
+ }, `Sorting of element's ${key}`);
+}
+
+const PI_TEST_CASES = [
+ [
+ ["b", "a"],
+ ["a", "b"]
+ ],
+ [
+ ["c", "b", "a"],
+ ["a", "b", "c"]
+ ],
+ [
+ [{target: "b"}, {target: "a"}],
+ [{target: "a"}, {target: "b"}]
+ ],
+ [
+ [{target: "c"}, {target: "b"}, {target: "a"}],
+ [{target: "a"}, {target: "b"}, {target: "c"}]
+ ]
+];
+
+for (const key of ["processingInstructions", "removeProcessingInstructions"]) {
+ test(() => {
+ for (const [input, expected] of PI_TEST_CASES) {
+ let s = new Sanitizer({
+ [key]: input
+ });
+ assert_config(s.get(), {
+ [key]: expected
+ });
+ }
+ }, `Sorting of ${key}`);
+}
+
+</script>
+</body>
+</html>
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-in-adoption-agency.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-in-adoption-agency.html
new file mode 100644
index 00000000000..2eee3430834
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-in-adoption-agency.html
@@ -0,0 +1,40 @@
+<!DOCTYPE html>
+<html>
+<head>
+<title>Sanitizer Adoption Agency Algorithm tests</title>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="support/html5lib-testcase-support.js"></script>
+</head>
+<body>
+<script>
+promise_test(_ => {
+ return html5lib_testcases_from_response(fetch("sanitizer-in-adoption-agency.sub.dat")).
+ then(testcases => {
+ testcases.forEach((testcase, index) => {
+ test(_ => {
+ const context = document.createElement(testcase["document-fragment"] ?? "div");
+ let config = undefined;
+ try {
+ config = JSON.parse(testcase.config);
+ } catch { }
+ try {
+ context.setHTML(testcase.data, { sanitizer: config });
+ } catch (error) {
+ assert_equals(
+ error.name, testcase.error,
+ `Expect exception ${testcase.error}, but got ${error}.`);
+ assert_equals(context.firstChild, null);
+ return;
+ }
+ assert_false(
+ !!testcase.error,
+ `Expect exception ${testcase.error}, but nothing was thrown.`);
+ assert_testcase(context, testcase);
+ }, `Testcase #${index}, "${testcase.data}", config: "${testcase.config}".`);
+ });
+ });
+}, "Sanitizer Adoption Agency Algorithm testcases");
+</script>
+</body>
+</html>
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-in-adoption-agency.sub.dat b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-in-adoption-agency.sub.dat
new file mode 100644
index 00000000000..88690c4bda3
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-in-adoption-agency.sub.dat
@@ -0,0 +1,634 @@
+#data
+<b><i onclick="alert(1)"><div></b>x
+#document
+| <b>
+| <i>
+| <i>
+| <div>
+| <b>
+| "x"
+
+#data
+<b><div>Text</b></div>
+#config
+{ "replaceWithChildrenElements": ["b"] }
+#document
+| <div>
+| "Text"
+
+#data
+<b><i><div>Text</b></div>
+#config
+{ "replaceWithChildrenElements": ["i"] }
+#document
+| <b>
+| <div>
+| <b>
+| "Text"
+
+#data
+<b><div>Text</b>
+#config
+{ "removeElements": ["div"] }
+#document
+| <b>
+
+#data
+<b><div><b>x
+#config
+{ "removeElements": ["div"] }
+#document
+| <b>
+
+#data
+<b>1<p>foo</b>bar
+#config
+{ "replaceWithChildrenElements": ["b"] }
+#document
+| "1"
+| <p>
+| "foobar"
+
+#data
+<b><div>Text</b>
+#config
+{ "replaceWithChildrenElements": ["div"] }
+#document
+| <b>
+| "Text"
+| <b>
+
+#data
+<a href="https://wpt.live/1"><div><a href="https://wpt.live/2">Click</a></div></a>
+#config
+{ "removeElements": ["div"] }
+#document
+| <a>
+| href="https://wpt.live/1"
+
+#data
+<b><i><p>foo</b>bar</i>
+#config
+{ "removeElements": ["p"] }
+#document
+| <b>
+| <i>
+| <i>
+
+#data
+<b><i><p>foo</b>bar</i>
+#config
+{ "removeElements": ["i"] }
+#document
+| <b>
+| <p>
+
+#data
+<b><i><div>Text</b></i>
+#config
+{ "removeElements": ["div"], "replaceWithChildrenElements": ["i"] }
+#document
+| <b>
+
+#data
+<b><i onclick="alert(1)"><u onclick="alert(2)"><div></b>x
+#document
+| <b>
+| <i>
+| <u>
+| <i>
+| <u>
+| <div>
+| <b>
+| "x"
+
+#data
+<b><em><div>Text</b>after
+#config
+{ "replaceWithChildrenElements": ["div"] }
+#document
+| <b>
+| <em>
+| "Text"
+| <em>
+| <b>
+| "after"
+
+#data
+<b><em><s><div>Text</b>after</div>more
+#config
+{ "replaceWithChildrenElements": ["div", "s"] }
+#document
+| <b>
+| <em>
+| "Text"
+| <em>
+| <b>
+| "aftermore"
+
+#data
+<b><em><u><div>Text</b>after
+#config
+{ "replaceWithChildrenElements": ["div"] }
+#document
+| <b>
+| <em>
+| <u>
+| "Text"
+| <em>
+| <u>
+| <b>
+| "after"
+
+#data
+<b><u><em><div>Text</b>after
+#config
+{ "replaceWithChildrenElements": ["div", "em"] }
+#document
+| <b>
+| <u>
+| "Text"
+| <u>
+| <b>
+| "after"
+
+#data
+<b><em><div>Text</b>after
+#config
+{ "replaceWithChildrenElements": ["div"], "removeElements": ["em"] }
+#document
+| <b>
+
+#data
+<b><em><div><p>Text</b>after
+#config
+{ "replaceWithChildrenElements": ["div"] }
+#document
+| <b>
+| <em>
+| <em>
+| <b>
+| <p>
+| <b>
+| "Text"
+| "after"
+
+#data
+<b><div><section>Text</b>after
+#config
+{ "replaceWithChildrenElements": ["div", "section"] }
+#document
+| <b>
+| "Text"
+| <b>
+| <b>
+| "after"
+
+#data
+<b><div><span>Text</b>after
+#config
+{ "replaceWithChildrenElements": ["span"] }
+#document
+| <b>
+| <div>
+| <b>
+| "Text"
+| "after"
+
+#data
+<b><em><div>Text</b>after</div>more
+#config
+{ "replaceWithChildrenElements": ["div"] }
+#document
+| <b>
+| <em>
+| "Text"
+| <em>
+| <b>
+| "aftermore"
+
+#data
+<b><div><div><div><div><div><div><div><div><section>Text</b>after
+#config
+{ "replaceWithChildrenElements": ["section"] }
+#document
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| "Textafter"
+
+#data
+<b><div><div><div><div><div><div><div><div><section>Text</b>after
+#config
+{ "replaceWithChildrenElements": ["section", "b"] }
+#document
+| <div>
+| <div>
+| <div>
+| <div>
+| <div>
+| <div>
+| <div>
+| <div>
+| "Textafter"
+
+#data
+<b><div><div><div><div><div><div><div><div><section><span>Text</b>after
+#config
+{ "replaceWithChildrenElements": ["section", "span"] }
+#document
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| "Textafter"
+
+#data
+<b><div><div><div><div><div><div><div><div><section><i><span>Text</b>after
+#config
+{ "replaceWithChildrenElements": ["section", "span"] }
+#document
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <i>
+| "Textafter"
+
+#data
+<table><b><div>x</b>y
+#document
+| <b>
+| <div>
+| <b>
+| "x"
+| "y"
+| <table>
+
+#data
+<table><b><div>x</b>y
+#config
+{ "removeElements": ["table"] }
+#document
+| <b>
+| <div>
+| <b>
+| "x"
+| "y"
+
+#data
+<table><b><div>x</b>y
+#config
+{ "replaceWithChildrenElements": ["b"] }
+#document
+| <div>
+| "xy"
+| <table>
+
+#data
+<table><tbody><b><div>x</b>y
+#config
+{ "replaceWithChildrenElements": ["tbody"] }
+#document
+| <b>
+| <div>
+| <b>
+| "x"
+| "y"
+| <table>
+
+#data
+<table><b><div>x</b>y
+#config
+{ "replaceWithChildrenElements": ["div"] }
+#document
+| <b>
+| "x"
+| <b>
+| "y"
+| <table>
+
+#data
+<b><div>Text</b>after
+#config
+{ "removeElements": ["b"] }
+#document
+| <div>
+| "after"
+
+#data
+<p><b>x</p>y
+#config
+{ "replaceWithChildrenElements": ["b"] }
+#document
+| <p>
+| "x"
+| "y"
+
+#data
+<p><b>x</p>y
+#config
+{ "removeElements": ["b"] }
+#document
+| <p>
+
+#data
+<p><i onclick="1">x</p>y
+#document
+| <p>
+| <i>
+| "x"
+| <i>
+| "y"
+
+#data
+<p><b a="1"><b a="2"><b a="3"><b a="4"></p>x
+#config
+{ "removeAttributes": ["a"] }
+#document
+| <p>
+| <b>
+| <b>
+| <b>
+| <b>
+| <b>
+| <b>
+| <b>
+| <b>
+| "x"
+
+#data
+<b><i><u><p>foo</b>bar
+#config
+{ "removeElements": ["i"] }
+#document
+| <b>
+
+#data
+<b><div><p>Text</b>after
+#config
+{ "removeElements": ["p"] }
+#document
+| <b>
+| <div>
+| <b>
+
+#data
+<b><div>Text</b>after
+#config
+{ "replaceWithChildrenElements": ["b", "div"] }
+#document
+| "Textafter"
+
+#data
+<a href="1">x<div>y<a href="2">z
+#config
+{ "replaceWithChildrenElements": ["a"] }
+#document
+| "x"
+| <div>
+| "yz"
+
+#data
+<a href="1">x<div>y<a href="2">z
+#config
+{ "removeElements": ["a"] }
+#document
+| <div>
+
+#data
+<b><span><div>x</b>y
+#config
+{ "removeElements": ["span"] }
+#document
+| <b>
+| <div>
+| <b>
+| "x"
+| "y"
+
+#data
+<b><div><table></b>x
+#config
+{ "replaceWithChildrenElements": ["b"] }
+#document
+| <div>
+| "x"
+| <table>
+
+#data
+<b><i><div>Text</b>after
+#config
+{ "removeElements": ["div"] }
+#document
+| <b>
+| <i>
+| <i>
+
+#data
+<b><i><div>Text</b>after
+#config
+{ "replaceWithChildrenElements": ["i", "div"] }
+#document
+| <b>
+| "Text"
+| <b>
+| "after"
+
+#data
+<div><b><p>x</b>y
+#config
+{ "replaceWithChildrenElements": ["div"] }
+#document
+| <b>
+| <p>
+| <b>
+| "x"
+| "y"
+
+#data
+<div><b><p>x</b>y
+#config
+{ "removeElements": ["div"] }
+#document
+
+#data
+<b><u><em><div>Text</b>after</div>more
+#config
+{ "replaceWithChildrenElements": ["div", "em"] }
+#document
+| <b>
+| <u>
+| "Text"
+| <u>
+| <b>
+| "aftermore"
+
+#data
+<b><u><em><div>Text</b>after</div>more
+#config
+{ "replaceWithChildrenElements": ["div", "em"], "removeElements": ["u"] }
+#document
+| <b>
+
+#data
+<table><b><div>x</b><input type="hidden">
+#config
+{ "replaceWithChildrenElements": ["div"] }
+#document
+| <b>
+| "x"
+| <b>
+| <input>
+| type="hidden"
+| <table>
+
+#data
+<article><b><i><section><div><div><div><div><div><div><div><div>x</b>y</article>z
+#document
+| <article>
+| <b>
+| <i>
+| <i>
+| <section>
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <div>
+| "xy"
+| <i>
+| <b>
+| "z"
+
+#data
+<article><b><i><section><div><div><div><div><div><div><div><div>x</b>y</article>z
+#config
+{ "replaceWithChildrenElements": ["section"] }
+#document
+| <article>
+| <b>
+| <i>
+| <i>
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <div>
+| "xy"
+| <i>
+| <b>
+| "z"
+
+#data
+<b><div><div><div><div><div><div><div><div>x</b>y
+#document
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| <div>
+| <b>
+| "xy"
+
+#data
+<b><div><div><div><div><div><div><div><div>x</b>y
+#config
+{ "replaceWithChildrenElements": ["b"] }
+#document
+| <div>
+| <div>
+| <div>
+| <div>
+| <div>
+| <div>
+| <div>
+| <div>
+| "xy"
+
+#data
+<b><u>1<p>foo</b><i>bar</i>baz
+#config
+{ "replaceWithChildrenElements": ["u"] }
+#document
+| <b>
+| "1"
+| <p>
+| <b>
+| "foo"
+| <i>
+| "bar"
+| "baz"
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-in-noahs-ark.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-in-noahs-ark.html
new file mode 100644
index 00000000000..7d24c195e8a
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-in-noahs-ark.html
@@ -0,0 +1,226 @@
+<!DOCTYPE html>
+<html>
+<head>
+<title>Sanitizer and the Noah's Ark clause of the list of active formatting elements</title>
+<link rel="help" href="https://html.spec.whatwg.org/#push-onto-the-list-of-active-formatting-elements">
+<link rel="help" href="https://html.spec.whatwg.org/#html-sanitization">
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="support/html5lib-testcase-support.js"></script>
+</head>
+<body>
+<!--
+ The Noah's Ark clause compares formatting elements by their tag name,
+ namespace and attributes as parsed. Attributes that the sanitizer removes
+ still count: four <b> elements whose (removed) attributes differ are all
+ kept in the list of active formatting elements, so all four are
+ reconstructed, even though the resulting elements look identical. When the
+ removed attributes are identical, the earliest entry is evicted and only
+ three are reconstructed.
+-->
+<script type="html5lib-tests">
+#data
+<p><b title=1>1<b title=2>2<b title=3>3<b title=4>4</p>x
+#config
+{ "removeAttributes": ["title"] }
+#document
+| <p>
+| <b>
+| "1"
+| <b>
+| "2"
+| <b>
+| "3"
+| <b>
+| "4"
+| <b>
+| <b>
+| <b>
+| <b>
+| "x"
+
+#data
+<p><b title=1>1<b title=1>2<b title=1>3<b title=1>4</p>x
+#config
+{ "removeAttributes": ["title"] }
+#document
+| <p>
+| <b>
+| "1"
+| <b>
+| "2"
+| <b>
+| "3"
+| <b>
+| "4"
+| <b>
+| <b>
+| <b>
+| "x"
+
+#data
+<p><b>1<b>2<b>3<b title=1>4</p>x
+#config
+{ "removeAttributes": ["title"] }
+#document
+| <p>
+| <b>
+| "1"
+| <b>
+| "2"
+| <b>
+| "3"
+| <b>
+| "4"
+| <b>
+| <b>
+| <b>
+| <b>
+| "x"
+
+#data
+<p><b title=1>1<b>2<b>3<b>4</p>x
+#config
+{ "removeAttributes": ["title"] }
+#document
+| <p>
+| <b>
+| "1"
+| <b>
+| "2"
+| <b>
+| "3"
+| <b>
+| "4"
+| <b>
+| <b>
+| <b>
+| <b>
+| "x"
+
+#data
+<p><b class=c title=1>1<b class=c title=2>2<b class=c title=3>3<b class=c title=4>4</p>x
+#config
+{ "removeAttributes": ["title"] }
+#document
+| <p>
+| <b>
+| class="c"
+| "1"
+| <b>
+| class="c"
+| "2"
+| <b>
+| class="c"
+| "3"
+| <b>
+| class="c"
+| "4"
+| <b>
+| class="c"
+| <b>
+| class="c"
+| <b>
+| class="c"
+| <b>
+| class="c"
+| "x"
+
+#data
+<p><b class=c title=1>1<b class=c title=2>2<b class=c title=3>3<b class=c title=4>4</p>x
+#config
+{ "attributes": ["class"] }
+#document
+| <p>
+| <b>
+| class="c"
+| "1"
+| <b>
+| class="c"
+| "2"
+| <b>
+| class="c"
+| "3"
+| <b>
+| class="c"
+| "4"
+| <b>
+| class="c"
+| <b>
+| class="c"
+| <b>
+| class="c"
+| <b>
+| class="c"
+| "x"
+
+#data
+<p><b onclick=1>1<b onclick=2>2<b onclick=3>3<b onclick=4>4</p>x
+#document
+| <p>
+| <b>
+| "1"
+| <b>
+| "2"
+| <b>
+| "3"
+| <b>
+| "4"
+| <b>
+| <b>
+| <b>
+| <b>
+| "x"
+
+#data
+<p><b onclick=1>1<b onclick=1>2<b onclick=1>3<b onclick=1>4</p>x
+#document
+| <p>
+| <b>
+| "1"
+| <b>
+| "2"
+| <b>
+| "3"
+| <b>
+| "4"
+| <b>
+| <b>
+| <b>
+| "x"
+
+</script>
+<script>
+function parse_config(testcase) {
+ return testcase.config ? JSON.parse(testcase.config) : undefined;
+}
+
+html5lib_testcases_from_script().forEach((testcase, index) => {
+ const label = `Testcase #${index}, "${testcase.data}", config: "${testcase.config}"`;
+
+ test(_ => {
+ const context = document.createElement("div");
+ context.setHTML(testcase.data, { sanitizer: parse_config(testcase) });
+ assert_testcase(context, testcase);
+ }, `${label}, with setHTML()`);
+
+ // setHTMLUnsafe() only sanitizes when given a sanitizer, and does not
+ // remove unsafe content, so only run the test cases with an explicit
+ // configuration.
+ if (testcase.config) {
+ test(_ => {
+ const context = document.createElement("div");
+ context.setHTMLUnsafe(testcase.data, { sanitizer: parse_config(testcase) });
+ assert_testcase(context, testcase);
+ }, `${label}, with setHTMLUnsafe()`);
+ }
+
+ test(_ => {
+ const doc = Document.parseHTML(testcase.data, { sanitizer: parse_config(testcase) });
+ const expected = build_node_tree(document.createElement("body"), testcase.document);
+ assert_subtree_equals(doc.body, expected);
+ }, `${label}, with Document.parseHTML()`);
+});
+</script>
+</body>
+</html>
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-javascript-url.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-javascript-url.html
new file mode 100644
index 00000000000..309ec877e37
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-javascript-url.html
@@ -0,0 +1,435 @@
+<!DOCTYPE html>
+<head>
+<title>Testcases for handling javascript: URL attributes</title>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="support/html5lib-testcase-support.js"></script>
+<script src="../mathml/support/mathml-fragments.js"></script>
+
+<script id="built-in-navigating-url-attributes-list" type="html5lib-testcases">
+#data
+<a href="javascript:alert(1)"></a>
+#document
+| <a>
+
+#data
+<area href="javascript:alert(1)"></area>
+#document
+| <area>
+
+#data
+<button formaction="javascript:alert(1)"></button>
+#document
+| <button>
+
+#data
+<form action="javascript:alert(1)"></form>
+#document
+| <form>
+
+#data
+<input formaction="javascript:alert(1)"></input>
+#document
+| <input>
+
+#data
+<svg><a href="javascript:alert(1)"></a></svg>
+#document
+| <svg svg>
+| <svg a>
+
+#data
+<svg><a xlink:href="javascript:alert(1)"></a></svg>
+#document
+| <svg svg>
+| <svg a>
+
+</script>
+
+<script id="mathml" type="html5lib-testcases">
+#data
+<math><mrow href="javascript:alert(1)"></mrow></math>
+#document
+| <math math>
+| <math mrow>
+
+#data
+<math><msqrt href="javascript:alert(1)"></msqrt></math>
+#document
+| <math math>
+| <math msqrt>
+
+#data
+<math><mtext href="javascript:alert(1)">Test</mtext></math>
+#document
+| <math math>
+| <math mtext>
+| "Test"
+
+#data
+<math><mrow xlink:href="javascript:alert(1)"></mrow></math>
+#document
+| <math math>
+| <math mrow>
+
+</script>
+
+<script id="built-in-animating-url-attributes-list" type="html5lib-testcases">
+#data
+<svg><animate attributeName="href"></svg>
+#document
+| <svg svg>
+| <svg animate>
+
+#data
+<svg><animate attributeName="xlink:href"></svg>
+#document
+| <svg svg>
+| <svg animate>
+
+#data
+<svg><animateMotion attributeName="href"></svg>
+#document
+| <svg svg>
+| <svg animateMotion>
+| attributeName="href"
+
+#data
+<svg><animateMotion attributeName="xlink:href"></svg>
+#document
+| <svg svg>
+| <svg animateMotion>
+| attributeName="xlink:href"
+
+#data
+<svg><animateTransform attributeName="href"></svg>
+#document
+| <svg svg>
+| <svg animateTransform>
+
+#data
+<svg><animateTransform attributeName="xlink:href"></svg>
+#document
+| <svg svg>
+| <svg animateTransform>
+
+
+#data
+<svg><set attributeName="href"></svg>
+#document
+| <svg svg>
+| <svg set>
+
+#data
+<svg><set attributeName="xlink:href"></svg>
+#document
+| <svg svg>
+| <svg set>
+
+</script>
+
+<script id="allowed" type="html5lib-testcases">
+#data
+<a nothref="javascript:alert(1)"></a>
+#document
+| <a>
+| nothref="javascript:alert(1)"
+
+#data
+<svg><a xlink:href="data:text/html,foobar"></a></svg>
+#document
+| <svg svg>
+| <svg a>
+| xlink href="data:text/html,foobar"
+
+#data
+<svg><set attributeName=" href "></svg>
+#document
+| <svg svg>
+| <svg set>
+| attributeName=" href "
+
+</script>
+
+<script id="url-normalization" type="html5lib-testcases">
+#data
+<a href="JaVaScRiPt:alert(1)"></a>
+#document
+| <a>
+
+#data
+<a href=" javascript:alert(1)"></a>
+#document
+| <a>
+
+#data
+<a href="&#10;javascript:alert(1)"></a>
+#document
+| <a>
+
+#data
+<a href="java&#9;script:alert(1)"></a>
+#document
+| <a>
+
+#data
+<a href="java&#10;script:alert(1)"></a>
+#document
+| <a>
+
+#data
+<a href="java&#13;script:alert(1)"></a>
+#document
+| <a>
+
+#data
+<a href="javascript&#58;alert(1)"></a>
+#document
+| <a>
+
+#data
+<svg><a xlink:href="java&#9;script:alert(1)"></a></svg>
+#document
+| <svg svg>
+| <svg a>
+
+</script>
+
+<script>
+const mathmlDynamicCasesText = Object.keys(MathMLFragments).map(tag => `
+#data
+<math><${tag} href="javascript:alert(1)"></${tag}></math>
+#document
+| <math math>
+| <math ${tag}>
+
+#data
+<math><${tag} xlink:href="javascript:alert(1)"></${tag}></math>
+#document
+| <math math>
+| <math ${tag}>
+`).join("");
+
+const testcaseGroups = [
+ ...Array.from(document.querySelectorAll("script[type='html5lib-testcases']")).map(el => ({ id: el.id, text: el.textContent })),
+ { id: "mathml-all-elements", text: mathmlDynamicCasesText }
+];
+
+for (const group of testcaseGroups) {
+ parse_html5lib_testcases(group.text).forEach((testcase, index) => {
+ // 1. Safe methods: javascript URLs must always be removed regardless of config.
+ const safeConfigs = [
+ ["{ sanitizer: {} }", { sanitizer: {} }],
+ ["{ sanitizer: { javascriptURLs: false } }", { sanitizer: { javascriptURLs: false } }],
+ ["{ sanitizer: { javascriptURLs: true } }", { sanitizer: { javascriptURLs: true } }],
+ ["{ sanitizer: new Sanitizer({ javascriptURLs: true }) }", { sanitizer: new Sanitizer({ javascriptURLs: true }) }],
+ ];
+
+ for (const [name, config] of safeConfigs) {
+ test((_) => {
+ const div = document.createElement("div");
+ div.setHTML(testcase.data, config);
+ assert_testcase(div, testcase);
+ }, `setHTML ${name} testcase ${group.id}/${index}, "${testcase.data}"`);
+
+ test((_) => {
+ assert_testcase(Document.parseHTML("<body>" + testcase.data, config).body, testcase);
+ }, `parseHTML ${name} testcase ${group.id}/${index}, "${testcase.data}"`);
+ }
+
+ // 2. Unsafe methods with javascriptURLs: false -> URLs must be removed (same as safe result).
+ // The default configuration has javascriptURLs: false as well, but its element and attribute
+ // allow lists remove nearly all the markup above, so it cannot be compared against these
+ // expectations. It is covered separately below.
+ const afterRemoveUnsafe = new Sanitizer({});
+ afterRemoveUnsafe.removeUnsafe();
+ const unsafeDisallowedConfigs = [
+ ["{ sanitizer: { javascriptURLs: false } }", { sanitizer: { javascriptURLs: false } }],
+ ["{ sanitizer: new Sanitizer({ javascriptURLs: false }) }", { sanitizer: new Sanitizer({ javascriptURLs: false }) }],
+ ["{ sanitizer: new Sanitizer({}) } after removeUnsafe()", { sanitizer: afterRemoveUnsafe }],
+ ];
+
+ for (const [name, config] of unsafeDisallowedConfigs) {
+ test((_) => {
+ const div = document.createElement("div");
+ div.setHTMLUnsafe(testcase.data, config);
+ assert_testcase(div, testcase);
+ }, `setHTMLUnsafe ${name} testcase ${group.id}/${index}, "${testcase.data}"`);
+
+ test((_) => {
+ assert_testcase(Document.parseHTMLUnsafe("<body>" + testcase.data, config).body, testcase);
+ }, `parseHTMLUnsafe ${name} testcase ${group.id}/${index}, "${testcase.data}"`);
+ }
+ });
+}
+
+// 3. Unsafe methods with the default configuration -> URLs must be removed.
+//
+// The default configuration has javascriptURLs: false, so the unsafe methods remove javascript:
+// URLs as well. Its element and attribute allow lists remove nearly all the markup in the
+// testcases above though, so it cannot be run against those expectations. HTML a/href and SVG
+// a/href are the only pairs from the built-in navigating URL attributes list that the default
+// configuration keeps at all; for every other pair the attribute is gone either way and
+// javascriptURLs makes no observable difference.
+const defaultConfigTestcases = [
+ { selector: "a", markup: (url) => `<a href="${url}"></a>` },
+ { selector: "svg a", markup: (url) => `<svg><a href="${url}"></a></svg>` },
+ { selector: "math a", markup: (url) => `<math><a href="${url}"></a></math>` },
+];
+
+const javascriptURL = "javascript:alert(1)";
+const otherURL = "https://example.com/";
+
+function assert_href(root, selector, expected, description) {
+ const element = root.querySelector(selector);
+ assert_not_equals(element, null, `${description} (${selector} is kept)`);
+ assert_equals(element.getAttribute("href"), expected, description);
+}
+
+for (const { selector, markup } of defaultConfigTestcases) {
+ for (const [name, config] of [
+ [`{ sanitizer: "default" }`, { sanitizer: "default" }],
+ ["{ sanitizer: new Sanitizer() }", { sanitizer: new Sanitizer() }],
+ ]) {
+ test((_) => {
+ const div = document.createElement("div");
+ div.setHTMLUnsafe(markup(javascriptURL), config);
+ assert_href(div, selector, null, "javascript: URL is removed");
+
+ // href is allowed by the default configuration, so what removed it above is javascriptURLs
+ // and not the attribute allow list.
+ div.setHTMLUnsafe(markup(otherURL), config);
+ assert_href(div, selector, otherURL, "other URL is kept");
+ }, `setHTMLUnsafe ${name} default configuration, "${markup(javascriptURL)}"`);
+
+ test((_) => {
+ assert_href(Document.parseHTMLUnsafe("<body>" + markup(javascriptURL), config).body,
+ selector, null, "javascript: URL is removed");
+ assert_href(Document.parseHTMLUnsafe("<body>" + markup(otherURL), config).body,
+ selector, otherURL, "other URL is kept");
+ }, `parseHTMLUnsafe ${name} default configuration, "${markup(javascriptURL)}"`);
+ }
+
+ test((_) => {
+ const sanitizer = new Sanitizer();
+ assert_true(sanitizer.setJavascriptURLs(true), "javascriptURLs defaults to false");
+
+ const div = document.createElement("div");
+ div.setHTMLUnsafe(markup(javascriptURL), { sanitizer });
+ assert_href(div, selector, javascriptURL, "unsafe method keeps the javascript: URL");
+
+ div.setHTML(markup(javascriptURL), { sanitizer });
+ assert_href(div, selector, null, "safe method removes the javascript: URL anyway");
+ }, `setJavascriptURLs(true) on the default configuration, "${markup(javascriptURL)}"`);
+}
+
+// 4. Unsafe methods with javascriptURLs: true -> URLs must be preserved.
+test(() => {
+ const unsafeAllowedConfigs = [
+ ["{ sanitizer: {} }", { sanitizer: {} }],
+ ["{ sanitizer: { javascriptURLs: true } }", { sanitizer: { javascriptURLs: true } }],
+ ["{ sanitizer: new Sanitizer({ javascriptURLs: true }) }", { sanitizer: new Sanitizer({ javascriptURLs: true }) }],
+ ["{ sanitizer: new Sanitizer({}) }", { sanitizer: new Sanitizer({}) }],
+ ];
+
+ const baseProbes = [
+ '<a href="javascript:alert(1)"></a>',
+ '<area href="javascript:alert(1)"></area>',
+ '<button formaction="javascript:alert(1)"></button>',
+ '<form action="javascript:alert(1)"></form>',
+ '<input formaction="javascript:alert(1)"></input>',
+ '<svg><a href="javascript:alert(1)"></a></svg>',
+ '<svg><a xlink:href="javascript:alert(1)"></a></svg>',
+ '<svg><animate attributeName="href"></svg>',
+ '<svg><animate attributeName="xlink:href"></svg>',
+ '<svg><animateMotion attributeName="href"></svg>',
+ '<svg><animateMotion attributeName="xlink:href"></svg>',
+ '<svg><animateTransform attributeName="href"></svg>',
+ '<svg><animateTransform attributeName="xlink:href"></svg>',
+ '<svg><set attributeName="href"></svg>',
+ '<svg><set attributeName="xlink:href"></svg>',
+ '<a href="JaVaScRiPt:alert(1)"></a>',
+ '<a href=" javascript:alert(1)"></a>',
+ '<a href="&#10;javascript:alert(1)"></a>',
+ '<a href="java&#9;script:alert(1)"></a>',
+ '<svg><a xlink:href="java&#9;script:alert(1)"></a></svg>',
+ ];
+
+ const mathmlProbes = Object.keys(MathMLFragments).flatMap(tag => [
+ `<math><${tag} href="javascript:alert(1)"></${tag}></math>`,
+ `<math><${tag} xlink:href="javascript:alert(1)"></${tag}></math>`
+ ]);
+
+ const probes = [...baseProbes, ...mathmlProbes];
+
+ for (const [configName, config] of unsafeAllowedConfigs) {
+ for (const probe of probes) {
+ const div = document.createElement("div");
+ div.setHTMLUnsafe(probe, config);
+ const parsed = Document.parseHTMLUnsafe("<body>" + probe, config);
+
+ if (probe.includes("attributeName")) {
+ assert_true(div.querySelector("[attributeName]") !== null, `setHTMLUnsafe ${configName}: retains attributeName in ${probe}`);
+ assert_true(parsed.body.querySelector("[attributeName]") !== null, `parseHTMLUnsafe ${configName}: retains attributeName in ${probe}`);
+ } else if (probe.includes("formaction")) {
+ assert_true(div.querySelector("[formaction]") !== null, `setHTMLUnsafe ${configName}: retains formaction in ${probe}`);
+ assert_true(parsed.body.querySelector("[formaction]") !== null, `parseHTMLUnsafe ${configName}: retains formaction in ${probe}`);
+ } else if (probe.includes("action=")) {
+ assert_true(div.querySelector("[action]") !== null, `setHTMLUnsafe ${configName}: retains action in ${probe}`);
+ assert_true(parsed.body.querySelector("[action]") !== null, `parseHTMLUnsafe ${configName}: retains action in ${probe}`);
+ } else if (probe.includes("xlink:href")) {
+ assert_true(div.querySelector("a, mrow")?.hasAttributeNS("http://www.w3.org/1999/xlink", "href") || div.querySelector("[*|href]") !== null, `setHTMLUnsafe ${configName}: retains xlink:href in ${probe}`);
+ assert_true(parsed.body.querySelector("a, mrow")?.hasAttributeNS("http://www.w3.org/1999/xlink", "href") || parsed.body.querySelector("[*|href]") !== null, `parseHTMLUnsafe ${configName}: retains xlink:href in ${probe}`);
+ } else {
+ assert_true(div.querySelector("[href]") !== null, `setHTMLUnsafe ${configName}: retains href in ${probe}`);
+ assert_true(parsed.body.querySelector("[href]") !== null, `parseHTMLUnsafe ${configName}: retains href in ${probe}`);
+ }
+ }
+ }
+}, "javascript: URLs preserved in unsafe methods when javascriptURLs is true");
+
+// 5. Modifier method setJavascriptURLs() effects on sanitization
+test(() => {
+ let s = new Sanitizer();
+ s.setJavascriptURLs(true);
+ const div1 = document.createElement("div");
+ div1.setHTMLUnsafe('<a href="javascript:alert(1)"></a>', { sanitizer: s });
+ assert_true(div1.querySelector("a").hasAttribute("href"));
+
+ s.setJavascriptURLs(false);
+ const div2 = document.createElement("div");
+ div2.setHTMLUnsafe('<a href="javascript:alert(1)"></a>', { sanitizer: s });
+ assert_false(div2.querySelector("a").hasAttribute("href"));
+}, "sanitizer.setJavascriptURLs() controls URL preservation in setHTMLUnsafe");
+
+// 6. Template and ShadowRoot handling with javascriptURLs
+test(() => {
+ const tplHTML = '<template><a href="javascript:alert(1)"></a></template>';
+
+ const divSafe = document.createElement("div");
+ divSafe.setHTML(tplHTML, { sanitizer: { javascriptURLs: true } });
+ assert_false(divSafe.querySelector("template").content.querySelector("a").hasAttribute("href"));
+
+ const divUnsafeFalse = document.createElement("div");
+ divUnsafeFalse.setHTMLUnsafe(tplHTML, { sanitizer: { javascriptURLs: false } });
+ assert_false(divUnsafeFalse.querySelector("template").content.querySelector("a").hasAttribute("href"));
+
+ const divUnsafeTrue = document.createElement("div");
+ divUnsafeTrue.setHTMLUnsafe(tplHTML, { sanitizer: { javascriptURLs: true } });
+ assert_true(divUnsafeTrue.querySelector("template").content.querySelector("a").hasAttribute("href"));
+
+ const host = document.createElement("div");
+ const shadow = host.attachShadow({ mode: "open" });
+ shadow.setHTMLUnsafe('<a href="javascript:alert(1)"></a>', { sanitizer: { javascriptURLs: false } });
+ assert_false(shadow.querySelector("a").hasAttribute("href"));
+
+ shadow.setHTMLUnsafe('<a href="javascript:alert(1)"></a>', { sanitizer: { javascriptURLs: true } });
+ assert_true(shadow.querySelector("a").hasAttribute("href"));
+
+ shadow.setHTML('<a href="javascript:alert(1)"></a>', { sanitizer: { javascriptURLs: true } });
+ assert_false(shadow.querySelector("a").hasAttribute("href"));
+}, "Template and ShadowRoot handling with javascriptURLs");
+</script>
+</head>
+<body>
+</body>
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-modifiers.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-modifiers.html
new file mode 100644
index 00000000000..43b2c2e59f2
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-modifiers.html
@@ -0,0 +1,610 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <script src="../resources/testharness.js"></script>
+ <script src="../resources/testharnessreport.js"></script>
+ <script src="./support/util.js"></script>
+</head>
+<body>
+<script>
+const NS = "http://example.org/";
+
+test(() => {
+ let s = new Sanitizer({ attributes: [] });
+
+ assert_true(s.allowAttribute("id"));
+ assert_config(s.get(), { attributes: ["id"] });
+
+ assert_false(s.allowAttribute({ name: "id", namespace: null }));
+ assert_config(s.get(), { attributes: ["id"] });
+
+ assert_true(s.allowAttribute({ name: "id", namespace: NS }));
+ assert_config(s.get(), {
+ attributes: ["id", { name: "id", namespace: NS }],
+ removeElements: [],
+ });
+}, "sanitizer.allowAttribute() with global attributes");
+
+test(() => {
+ let s = new Sanitizer({ removeAttributes: ["title"] });
+
+ assert_false(s.allowAttribute("id"));
+ assert_config(s.get(), { removeAttributes: ["title"] });
+
+ assert_false(s.allowAttribute({ name: "title", namespace: NS }));
+ assert_config(s.get(), { removeAttributes: ["title"] });
+
+ assert_true(s.allowAttribute("title"));
+ assert_config(s.get(), { removeAttributes: [] });
+}, "sanitizer.allowAttribute() with global removeAttributes");
+
+test(() => {
+ let s = new Sanitizer({
+ attributes: [],
+ elements: [{ name: "id", attributes: ["href", { name: "title", namespace: NS }] }],
+ });
+
+ assert_true(s.allowAttribute("class"));
+ assert_config(s.get(), { attributes: ["class"] });
+
+ assert_false(s.allowAttribute("class"));
+ assert_config(s.get(), { attributes: ["class"] });
+
+ assert_true(s.allowAttribute("title"));
+ assert_config(s.get(), {
+ attributes: ["class", "title"],
+ elements: [{ name: "id", attributes: ["href", { name: "title", namespace: NS }] }],
+ });
+
+ assert_true(s.allowAttribute({ name: "title", namespace: NS }));
+ assert_config(s.get(), {
+ attributes: ["class", "title", { name: "title", namespace: NS }],
+ elements: [{ name: "id", attributes: ["href"] }],
+ });
+
+ assert_false(s.allowAttribute({ name: "title", namespace: NS }));
+ assert_config(s.get(), {
+ attributes: ["class", "title", { name: "title", namespace: NS }],
+ elements: [{ name: "id", attributes: ["href"] }],
+ });
+}, "sanitizer.allowAttribute() with global attributes and elements");
+
+test(() => {
+ const ELEMENTS = [{ name: "div", attributes: ["href"] }];
+
+ let s = new Sanitizer({
+ removeAttributes: ["id"],
+ elements: ELEMENTS,
+ });
+
+ assert_false(s.allowAttribute("class"));
+ assert_config(s.get(), {
+ removeAttributes: ["id"],
+ elements: ELEMENTS,
+ });
+
+ assert_true(s.allowAttribute("id"));
+ assert_config(s.get(), {
+ removeAttributes: [],
+ elements: ELEMENTS,
+ });
+
+ assert_false(s.allowAttribute("href"));
+ assert_config(s.get(), {
+ removeAttributes: [],
+ elements: ELEMENTS,
+ });
+
+ assert_false(s.allowAttribute("title"));
+ assert_config(s.get(), {
+ removeAttributes: [],
+ elements: ELEMENTS,
+ });
+}, "sanitizer.allowAttribute() with global removeAttributes and element's attributes");
+
+test(() => {
+ const ELEMENTS = [{ name: "div", removeAttributes: ["href"] }];
+
+ let s = new Sanitizer({
+ removeAttributes: ["id"],
+ elements: ELEMENTS,
+ });
+
+ assert_false(s.allowAttribute("class"));
+ assert_config(s.get(), {
+ removeAttributes: ["id"],
+ elements: ELEMENTS,
+ });
+
+ assert_true(s.allowAttribute("id"));
+ assert_config(s.get(), {
+ removeAttributes: [],
+ elements: ELEMENTS,
+ });
+
+ assert_false(s.allowAttribute("href"));
+ assert_config(s.get(), {
+ removeAttributes: [],
+ elements: ELEMENTS,
+ });
+
+ assert_false(s.allowAttribute("title"));
+ assert_config(s.get(), {
+ removeAttributes: [],
+ elements: ELEMENTS,
+ });
+}, "sanitizer.allowAttribute() with global removeAttributes and element's removeAttributes");
+
+
+test(() => {
+ let s = new Sanitizer({
+ attributes: ["id"],
+ });
+
+ assert_false(s.removeAttribute("title"));
+ assert_config(s.get(), { attributes: ["id"] });
+
+ assert_false(s.removeAttribute({ name: "id", namespace: NS }));
+ assert_config(s.get(), { attributes: ["id"] });
+
+ assert_true(s.removeAttribute("id"));
+ assert_config(s.get(), { attributes: [] });
+}, "sanitizer.removeAttribute() with global attributes");
+
+test(() => {
+ let s = new Sanitizer({
+ removeAttributes: ["id"],
+ });
+
+ assert_true(s.removeAttribute("title"));
+ assert_config(s.get(), { removeAttributes: ["id", "title"] });
+
+ assert_true(s.removeAttribute({ name: "id", namespace: NS }));
+ assert_config(s.get(), { removeAttributes: ["id", "title", { name: "id", namespace: NS }] });
+
+ assert_false(s.removeAttribute("id"));
+ assert_config(s.get(), { removeAttributes: ["id", "title", { name: "id", namespace: NS }] });
+}, "sanitizer.removeAttribute() with global removeAttributes");
+
+test(() => {
+ let s = new Sanitizer({
+ attributes: ["id", "title"],
+ elements: [{ name: "div", attributes: ["class", "dir"], removeAttributes: ["title"] }],
+ });
+
+ assert_true(s.removeAttribute("dir"));
+ assert_config(s.get(), {
+ attributes: ["id", "title"],
+ elements: [{ name: "div", attributes: ["class"], removeAttributes: ["title"] }],
+ });
+
+ assert_true(s.removeAttribute("id"));
+ assert_config(s.get(), {
+ attributes: ["title"],
+ elements: [{ name: "div", attributes: ["class"], removeAttributes: ["title"] }],
+ });
+
+ assert_false(s.removeAttribute("id"));
+ assert_config(s.get(), {
+ attributes: ["title"],
+ elements: [{ name: "div", attributes: ["class"], removeAttributes: ["title"] }],
+ });
+
+ assert_true(s.removeAttribute("title"));
+ assert_config(s.get(), {
+ attributes: [],
+ elements: [{ name: "div", attributes: ["class"], removeAttributes: [] }],
+ });
+
+ assert_true(s.removeAttribute("class"));
+ assert_config(s.get(), {
+ attributes: [],
+ elements: [{ name: "div", attributes: [], removeAttributes: [] }],
+ });
+}, "sanitizer.removeAttribute() with global attributes and elements");
+
+test(() => {
+ let s = new Sanitizer({
+ removeAttributes: ["title"],
+ elements: [{ name: "div", attributes: ["class"] }],
+ });
+
+ assert_false(s.removeAttribute({ name: "title", namespace: null }));
+ assert_config(s.get(), {
+ removeAttributes: ["title"],
+ elements: [{ name: "div", attributes: ["class"] }],
+ });
+
+ assert_true(s.removeAttribute("dir"));
+ assert_config(s.get(), {
+ removeAttributes: ["dir", "title"],
+ elements: [{ name: "div", attributes: ["class"] }],
+ });
+
+ assert_true(s.removeAttribute("class"));
+ assert_config(s.get(), {
+ removeAttributes: ["class", "dir", "title"],
+ elements: [{ name: "div", attributes: [] }],
+ });
+}, "sanitizer.removeAttribute() with global removeAttributes and element's attributes");
+
+test(() => {
+ let s = new Sanitizer({
+ removeAttributes: ["title"],
+ elements: [{ name: "div", removeAttributes: ["id"] }],
+ });
+
+ assert_false(s.removeAttribute({ name: "title", namespace: null }));
+ assert_config(s.get(), {
+ removeAttributes: ["title"],
+ elements: [{ name: "div", removeAttributes: ["id"] }],
+ });
+
+ assert_true(s.removeAttribute("dir"));
+ assert_config(s.get(), {
+ removeAttributes: ["dir", "title"],
+ elements: [{ name: "div", removeAttributes: ["id"] }],
+ });
+
+ assert_true(s.removeAttribute("id"));
+ assert_config(s.get(), {
+ removeAttributes: ["dir", "id", "title"],
+ elements: [{ name: "div", removeAttributes: [] }],
+ });
+}, "sanitizer.removeAttribute() with global removeAttributes and element's removeAttributes");
+
+test(() => {
+ let s = new Sanitizer({
+ elements: ["p", { name: "p", namespace: NS }],
+ replaceWithChildrenElements: ["b"],
+ });
+
+ assert_false(s.removeElement("span"));
+ assert_config(s.get(), {
+ elements: [{ name: "p", namespace: NS }, "p"],
+ replaceWithChildrenElements: ["b"],
+ });
+
+ assert_true(s.removeElement("b"));
+ assert_config(s.get(), {
+ elements: [{ name: "p", namespace: NS }, "p"],
+ replaceWithChildrenElements: [],
+ });
+
+ assert_true(s.removeElement("p"));
+ assert_config(s.get(), {
+ elements: [{ name: "p", namespace: NS }],
+ replaceWithChildrenElements: [],
+ });
+
+ assert_true(s.removeElement({ name: "p", namespace: NS }));
+ assert_config(s.get(), {
+ elements: [],
+ replaceWithChildrenElements: [],
+ });
+}, "sanitizer.removeElement() with global elements");
+
+test(() => {
+ let s = new Sanitizer({
+ removeElements: ["p", { name: "p", namespace: NS }],
+ replaceWithChildrenElements: ["b"],
+ });
+
+ assert_false(s.removeElement("p"));
+ assert_config(s.get(), {
+ removeElements: [{ name: "p", namespace: NS }, "p"],
+ replaceWithChildrenElements: ["b"],
+ });
+
+ assert_false(s.removeElement({ name: "p", namespace: NS }));
+ assert_config(s.get(), {
+ removeElements: [{ name: "p", namespace: NS }, "p"],
+ replaceWithChildrenElements: ["b"],
+ });
+
+ assert_true(s.removeElement("span"));
+ assert_config(s.get(), {
+ removeElements: [{ name: "p", namespace: NS }, "p", "span"],
+ replaceWithChildrenElements: ["b"],
+ });
+
+ assert_true(s.removeElement("b"));
+ assert_config(s.get(), {
+ removeElements: [{ name: "p", namespace: NS }, "b", "p", "span"],
+ replaceWithChildrenElements: [],
+ });
+}, "sanitizer.removeElement() with global removeElements");
+
+test(() => {
+ let s = new Sanitizer({
+ replaceWithChildrenElements: ["a"],
+ elements: ["b"],
+ });
+
+ assert_false(s.replaceElementWithChildren("a"));
+ assert_config(s.get(), {
+ replaceWithChildrenElements: ["a"],
+ elements: ["b"],
+ });
+
+ assert_true(s.replaceElementWithChildren("span"));
+ assert_config(s.get(), {
+ replaceWithChildrenElements: ["a", "span"],
+ elements: ["b"],
+ });
+
+ assert_true(s.replaceElementWithChildren("b"));
+ assert_config(s.get(), {
+ replaceWithChildrenElements: ["a", "b", "span"],
+ elements: [],
+ });
+}, "sanitizer.replaceElementWithChildren() with global elements");
+
+test(() => {
+ let s = new Sanitizer({
+ replaceWithChildrenElements: ["a"],
+ removeElements: ["b"],
+ });
+
+ assert_false(s.replaceElementWithChildren("a"));
+ assert_config(s.get(), {
+ replaceWithChildrenElements: ["a"],
+ removeElements: ["b"],
+ });
+
+ assert_true(s.replaceElementWithChildren("span"));
+ assert_config(s.get(), {
+ replaceWithChildrenElements: ["a", "span"],
+ removeElements: ["b"],
+ });
+
+ assert_true(s.replaceElementWithChildren("b"));
+ assert_config(s.get(), {
+ replaceWithChildrenElements: ["a", "b", "span"],
+ removeElements: [],
+ });
+}, "sanitizer.replaceElementWithChildren() with global removeElements");
+
+test(() => {
+ let s = new Sanitizer({
+ elements: ["a"],
+ replaceWithChildrenElements: ["b"]
+ });
+
+ assert_false(s.allowElement("a"));
+ assert_config(s.get(), {
+ elements: ["a"],
+ replaceWithChildrenElements: ["b"]
+ });
+
+ assert_true(s.allowElement({name: "a", namespace: NS}));
+ assert_config(s.get(), {
+ elements: [{name: "a", namespace: NS}, "a"],
+ replaceWithChildrenElements: ["b"]
+ });
+
+ assert_true(s.allowElement("b"));
+ assert_config(s.get(), {
+ elements: [{name: "a", namespace: NS}, "a", "b"],
+ replaceWithChildrenElements: []
+ });
+}, "sanitizer.allowElement() with global elements");
+
+test(() => {
+ let s = new Sanitizer({
+ removeElements: ["a"],
+ replaceWithChildrenElements: ["b"]
+ });
+
+ assert_false(s.allowElement("span"));
+ assert_config(s.get(), {
+ removeElements: ["a"],
+ replaceWithChildrenElements: ["b"]
+ });
+
+ assert_false(s.allowElement({name: "a", namespace: NS}));
+ assert_config(s.get(), {
+ removeElements: ["a"],
+ replaceWithChildrenElements: ["b"]
+ });
+
+ assert_true(s.allowElement("b"));
+ assert_config(s.get(), {
+ removeElements: ["a"],
+ replaceWithChildrenElements: []
+ });
+
+ // If element["attributes"] exists or element["removeAttributes"] with default « » is not empty:
+ // The user agent may report a warning to the console that this operation is not supported.
+ // Return false.
+ assert_false(s.allowElement({name: "a", attributes: ["dir"]}));
+ assert_config(s.get(), {
+ removeElements: ["a"],
+ replaceWithChildrenElements: []
+ });
+ assert_false(s.allowElement({name: "a", removeAttributes: ["dir"]}));
+ assert_config(s.get(), {
+ removeElements: ["a"],
+ replaceWithChildrenElements: []
+ });
+ assert_false(s.allowElement({name: "a", attributes: ["title"], removeAttributes: ["dir"]}));
+ assert_config(s.get(), {
+ removeElements: ["a"],
+ replaceWithChildrenElements: []
+ });
+ assert_true(s.allowElement({name: "a", removeAttributes: [] }));
+ assert_config(s.get(), {
+ removeElements: [],
+ replaceWithChildrenElements: []
+ });
+}, "sanitizer.allowElement() with global removeElements");
+
+test(() => {
+ let s = new Sanitizer({
+ elements: [],
+ attributes: ["id"]
+ });
+
+ assert_true(s.allowElement({name: "p", attributes: ["id", "title"]}));
+ assert_config(s.get(), {
+ elements: [{name: "p", attributes: ["title"], removeAttributes: undefined}]
+ });
+ // Duplicate
+ assert_false(s.allowElement({name: "p", attributes: ["id", "title"]}));
+ assert_config(s.get(), {
+ elements: [{name: "p", attributes: ["title"], removeAttributes: undefined}]
+ });
+
+
+ assert_true(s.allowElement({name: "p", removeAttributes: ["id", "class"]}));
+ assert_config(s.get(), {
+ elements: [{name: "p", attributes: undefined, removeAttributes: ["id"]}]
+ })
+ // Duplicate
+ assert_false(s.allowElement({name: "p", removeAttributes: ["id", "class"]}));
+ assert_config(s.get(), {
+ elements: [{name: "p", attributes: undefined, removeAttributes: ["id"]}]
+ })
+
+
+ assert_true(s.allowElement({name: "p", attributes: ["id", "dir"], removeAttributes: ["id", "lang"]}));
+ assert_config(s.get(), {
+ elements: [{name: "p", attributes: ["dir"], removeAttributes: ["id"]}]
+ });
+ // Duplicate
+ assert_false(s.allowElement({name: "p", attributes: ["id", "dir"], removeAttributes: ["id", "lang"]}));
+ assert_config(s.get(), {
+ elements: [{name: "p", attributes: ["dir"], removeAttributes: ["id"]}]
+ });
+
+
+ assert_true(s.allowElement({name: "p"}));
+ assert_config(s.get(), {
+ elements: [{name: "p", attributes: undefined, removeAttributes: []}]
+ });
+
+ assert_false(s.allowElement("p"));
+ assert_config(s.get(), {
+ elements: [{name: "p", attributes: undefined, removeAttributes: []}]
+ });
+
+ // Set element["attributes"] to remove duplicates from element["attributes"].
+ assert_true(s.allowElement({name: "p", attributes: ["dir", "dir"]}));
+ assert_config(s.get(), {
+ elements: [{name: "p", attributes: ["dir"], removeAttributes: undefined}]
+ });
+
+ // Set element["removeAttributes"] to remove duplicates from element["removeAttributes"].
+ assert_true(s.allowElement({name: "p", removeAttributes: ["id", "id"]}));
+ assert_config(s.get(), {
+ elements: [{name: "p", attributes: undefined, removeAttributes: ["id"]}]
+ });
+
+ assert_true(s.allowElement({name: "p", attributes: ["dir", "dir"], removeAttributes: ["id", "id"]}));
+ assert_config(s.get(), {
+ elements: [{name: "p", attributes: ["dir"], removeAttributes: ["id"]}]
+ });
+}, "sanitizer.allowElement() with global elements and attributes");
+
+test(() => {
+ let s = new Sanitizer({
+ elements: [],
+ removeAttributes: ["id"]
+ });
+
+ assert_true(s.allowElement({name: "p", attributes: ["id", "title"]}));
+ assert_config(s.get(), {
+ elements: [{name: "p", attributes: ["title"], removeAttributes: undefined}]
+ });
+ // Duplicate
+ assert_false(s.allowElement({name: "p", attributes: ["id", "title"]}));
+ assert_config(s.get(), {
+ elements: [{name: "p", attributes: ["title"], removeAttributes: undefined}]
+ });
+
+ assert_true(s.allowElement({name: "p", removeAttributes: ["id", "class"]}));
+ assert_config(s.get(), {
+ elements: [{name: "p", attributes: undefined, removeAttributes: ["class"]}]
+ });
+ // Duplicate
+ assert_false(s.allowElement({name: "p", removeAttributes: ["id", "class"]}));
+ assert_config(s.get(), {
+ elements: [{name: "p", attributes: undefined, removeAttributes: ["class"]}]
+ });
+
+ assert_true(s.allowElement({ name: "p", attributes: ["id", "dir", "lang"], removeAttributes: ["id", "lang"] }))
+ assert_config(s.get(), {
+ elements: [{name: "p", attributes: ["dir"], removeAttributes: undefined}]
+ });
+ // Duplicate
+ assert_false(s.allowElement({ name: "p", attributes: ["id", "dir", "lang"], removeAttributes: ["id", "lang"] }))
+ assert_config(s.get(), {
+ elements: [{name: "p", attributes: ["dir"], removeAttributes: undefined}]
+ });
+
+ assert_true(s.allowElement({name: "p"}));
+ assert_config(s.get(), {
+ elements: [{name: "p", attributes: undefined, removeAttributes: []}]
+ });
+
+ assert_false(s.allowElement("p"));
+ assert_config(s.get(), {
+ elements: [{name: "p", attributes: undefined, removeAttributes: []}]
+ });
+}, "sanitizer.allowElement() with global elements and removeAttributes");
+
+test(() => {
+ for (let element of NON_REPLACEABLE_ELEMENTS) {
+ let s = new Sanitizer();
+ assert_false(s.replaceElementWithChildren(element));
+ assert_config(s.get(), { replaceWithChildrenElements: undefined });
+ }
+}, "sanitizer.replaceElementWithChildren() does not allow non-replaceable elements.");
+
+test(() => {
+ let s = new Sanitizer();
+ assert_false(s.setJavascriptURLs(false));
+ assert_config(s.get(), { javascriptURLs: false });
+
+ assert_true(s.setJavascriptURLs(true));
+ assert_config(s.get(), { javascriptURLs: true });
+
+ assert_false(s.setJavascriptURLs(true));
+ assert_config(s.get(), { javascriptURLs: true });
+
+ assert_true(s.setJavascriptURLs(false));
+ assert_config(s.get(), { javascriptURLs: false });
+}, "sanitizer.setJavascriptURLs()");
+
+test(() => {
+ let s = new Sanitizer();
+ assert_false(s.setComments(false));
+ assert_config(s.get(), { comments: false });
+
+ assert_true(s.setComments(true));
+ assert_config(s.get(), { comments: true });
+
+ assert_false(s.setComments(true));
+ assert_config(s.get(), { comments: true });
+
+ assert_true(s.setComments(false));
+ assert_config(s.get(), { comments: false });
+}, "sanitizer.setComments()");
+
+test(() => {
+ let s = new Sanitizer({ attributes: [] });
+ assert_false(s.setDataAttributes(true));
+ assert_config(s.get(), { dataAttributes: true, attributes: [] });
+
+ assert_true(s.setDataAttributes(false));
+ assert_config(s.get(), { dataAttributes: false, attributes: [] });
+
+ assert_false(s.setDataAttributes(false));
+ assert_config(s.get(), { dataAttributes: false, attributes: [] });
+
+ assert_true(s.setDataAttributes(true));
+ assert_config(s.get(), { dataAttributes: true, attributes: [] });
+}, "sanitizer.setDataAttributes()");
+</script>
+</body>
+</html>
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-parseHTML.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-parseHTML.html
new file mode 100644
index 00000000000..a3583ba5c95
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-parseHTML.html
@@ -0,0 +1,435 @@
+<!DOCTYPE html>
+<head>
+<title>Testcases for parseHTML and parseHTMLUnsafe</title>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="support/html5lib-testcase-support.js"></script>
+<!--
+ This is a set of basic Sanitizer test cases using the parseHTML and
+ parseHTMLUnsafe methods.
+-->
+<script id="all" type="html5lib-testcases">
+#data
+text
+#document
+| <html>
+| <head>
+| <body>
+| "text"
+
+#data
+<div>text
+#config
+{ "elements": ["html", "body", "div"] }
+#document
+| <html>
+| <body>
+| <div>
+| "text"
+
+#data
+<div>text
+#config
+{ "elements": ["body", "div"] }
+#document
+
+#data
+<div>text
+#config
+{ "elements": ["html", "div"] }
+#document
+| <html>
+
+#data
+<html onload="3 + 3"><div>a
+#config
+{ "replaceWithChildrenElements": ["html"], "elements": ["head", "body", "div"] }
+#error
+TypeError
+
+#data
+<body><body onload="alert(1)">Hello
+#config
+{ "attributes": [] }
+#document
+| <html>
+| <head>
+| <body>
+| "Hello"
+
+#data
+<!-- a --><html><body>x<!-- b --></body></html><!-- c -->
+#config
+{ "comments": false }
+#document
+| <html>
+| <head>
+| <body>
+| "x"
+
+#data
+<?a b?><html><body>x<?c d?></body></html><?e f?>
+#config
+{ "processingInstructions": [] }
+#document
+| <html>
+| <head>
+| <body>
+| "x"
+
+#data
+x<p>y
+#config
+{ "replaceWithChildrenElements": ["head", "body"] }
+#document
+| <html>
+| "x"
+| <p>
+| "y"
+
+#data
+<noscript><p>x</noscript>y
+#config
+{}
+#document
+| <html>
+| <head>
+| <noscript>
+| <body>
+| <p>
+| "xy"
+
+#data
+<noscript><p>x</noscript>y
+#config
+{ "elements": ["html", "head", "body", "noscript", "p"] }
+#document
+| <html>
+| <head>
+| <noscript>
+| <body>
+| <p>
+| "xy"
+
+</script>
+<script id="safe" type="html5lib-testcases">
+#data
+<script>hello
+#document
+| <html>
+| <head>
+| <body>
+
+#data
+<html onload="2+2"><body onload="3+3"><div>hello
+#document
+| <html>
+| <head>
+| <body>
+| <div>
+| "hello"
+
+#data
+<div data-xyz="1" id="2" title="3">
+#config
+{ "attributes": ["id"] }
+#document
+| <html>
+| <head>
+| <body>
+| <div>
+| id="2"
+
+#data
+<div>a<!-- xx -->b
+#config
+{ }
+#document
+| <html>
+| <head>
+| <body>
+| <div>
+| "ab"
+
+#data
+<html onload="2 + 2"><div>a
+#config
+{ "replaceWithChildrenElements": ["html"], "removeElements": [] }
+#error
+TypeError
+
+#data
+<br id="document">
+#config
+{"elements": [{ "name":"br", "attributes":[] }, "html", "body"]}
+#document
+| <html>
+| <body>
+| <br>
+
+#data
+<br id="document">
+#config
+{"elements": [{ "name":"br", "attributes":[] }, "html", "body"], "attributes":[]}
+#document
+| <html>
+| <body>
+| <br>
+
+#data
+<p onclick="alert(document.cookie)">Click handler!</p>
+#config
+{"elements": [{ "name":"p", "attributes":["onclick"] }, "html", "body"], "attributes":[]}
+#document
+#document
+| <html>
+| <body>
+| <p>
+| "Click handler!"
+
+#data
+<p onclick="alert(document.cookie)">Click handler!</p>
+#config
+{"elements": [{ "name":"p", "attributes":["onclick"] }, "html", "body"]}
+#document
+#document
+| <html>
+| <body>
+| <p>
+| "Click handler!"
+
+#data
+<noscript><p>x</noscript>y
+#document
+| <html>
+| <head>
+| <body>
+| <p>
+| "xy"
+
+</script>
+<script id="unsafe" type="html5lib-testcases">
+#data
+<script>hello
+#document
+| <html>
+| <head>
+| <script>
+| "hello"
+| <body>
+
+#data
+<html onload="2+2"><body onload="3+3"><div>hello
+#document
+| <html>
+| onload="2+2"
+| <head>
+| <body>
+| onload="3+3"
+| <div>
+| "hello"
+
+#data
+<div data-xyz="1" id="2" title="3">
+#config
+{ "attributes": ["id"] }
+#document
+| <html>
+| <head>
+| <body>
+| <div>
+| data-xyz="1"
+| id="2"
+
+#data
+<div>a<!-- xx -->b
+#config
+{ }
+#document
+| <html>
+| <head>
+| <body>
+| <div>
+| "a"
+| <!-- xx -->
+| "b"
+
+#data
+<html onload="2 + 2"><div>a
+#config
+{ "replaceWithChildrenElements": ["html"], "removeElements": [] }
+#error
+TypeError
+
+#data
+<div>a<!-- xx -->b
+#document
+| <html>
+| <head>
+| <body>
+| <div>
+| "a"
+| <!-- xx -->
+| "b"
+
+#data
+<!-- 1 --><html><body>x<!-- 2 --></body></html><!-- 3 -->
+#document
+| <!-- 1 -->
+| <html>
+| <head>
+| <body>
+| "x"
+| <!-- 2 -->
+| <!-- 3 -->
+
+#data
+a<template>x</template>b
+#config
+{ "replaceWithChildrenElements": ["template"] }
+#document
+| <html>
+| <head>
+| <body>
+| "ab"
+
+#data
+<noscript><p>x</noscript>y
+#document
+| <html>
+| <head>
+| <noscript>
+| <body>
+| <p>
+| "xy"
+
+#data
+<head><meta></head><body>x
+#config
+{ "replaceWithChildrenElements": ["head"] }
+#document
+| <html>
+| <meta>
+| <body>
+| "x"
+
+#data
+<head></head><body>x<p>y
+#config
+{ "replaceWithChildrenElements": ["body"] }
+#document
+| <html>
+| <head>
+| "x"
+| <p>
+| "y"
+
+#data
+<head></head><meta><body>x
+#config
+{ "replaceWithChildrenElements": ["head"] }
+#document
+| <html>
+| <meta>
+| <body>
+| "x"
+
+#data
+<div></div><frameset>
+#config
+{ "replaceWithChildrenElements": ["body"] }
+#document
+| <html>
+| <head>
+| <div>
+| <frameset>
+
+#data
+<div></div><frameset>
+#config
+{ "removeElements": ["body"] }
+#document
+| <html>
+| <head>
+| <frameset>
+
+</script>
+<script id="document" type="html5lib-testcases">
+#data
+<!DOCTYPE html>
+text
+#document
+| <!DOCTYPE html "" "">
+| <html>
+| <head>
+| <body>
+| "text"
+
+</script>
+<script>
+function test_safe(testcase, index) {
+ let config = undefined;
+ if (testcase.config) {
+ config = { sanitizer: JSON.parse(testcase.config) };
+ }
+ test(_ => {
+ if (testcase.error) {
+ assert_throws_js(globalThis[testcase.error],
+ () => Document.parseHTML(testcase.data, config));
+ } else {
+ assert_testcase(Document.parseHTML(testcase.data, config), testcase);
+ }
+ }, `parseHTML testcase ${index}, "${testcase.data}"`);
+}
+function test_unsafe(testcase, index) {
+ let config = undefined;
+ if (testcase.config) {
+ config = { sanitizer: JSON.parse(testcase.config) };
+ }
+ test(_ => {
+ if (testcase.error) {
+ assert_throws_js(globalThis[testcase.error],
+ () => Document.parseHTMLUnsafe(testcase.data, config));
+ } else {
+ assert_testcase(Document.parseHTMLUnsafe(testcase.data, config), testcase);
+ }
+ }, `parseHTMLUnsafe testcase ${index}, "${testcase.data}"`);
+}
+
+const all = parse_html5lib_testcases(
+ document.getElementById("all").textContent);
+const safe = parse_html5lib_testcases(
+ document.getElementById("safe").textContent);
+const unsafe = parse_html5lib_testcases(
+ document.getElementById("unsafe").textContent);
+all.concat(safe).forEach(test_safe);
+all.concat(unsafe).forEach(test_unsafe);
+
+// Without an options argument there is no sanitizer, so nothing is removed.
+test(_ => {
+ const doc = Document.parseHTMLUnsafe("<div>a<!-- xx -->b");
+ const div = doc.body.firstChild;
+ assert_equals(div.childNodes.length, 3);
+ assert_equals(div.childNodes[1].nodeType, Node.COMMENT_NODE);
+ assert_equals(div.childNodes[1].data, " xx ");
+}, "parseHTMLUnsafe() without options keeps comments");
+
+
+// DOM only supports Document Type Declarations as children of documents. This
+// trips up the assert_testcase implementation, so we'll handle that seperately.
+parse_html5lib_testcases(
+ document.getElementById("document").textContent).
+ forEach((testcase, index) => {
+ test(_ => {
+ const tree = build_node_tree(new Document(), testcase.document);
+ assert_subtree_equals(Document.parseHTMLUnsafe(testcase.data, {}), tree);
+ }, `parseHTMLUnsafe full document testcase ${index}, "${testcase.data}"`);
+ test(_ => {
+ const tree = build_node_tree(new Document(), testcase.document);
+ assert_subtree_equals(Document.parseHTML(testcase.data, {}), tree);
+ }, `parseHTML full document testcase ${index}, "${testcase.data}"`);
+});
+</script>
+</head>
+<body>
+</body>
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-processing-instructions.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-processing-instructions.html
new file mode 100644
index 00000000000..da68a2f06ad
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-processing-instructions.html
@@ -0,0 +1,166 @@
+<!doctype html>
+<head>
+<title>Sanitizer API: Processing Instructions</title>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="support/html5lib-testcase-support.js"></script>
+
+<script id="agnostic" type="html5lib-testcases">
+#data
+<?target data?>
+#config
+{ "processingInstructions": ["target"] }
+#document
+| <?target data?>
+
+#data
+<?target data?>
+#config
+{ "processingInstructions": [{ "target": "target" }] }
+#document
+| <?target data?>
+
+#data
+<?Target data?>
+#config
+{ "processingInstructions": ["target"] }
+#document
+
+#data
+<?target data?>
+#config
+{ "processingInstructions": ["Target"] }
+#document
+
+#data
+<?target-1 data?><?target-2 data?>
+#config
+{ "processingInstructions": ["target-1", "target-2"] }
+#document
+| <?target-1 data?>
+| <?target-2 data?>
+
+#data
+<?target-1 data?><?target-2 data?>
+#config
+{ "processingInstructions": ["target-1"] }
+#document
+| <?target-1 data?>
+
+#data
+<div><?target data?></div>
+#config
+{ "processingInstructions": ["target"] }
+#document
+| <div>
+| <?target data?>
+
+#data
+<div><?unlisted-target data?></div>
+#config
+{ "processingInstructions": ["allowed-target"] }
+#document
+| <div>
+
+</script>
+
+<script id="unsafe-only" type="html5lib-testcases">
+#data
+<?target data?>
+#config
+{ "removeProcessingInstructions": ["target"] }
+#document
+
+#data
+<?target data?>
+#config
+{ "removeProcessingInstructions": [{ "target": "target" }] }
+#document
+
+#data
+<div><?target data?></div>
+#config
+{ "removeProcessingInstructions": ["target"] }
+#document
+| <div>
+
+#data
+<div><?target data?></div>
+#config
+{}
+#document
+| <div>
+| <?target data?>
+
+</script>
+
+<script id="safe-only" type="html5lib-testcases">
+#data
+<div><?target data?></div>
+#config
+{}
+#document
+| <div>
+
+</script>
+<script>
+ for (const group of document.querySelectorAll(
+ "script[type='html5lib-testcases']",
+ )) {
+ const type = group.id;
+ parse_html5lib_testcases(group.textContent).forEach((testcase, index) => {
+ let config = undefined;
+ if (testcase.config) {
+ config = { sanitizer: JSON.parse(testcase.config) };
+ }
+
+ if (type !== "safe-only") {
+ test((_) => {
+ const div = document.createElement("div");
+ div.setHTMLUnsafe(testcase.data, config);
+ assert_testcase(div, testcase);
+ }, `setHTMLUnsafe testcase ${group.id}/${index}, "${testcase.data}"`);
+ test((_) => {
+ const div = document.createElement("div");
+ const shadowRoot = div.attachShadow({ mode: "open" });
+ shadowRoot.setHTMLUnsafe(testcase.data, config);
+ assert_testcase(shadowRoot, testcase);
+ }, `ShadowRoot.setHTMLUnsafe testcase ${group.id}/${index}, "${testcase.data}"`);
+ }
+
+ if (type !== "unsafe-only") {
+ test((_) => {
+ const div = document.createElement("div");
+ div.setHTML(testcase.data, config);
+ assert_testcase(div, testcase);
+ }, `setHTML testcase ${group.id}/${index}, "${testcase.data}"`);
+
+ test((_) => {
+ const div = document.createElement("div");
+ const shadowRoot = div.attachShadow({ mode: "open" });
+ shadowRoot.setHTML(testcase.data, config);
+ assert_testcase(shadowRoot, testcase);
+ }, `ShadowRoot.setHTML testcase ${group.id}/${index}, "${testcase.data}"`);
+ }
+
+ if (type !== "unsafe-only") {
+ test((_) => {
+ // Wrap in a div to ensure the processing instruction goes into the body.
+ const doc = Document.parseHTML(`<div>${testcase.data}</div>`, config);
+ assert_testcase(doc.body.firstChild, testcase);
+ }, `parseHTML testcase ${group.id}/${index}, "${testcase.data}"`);
+ }
+
+ if (type !== "safe-only") {
+ test((_) => {
+ // Wrap in a div to ensure the processing instruction goes into the body.
+ const doc = Document.parseHTMLUnsafe(
+ `<div>${testcase.data}</div>`, config);
+ assert_testcase(doc.body.firstChild, testcase);
+ }, `parseHTMLUnsafe testcase ${group.id}/${index}, "${testcase.data}"`);
+ }
+ });
+ }
+</script>
+</head>
+<body></body>
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-removeUnsafe.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-removeUnsafe.html
new file mode 100644
index 00000000000..ad2c8b70556
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-removeUnsafe.html
@@ -0,0 +1,148 @@
+<!DOCTYPE html>
+<html>
+<head>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+</head>
+<body>
+<script>
+test(t => {
+ // Create an empty config.
+ let s = new Sanitizer({});
+ // Remove everything unsafe.
+ s.removeUnsafe();
+
+ let config = s.get();
+ assert_false('elements' in config, "no elements");
+ assert_false('replaceWithChildrenElements' in config, "no replaceWithChildrenElements");
+ assert_false('attributes' in config, "no attributes");
+ assert_false(config.javascriptURLs, "javascriptURLs is false");
+
+ // https://wicg.github.io/sanitizer-api/#built-in-safe-baseline-configuration
+ const SAFE_BASELINE = {
+ "removeElements": [
+ {
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "name": "base"
+ },
+ {
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "name": "embed"
+ },
+ {
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "name": "frame"
+ },
+ {
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "name": "iframe"
+ },
+ {
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "name": "object"
+ },
+ {
+ "namespace": "http://www.w3.org/1999/xhtml",
+ "name": "script"
+ },
+ {
+ "namespace": "http://www.w3.org/2000/svg",
+ "name": "script"
+ },
+ {
+ "namespace": "http://www.w3.org/2000/svg",
+ "name": "use"
+ }
+ ],
+ "removeAttributes": []
+ };
+
+ assert_equals(config.removeElements.length, SAFE_BASELINE.removeElements.length);
+ for (let i = 0; i < SAFE_BASELINE.removeElements.length; i++) {
+ let element = config.removeElements[i];
+ assert_own_property(element, "name");
+ assert_equals(element.name, SAFE_BASELINE.removeElements[i].name);
+ assert_own_property(element, "namespace");
+ assert_equals(element.namespace, SAFE_BASELINE.removeElements[i].namespace);
+ }
+
+ // This list depends on the implementation defined "event handler content attributes"
+ assert_true(config.removeAttributes.length > 0, "Has removeAttributes");
+ for (let attribute of config.removeAttributes) {
+ assert_own_property(attribute, "name");
+ assert_true(attribute.name.startsWith("on"), `attribute '${attribute.name}' starts with "on"`);
+ assert_own_property(attribute, "namespace"); // XXX Maybe optional?
+ assert_equals(attribute.namespace, null, "attribute is in null namespace");
+ }
+}, "removeUnsafe removes the right elements and attributes");
+
+test(t => {
+ let s = new Sanitizer("default");
+ let before = s.get();
+
+ let s2 = new Sanitizer("default");
+ s2.removeUnsafe();
+ let after = s2.get();
+
+ // None of the default config elements are unsafe.
+ assert_true(before.elements.length > 0);
+ assert_equals(before.elements.length, after.elements.length, "elements don't change");
+
+ // None of the default config attributes are unsafe.
+ assert_true(before.attributes.length > 0);
+ assert_equals(before.attributes.length, after.attributes.length, "attributes don't change");
+
+ assert_false(before.javascriptURLs);
+ assert_false(after.javascriptURLs);
+
+ // Not in default config.
+ assert_false('replaceWithChildrenElements' in before);
+ assert_false('replaceWithChildrenElements' in after);
+ assert_false('removeElements' in before);
+ assert_false('removeElements' in after);
+ assert_false('removeAttributes' in before);
+ assert_false('removeAttributes' in after);
+}, "removeUnsafe with default config");
+
+test(t => {
+ let s = new Sanitizer({ javascriptURLs: true });
+ assert_true(s.get().javascriptURLs);
+ let changed = s.removeUnsafe();
+ assert_true(changed);
+ assert_false(s.get().javascriptURLs);
+
+ let s2 = new Sanitizer({ javascriptURLs: false });
+ assert_false(s2.get().javascriptURLs);
+ s2.removeUnsafe();
+ assert_false(s2.get().javascriptURLs);
+}, "removeUnsafe sets javascriptURLs to false");
+
+// https://wicg.github.io/sanitizer-api/#built-in-safe-baseline-configuration
+// The baseline remove list is namespace specific: only script in the HTML and
+// SVG namespaces and use in the SVG namespace are unsafe.
+const HTML_NS = "http://www.w3.org/1999/xhtml";
+const SVG_NS = "http://www.w3.org/2000/svg";
+const MATHML_NS = "http://www.w3.org/1998/Math/MathML";
+[
+ [ { name: "script", namespace: HTML_NS }, "<script><\/script>", "" ],
+ [ { name: "script", namespace: SVG_NS }, "<svg><script><\/script></svg>",
+ "<svg></svg>" ],
+ [ { name: "use", namespace: SVG_NS }, "<svg><use></use></svg>",
+ "<svg></svg>" ],
+ // An element named "use" in the HTML namespace is not in the baseline list.
+ [ { name: "use", namespace: HTML_NS }, "<use>text</use>" ],
+ // Neither is a MathML element named "script".
+ [ { name: "script", namespace: MATHML_NS },
+ "<math><script><\/script></math>" ],
+].forEach(([element, probe, expected], index) => {
+ test(t => {
+ const elements = [element, { name: "svg", namespace: SVG_NS },
+ { name: "math", namespace: MATHML_NS }];
+ const div = document.createElement("div");
+ div.setHTML(probe, { sanitizer: { elements } });
+ assert_equals(div.innerHTML, expected ?? probe);
+ }, `Baseline remove list is namespace specific #${index}: ${JSON.stringify(element)}`);
+});
+</script>
+</body>
+</html>
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-script-tokenizer.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-script-tokenizer.html
new file mode 100644
index 00000000000..29d81666947
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-script-tokenizer.html
@@ -0,0 +1,30 @@
+<!DOCTYPE html>
+<html>
+<head>
+<meta charset="utf-8">
+<title>Sanitizer: script and raw text tokenizer state during sanitization</title>
+<link rel="help" href="https://github.com/whatwg/html/pull/12756">
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="support/html5lib-testcase-support.js"></script>
+</head>
+<body>
+<script>
+promise_test(async () => {
+ const testcases = await html5lib_testcases_from_response(fetch("sanitizer-script-tokenizer.sub.dat"));
+ testcases.forEach((testcase, index) => {
+ test(() => {
+ const context = document.createElement(testcase["document-fragment"] ?? "div");
+ let config = undefined;
+ if (testcase.config) {
+ config = { sanitizer: JSON.parse(testcase.config) };
+ }
+ const method = testcase.method ?? "setHTML";
+ context[method](testcase.data, config);
+ assert_testcase(context, testcase);
+ }, `Testcase #${index} [${testcase.method ?? "setHTML"}], "${testcase.data}", config: "${testcase.config ?? "{}"}"`);
+ });
+}, "Sanitizer script and raw text tokenizer testcases from sub.dat");
+</script>
+</body>
+</html>
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-script-tokenizer.sub.dat b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-script-tokenizer.sub.dat
new file mode 100644
index 00000000000..7a5623da9dd
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sanitizer-script-tokenizer.sub.dat
@@ -0,0 +1,80 @@
+#data
+<script><img src=x onerror='window.scriptRan=true;'><div>content</div></script>
+#method
+setHTML
+#document
+
+#data
+<script><img src=x onerror='window.scriptRan=true;'><div>content</div></script>
+#method
+setHTML
+#config
+{ "removeElements": ["script"] }
+#document
+
+#data
+<script><b>bold text</b><img src=x></script>
+#method
+setHTMLUnsafe
+#config
+{ "replaceWithChildrenElements": ["script"] }
+#document
+| "<b>bold text</b><img src=x>"
+
+#data
+<style><img src=x><div>test</div></style>
+#method
+setHTMLUnsafe
+#config
+{ "replaceWithChildrenElements": ["style"] }
+#document
+| "<img src=x><div>test</div>"
+
+#data
+<textarea><img src=x><div>test</div></textarea>
+#method
+setHTMLUnsafe
+#config
+{ "replaceWithChildrenElements": ["textarea"] }
+#document
+| "<img src=x><div>test</div>"
+
+#data
+<script><b>Hello</b></script>
+#method
+setHTML
+#config
+{ "replaceWithChildrenElements": ["script"] }
+#document
+
+#data
+<script><b>Hello</b></script>
+#method
+setHTMLUnsafe
+#config
+{ "removeElements": ["script"] }
+#document
+
+#data
+<p>before</p><script><b>bold text</b><img src=x></script><p>after</p>
+#method
+setHTMLUnsafe
+#config
+{ "replaceWithChildrenElements": ["script"] }
+#document
+| <p>
+| "before"
+| "<b>bold text</b><img src=x>"
+| <p>
+| "after"
+
+#data
+<p>before</p><script><b>bold text</b><img src=x></script><p>after</p>
+#method
+setHTML
+#document
+| <p>
+| "before"
+| <p>
+| "after"
+
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-custom-element-reactions.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-custom-element-reactions.html
new file mode 100644
index 00000000000..bdaed32f4c0
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-custom-element-reactions.html
@@ -0,0 +1,56 @@
+<!DOCTYPE html>
+<head>
+<title>setHTML() and setHTMLUnsafe() with a sanitizer run custom element reactions before returning</title>
+<link rel="help" href="https://html.spec.whatwg.org/#dom-element-sethtml">
+<link rel="help" href="https://html.spec.whatwg.org/#dom-shadowroot-sethtml">
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+</head>
+<body>
+<script>
+// The methods are [CEReactions], so the reactions queued while they run
+// (construction and connectedCallback for the parsed elements, then
+// disconnectedCallback for the replaced children) are invoked before they
+// return.
+// setHTMLUnsafe() without a sanitizer is covered by
+// /html/webappapis/dynamic-markup-insertion/html-unsafe-methods/setHTMLUnsafe-CEReactions.html.
+const log = [];
+customElements.define("x-reaction", class extends HTMLElement {
+ constructor() { super(); log.push("constructed"); }
+ connectedCallback() { log.push("connected"); }
+ disconnectedCallback() { log.push("disconnected"); }
+});
+
+const allow = { sanitizer: { elements: ["x-reaction"] } };
+
+for (const [name, run] of [
+ ["Element.setHTML", target => target.setHTML("<x-reaction></x-reaction>", allow)],
+ ["Element.setHTMLUnsafe", target => target.setHTMLUnsafe("<x-reaction></x-reaction>", allow)],
+ ["ShadowRoot.setHTML", target => target.shadowRoot.setHTML("<x-reaction></x-reaction>", allow)],
+ ["ShadowRoot.setHTMLUnsafe", target => target.shadowRoot.setHTMLUnsafe("<x-reaction></x-reaction>", allow)],
+]) {
+ const parentOf = target => name.startsWith("ShadowRoot")
+ ? target.attachShadow({ mode: "open" }) : target;
+
+ test(t => {
+ const target = document.createElement("div");
+ document.body.append(target);
+ t.add_cleanup(() => target.remove());
+ parentOf(target);
+ log.length = 0;
+ run(target);
+ assert_array_equals(log, ["constructed", "connected"]);
+ }, `${name} with a sanitizer runs custom element reactions before returning`);
+
+ test(t => {
+ const target = document.createElement("div");
+ document.body.append(target);
+ t.add_cleanup(() => target.remove());
+ parentOf(target).append(document.createElement("x-reaction"));
+ log.length = 0;
+ run(target);
+ assert_array_equals(log, ["constructed", "connected", "disconnected"]);
+ }, `${name} with a sanitizer runs disconnectedCallback for the replaced children before returning`);
+}
+</script>
+</body>
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-form-owner.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-form-owner.html
new file mode 100644
index 00000000000..27c394fda9e
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-form-owner.html
@@ -0,0 +1,49 @@
+<!DOCTYPE html>
+<head>
+<title>Form owner after the form element is replaced with its children</title>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+</head>
+<body>
+<script>
+const input = '<form id="f"><input name="i"></form>';
+
+test(t => {
+ const div = document.createElement("div");
+ div.setHTMLUnsafe(input);
+ const form = div.firstChild;
+ assert_equals(form.localName, "form");
+ assert_equals(form.firstChild.form, form);
+}, "Without a sanitizer, the input's form owner is the parsed form");
+
+test(t => {
+ const div = document.createElement("div");
+ div.setHTMLUnsafe(input,
+ { sanitizer: { replaceWithChildrenElements: ["form"] } });
+ assert_equals(div.childNodes.length, 1);
+ const control = div.firstChild;
+ assert_equals(control.localName, "input");
+ assert_equals(control.name, "i");
+ assert_equals(control.form, null);
+}, "With the form replaced with its children, the input has no form owner");
+
+// The form element pointer condition is only reachable in a full document
+// parse, i.e. parseHTMLUnsafe().
+test(t => {
+ const doc = Document.parseHTMLUnsafe(input);
+ const form = doc.querySelector("form");
+ assert_not_equals(form, null);
+ assert_equals(doc.querySelector("input").form, form);
+}, "parseHTMLUnsafe(): without a sanitizer, the input's form owner is the parsed form");
+
+test(t => {
+ const doc = Document.parseHTMLUnsafe(input,
+ { sanitizer: { replaceWithChildrenElements: ["form"] } });
+ assert_equals(doc.querySelector("form"), null);
+ const control = doc.querySelector("input");
+ assert_not_equals(control, null);
+ assert_equals(control.name, "i");
+ assert_equals(control.form, null);
+}, "parseHTMLUnsafe(): with the form replaced with its children, the input has no form owner");
+</script>
+</body>
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-noscript.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-noscript.html
new file mode 100644
index 00000000000..13d40ea0b49
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-noscript.html
@@ -0,0 +1,51 @@
+<!DOCTYPE html>
+<head>
+<title>setHTML() and setHTMLUnsafe() parse noscript with scripting disabled</title>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+</head>
+<body>
+<script>
+// The fragment parsing algorithm steps set the scripting mode to inert, so
+// <noscript> is parsed as raw text regardless of the options passed.
+const input = "<noscript><p>x</noscript>y";
+
+function assert_raw_text_noscript(div) {
+ assert_equals(div.childNodes.length, 2, "two child nodes");
+ const noscript = div.firstChild;
+ assert_equals(noscript.localName, "noscript");
+ assert_equals(noscript.childNodes.length, 1, "noscript has one child");
+ assert_equals(noscript.firstChild.nodeType, Node.TEXT_NODE);
+ assert_equals(noscript.firstChild.data, "<p>x");
+ assert_equals(div.lastChild.nodeType, Node.TEXT_NODE);
+ assert_equals(div.lastChild.data, "y");
+}
+
+for (const [name, options] of [
+ ["no options", undefined],
+ ["empty options", {}],
+ ["sanitizer: undefined", { sanitizer: undefined }],
+ ["empty sanitizer config", { sanitizer: {} }],
+]) {
+ test(t => {
+ const div = document.createElement("div");
+ div.setHTMLUnsafe(input, options);
+ assert_raw_text_noscript(div);
+ }, `setHTMLUnsafe() parses noscript as raw text (${name})`);
+}
+
+test(t => {
+ const div = document.createElement("div");
+ div.setHTML(input, { sanitizer: { elements: ["noscript"] } });
+ assert_raw_text_noscript(div);
+}, "setHTML() parses noscript as raw text when noscript is allowed");
+
+test(t => {
+ const div = document.createElement("div");
+ div.setHTML(input);
+ assert_equals(div.childNodes.length, 1);
+ assert_equals(div.firstChild.nodeType, Node.TEXT_NODE);
+ assert_equals(div.firstChild.data, "y");
+}, "setHTML() removes noscript with its raw text content by default");
+</script>
+</body>
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-replace-with-children.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-replace-with-children.html
new file mode 100644
index 00000000000..72369adf6d1
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-replace-with-children.html
@@ -0,0 +1,103 @@
+<!DOCTYPE html>
+<html>
+<head>
+<title>setHTML()/setHTMLUnsafe() with replaceWithChildrenElements: insertion location of hoisted children</title>
+<link rel="help" href="https://wicg.github.io/sanitizer-api/#sanitize">
+<link rel="help" href="https://html.spec.whatwg.org/#dom-element-sethtmlunsafe">
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+</head>
+<body>
+<div id="container"></div>
+<script>
+// When an element is replaced with its children while parsing, the nodes
+// parsed under it must behave as if they were parsed directly into the
+// element's parent: same node document, same custom element registry, and
+// no declarative shadow root is attached on behalf of the removed element.
+
+for (const method of ["setHTML", "setHTMLUnsafe"]) {
+ test(t => {
+ const container = document.getElementById("container");
+ t.add_cleanup(() => container.replaceChildren());
+ const target = document.createElement("div");
+ container.append(target);
+
+ target[method]('<div><span id="child">text</span></div>',
+ { sanitizer: { replaceWithChildrenElements: ["div"] } });
+
+ const span = target.querySelector("#child");
+ assert_not_equals(span, null);
+ assert_equals(span.ownerDocument, document);
+ assert_equals(target.innerHTML, '<span id="child">text</span>');
+ }, `${method}: children of a replaced element get the target's node document`);
+
+ test(t => {
+ const container = document.getElementById("container");
+ t.add_cleanup(() => container.replaceChildren());
+ const target = document.createElement("div");
+ container.append(target);
+
+ target[method](
+ '<div><span id="child">text</span><template shadowrootmode="open"><p>dsd</p></template></div>',
+ { sanitizer: { replaceWithChildrenElements: ["div"] } });
+
+ assert_not_equals(target.querySelector("#child"), null);
+ assert_equals(target.shadowRoot, null,
+ "a declarative shadow root inside a replaced element must not attach to the target");
+ assert_equals(container.shadowRoot, null);
+ if (method === "setHTMLUnsafe") {
+ const tpl = target.querySelector("template");
+ assert_not_equals(tpl, null,
+ "the template inside a replaced element stays a plain <template>");
+ assert_equals(tpl.content.querySelector("p").textContent, "dsd");
+ }
+ }, `${method}: a declarative shadow root inside a replaced element is not attached`);
+}
+
+const ceLog = [];
+customElements.define("replaced-child-ce", class extends HTMLElement {
+ constructor() { super(); ceLog.push("constructed"); }
+ connectedCallback() { ceLog.push(`connected:${this.parentNode.localName}`); }
+});
+
+test(t => {
+ const container = document.getElementById("container");
+ t.add_cleanup(() => container.replaceChildren());
+ const target = document.createElement("div");
+ container.append(target);
+ ceLog.length = 0;
+
+ target.setHTMLUnsafe("<div><replaced-child-ce></replaced-child-ce></div>", {
+ sanitizer: {
+ elements: ["replaced-child-ce"],
+ replaceWithChildrenElements: ["div"],
+ },
+ });
+
+ assert_array_equals(ceLog, ["constructed", "connected:div"]);
+ assert_equals(target.firstChild.localName, "replaced-child-ce");
+ assert_equals(target.firstChild.parentNode, target);
+}, "setHTMLUnsafe: a custom element inside a replaced element is constructed and connected to the target");
+
+test(t => {
+ const container = document.getElementById("container");
+ t.add_cleanup(() => container.replaceChildren());
+ const target = document.createElement("div");
+ container.append(target);
+ ceLog.length = 0;
+
+ target.setHTMLUnsafe(
+ "<table><div><replaced-child-ce></replaced-child-ce></div><td>cell</td></table>", {
+ sanitizer: {
+ elements: ["replaced-child-ce", "table", "tbody", "tr", "td"],
+ replaceWithChildrenElements: ["div"],
+ },
+ });
+
+ assert_array_equals(ceLog, ["constructed", "connected:div"]);
+ assert_equals(target.innerHTML,
+ "<replaced-child-ce></replaced-child-ce><table><tbody><tr><td>cell</td></tr></tbody></table>");
+}, "setHTMLUnsafe: a custom element inside a foster-parented replaced element is connected before the table");
+</script>
+</body>
+</html>
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-safety.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-safety.html
new file mode 100644
index 00000000000..d4712872463
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-safety.html
@@ -0,0 +1,48 @@
+<!DOCTYPE html>
+<head>
+<title>Testcases from the previous Sanitizer API</title>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="support/html5lib-testcase-support.js"></script>
+<script>
+promise_test(async _ => {
+ const safety = await fetch("sethtml-safety.sub.dat").
+ then(response => response.text()).
+ then(parse_html5lib_testcases);
+ const unsafety = await fetch("sethtml-unsafety.sub.dat").
+ then(response => response.text()).
+ then(parse_html5lib_testcases);
+
+ // Ensure that the "safe" and "unsafe" testcase inputs are the same and that
+ // they only differ only in the expected outcome.
+ assert_equals(safety.length, unsafety.length);
+ for (let i = 0; i < safety.length; i++) {
+ assert_equals(safety[i].data, unsafety[i].data);
+ assert_equals(safety[i].config, unsafety[i].config);
+ assert_equals(safety[i]["document-fragment"], unsafety[i]["document-fragment"]);
+ }
+
+ // The main tests here are non-async. Let's run them here, to make sure the
+ // two fetches have completed.
+ test_each("setHTML", safety);
+ test_each("setHTMLUnsafe", unsafety);
+}, "wrapper");
+
+function test_each(method, testcases) {
+ testcases.forEach((testcase, index) => {
+ test(_ => {
+ const context = document.createElement(testcase["document-fragment"] ?? "div");
+ let config = undefined;
+ try {
+ config = JSON.parse(testcase.config);
+ } catch { }
+
+ context[method].call(context, testcase.data, { sanitizer: config });
+ assert_testcase(context, testcase);
+ }, `Testcase #${index}, ${method}("${testcase.data}").`);
+ });
+}
+</script>
+</head>
+<body>
+</body>
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-safety.sub.dat b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-safety.sub.dat
new file mode 100644
index 00000000000..21b53bf9067
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-safety.sub.dat
@@ -0,0 +1,110 @@
+#data
+test
+#document-fragment
+script
+#document
+
+#data
+<p>Hello</p>
+#document-fragment
+script
+#document
+
+#data
+<div>Hello<script>World</script>xxx
+#document
+| <div>
+| "Helloxxx"
+
+#data
+<div>Hello<script>World</script>xxx
+#config
+{ "elements": ["div", "script"] }
+#document
+| <div>
+| "Helloxxx"
+
+#data
+<svg>Hello<script>World</script>xxx
+#document
+| <svg svg>
+| "Helloxxx"
+
+#data
+<a href="https://wpt.live/" onclick="2+2" one="two">
+#document
+| <a>
+| href="https://wpt.live/"
+
+#data
+<a href="https://wpt.live/" onclick="2+2" one="two">
+#config
+{ "elements": ["a"], "attributes": ["href", "onclick", "one"]}
+#document
+| <a>
+| href="https://wpt.live/"
+| one="two"
+
+#data
+<img src="https://wpt.live/test-image" onclick="2+2" one="two">
+#config
+{ "elements": ["img"], "attributes": ["src", "onclick", "one"]}
+#document
+| <img>
+| one="two"
+| src="https://wpt.live/test-image"
+
+#data
+<p data-x="1" data-y="2" data-z="3">
+#document
+| <p>
+
+#data
+<div><base href="https://example.org/"></base></div>
+#config
+{ }
+#document
+| <div>
+
+#data
+<div><embed src="https://example.org/"></embed></div>
+#config
+{ }
+#document
+| <div>
+
+#data
+<div><iframe src="https://example.org/"></iframe></div>
+#config
+{ }
+#document
+| <div>
+
+#data
+<div><object data="https://example.org/"></object></div>
+#config
+{ }
+#document
+| <div>
+
+#data
+<div><script src="https://example.org/"></script></div>
+#config
+{ }
+#document
+| <div>
+
+#data
+<svg><script src="https://example.org/"></script></svg>
+#config
+{ }
+#document
+| <svg svg>
+
+#data
+<svg><use href="https://example.org/"></use></svg>
+#config
+{ }
+#document
+| <svg svg>
+
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-scoped-custom-element-registry.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-scoped-custom-element-registry.html
new file mode 100644
index 00000000000..351f1e860de
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-scoped-custom-element-registry.html
@@ -0,0 +1,120 @@
+<!DOCTYPE html>
+<meta charset="utf-8">
+<title>setHTML() and setHTMLUnsafe() use the target's scoped custom element registry</title>
+<link rel="help" href="https://html.spec.whatwg.org/#dom-element-sethtml">
+<link rel="help" href="https://html.spec.whatwg.org/#dom-element-sethtmlunsafe">
+<link rel="help" href="https://html.spec.whatwg.org/#look-up-a-custom-element-registry">
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<body>
+<div id="container"></div>
+<script>
+ // Elements created by the fragment parser look up the custom element
+ // registry of their intended parent, so custom elements in markup set via
+ // setHTML()/setHTMLUnsafe() on an element (or shadow root) with a scoped
+ // registry are constructed with that registry, like innerHTML.
+
+ for (const method of ["setHTML", "setHTMLUnsafe"]) {
+ const safe = method === "setHTML";
+
+ test((t) => {
+ const container = document.getElementById("container");
+ t.add_cleanup(() => container.replaceChildren());
+ const scoped = new CustomElementRegistry();
+ const log = [];
+ scoped.define("scoped-element", class extends HTMLElement {
+ constructor() { super(); log.push("constructed"); }
+ connectedCallback() { log.push("connected"); }
+ });
+ const target = document.createElement("div", { customElementRegistry: scoped });
+ container.append(target);
+
+ target[method]("<scoped-element></scoped-element>",
+ safe ? { sanitizer: { elements: ["scoped-element"] } } : undefined);
+ assert_array_equals(log, ["constructed", "connected"]);
+ assert_equals(target.firstChild.customElementRegistry, scoped);
+ }, `${method} uses the target's scoped custom element registry`);
+
+ if (!safe) {
+ test((t) => {
+ const container = document.getElementById("container");
+ t.add_cleanup(() => container.replaceChildren());
+ const scoped = new CustomElementRegistry();
+ const log = [];
+ scoped.define("scoped-element", class extends HTMLElement {
+ constructor() { super(); log.push("constructed"); }
+ connectedCallback() { log.push("connected"); }
+ });
+ const target = document.createElement("div", { customElementRegistry: scoped });
+ container.append(target);
+
+ target.setHTMLUnsafe("<scoped-element></scoped-element>",
+ { sanitizer: { elements: ["scoped-element"] } });
+ assert_array_equals(log, ["constructed", "connected"]);
+ assert_equals(target.firstChild.customElementRegistry, scoped);
+ }, `setHTMLUnsafe with a sanitizer uses the target's scoped custom element registry`);
+ }
+
+ test((t) => {
+ const container = document.getElementById("container");
+ t.add_cleanup(() => container.replaceChildren());
+ const scoped = new CustomElementRegistry();
+ const log = [];
+ scoped.define("scoped-replaced-child", class extends HTMLElement {
+ constructor() { super(); log.push("constructed"); }
+ connectedCallback() { log.push("connected"); }
+ });
+ const target = document.createElement("div", { customElementRegistry: scoped });
+ container.append(target);
+
+ target[method]("<div><scoped-replaced-child></scoped-replaced-child></div>", {
+ sanitizer: {
+ elements: ["scoped-replaced-child"],
+ replaceWithChildrenElements: ["div"],
+ },
+ });
+ assert_equals(target.firstChild.localName, "scoped-replaced-child");
+ assert_array_equals(log, ["constructed", "connected"]);
+ }, `${method} with replaceWithChildrenElements preserves the scoped custom element registry for children`);
+
+ test((t) => {
+ const container = document.getElementById("container");
+ t.add_cleanup(() => container.replaceChildren());
+ const hostRegistry = new CustomElementRegistry();
+ const shadowRegistry = new CustomElementRegistry();
+ const log = [];
+ hostRegistry.define("scoped-target-ce", class extends HTMLElement {
+ constructor() { super(); log.push("host-registry"); }
+ });
+ shadowRegistry.define("scoped-target-ce", class extends HTMLElement {
+ constructor() { super(); log.push("shadow-registry"); }
+ });
+ const host = document.createElement("div", { customElementRegistry: hostRegistry });
+ container.append(host);
+ const shadow = host.attachShadow({ mode: "open", customElementRegistry: shadowRegistry });
+
+ shadow[method]("<scoped-target-ce></scoped-target-ce>",
+ safe ? { sanitizer: { elements: ["scoped-target-ce"] } } : undefined);
+ assert_array_equals(log, ["shadow-registry"]);
+ }, `${method} on a shadow root uses the shadow root's registry, not the host's`);
+
+ test((t) => {
+ const container = document.getElementById("container");
+ t.add_cleanup(() => container.replaceChildren());
+ const scoped = new CustomElementRegistry();
+ const log = [];
+ scoped.define("scoped-nested", class extends HTMLElement {
+ constructor() { super(); log.push("constructed"); }
+ });
+ const target = document.createElement("div", { customElementRegistry: scoped });
+ container.append(target);
+
+ target[method]("<section><p><scoped-nested></scoped-nested></p></section>",
+ safe ? { sanitizer: { elements: ["section", "p", "scoped-nested"] } } : undefined);
+ assert_array_equals(log, ["constructed"]);
+ assert_equals(target.querySelector("p").customElementRegistry, scoped,
+ "descendants inherit the target's registry");
+ }, `${method} constructs nested custom elements with the scoped registry`);
+ }
+</script>
+</body>
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-tree-construction.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-tree-construction.html
new file mode 100644
index 00000000000..3f6ab49f7f4
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-tree-construction.html
@@ -0,0 +1,71 @@
+<!DOCTYPE html>
+<head>
+<title>Testcases from the previous Sanitizer API</title>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="support/html5lib-testcase-support.js"></script>
+<script>
+
+// Testcases from the old(er) support/testcases.sub.js file, ported over to
+// the HTML5Lib testcase format.
+promise_test(_ => {
+ return html5lib_testcases_from_response(fetch("sethtml-tree-construction.sub.dat")).
+ then(testcases => {
+ testcases.forEach((testcase, index) => {
+ test(_ => {
+ const div = document.createElement(testcase["document-fragment"] ?? "div");
+ let config = undefined;
+ try {
+ config = JSON.parse(testcase.config);
+ } catch { }
+ try {
+ div.setHTML(testcase.data, { sanitizer: config });
+ } catch (error) {
+ assert_equals(
+ error.name, testcase.error,
+ `Expect exception ${testcase.error}, but got ${error}.`);
+ assert_equals(div.firstChild, null);
+ return; // Early return in order to not trigger the subsequent
+ // assertions.
+ }
+ assert_false(
+ !!testcase.error,
+ `Expect exception ${testcase.error}, but nothing was thrown.`);
+ assert_testcase(div, testcase);
+ }, `Testcase #${index}, "${testcase.data}", config: "${testcase.config}".`);
+ });
+ });
+}, "wrapper");
+
+// support/testcases.sub.js contained a few testcases with non-strings as
+// input. The html5lib format doesn't support that, so we'll just add them here:
+test(_ => {
+ const div = document.createElement("div");
+ div.setHTML({});
+ assert_equals(div.outerHTML, "<div>[object Object]</div>");
+}, "Non-string input: empty object.");
+test(_ => {
+ const div = document.createElement("div");
+ div.setHTML(1);
+ assert_equals(div.outerHTML, "<div>1</div>");
+}, "Non-string input: number.");
+test(_ => {
+ const div = document.createElement("div");
+ div.setHTML(000);
+ assert_equals(div.outerHTML, "<div>0</div>");
+}, "Non-string input: octal number.");
+test(_ => {
+ const div = document.createElement("div");
+ div.setHTML(1 + 2);
+ assert_equals(div.outerHTML, "<div>3</div>");
+}, "Non-string input: expression.");
+test(_ => {
+ const div = document.createElement("div");
+ div.setHTML(undefined);
+ assert_equals(div.outerHTML, "<div>undefined</div>");
+}, "Non-string input: undefined.");
+
+</script>
+</head>
+<body>
+</body>
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-tree-construction.sub.dat b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-tree-construction.sub.dat
new file mode 100644
index 00000000000..2f668d99fd7
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-tree-construction.sub.dat
@@ -0,0 +1,1049 @@
+#data
+test
+#document
+| "test"
+
+#data
+<b>bla</b>
+#document
+| <b>
+| "bla"
+
+#data
+<a<embla
+#errors
+Parse error
+#document
+
+#data
+<html><head></head><body>test</body></html>
+#document
+| "test"
+
+#data
+<div>test
+#document
+| <div>
+| "test"
+
+#data
+<script>alert('i am a test')</script>
+#document
+
+#data
+hello<script>alert('i am a test')</script>
+#document
+| "hello"
+
+#data
+<div><b>hello<script>alert('i am a test')</script>
+#document
+| <div>
+| <b>
+| "hello"
+
+#data
+<p onclick='a= 123'>Click.</p>
+#document
+| <p>
+| "Click."
+
+#data
+<plaintext><p>text</p>
+#config
+{}
+#document
+| <plaintext>
+| "<p>text</p>"
+
+#data
+<xmp>TEXT</xmp>
+#config
+{}
+#document
+| <xmp>
+| "TEXT"
+
+#data
+test
+#config
+{ "test": 123 }
+#document
+| "test"
+
+#data
+test
+#config
+{ "removeElements": [] }
+#document
+| "test"
+
+#data
+<div>test</div><p>bla
+#config
+{ "removeElements": ["div"] }
+#document
+| <p>
+| "bla"
+
+#data
+<custom-element>test1</custom-element>bla
+#document
+| "bla"
+
+#data
+<custom-element>test3</custom-element>bla
+#config
+{ "elements": ["custom-element"] }
+#document
+| <custom-element>
+| "test3"
+| "bla"
+
+#data
+<custom-element>test5</custom-element>bla
+#config
+{ "removeElements": ["custom-element"] }
+#document
+| "bla"
+
+#data
+<script>alert('i am a test')</script>
+#config
+{ "removeElements": ["script"] }
+#document
+
+#data
+<div>balabala<i>test</i></div><test-element>t</test-element>
+#config
+{ "removeElements": ["test-element", "i"] }
+#document
+| <div>
+| "balabala"
+
+#data
+<div>balabala<i>i</i><p>t</p></div>
+#config
+{ "removeElements": ["dl", "p"] }
+#document
+| <div>
+| "balabala"
+| <i>
+| "i"
+
+#data
+<div>test<div>p</div>tt<p>div</p></div>
+#config
+{ "elements": ["p"], "replaceWithChildrenElements": ["div"] }
+#document
+| "testptt"
+| <p>
+| "div"
+
+#data
+<div>test</div><p>bla
+#config
+{ "removeElements": ["div"], "elements": ["div"] }
+#error
+TypeError
+
+#data
+<p id='test'>Click.</p>
+#config
+{ "removeAttributes": [] }
+#document
+| <p>
+| id="test"
+| "Click."
+
+#data
+<p id='test'>Click.</p>
+#config
+{ "removeAttributes": ["id"] }
+#document
+| <p>
+| "Click."
+
+#data
+<p id='test'>Click.</p>
+#config
+{ "elements": ["p"], "removeAttributes": ["id"] }
+#document
+| <p>
+| "Click."
+
+#data
+<p id='p' data-attribute-with-dashes='123'>Click.</p><script>document.getElementById('p').dataset.attributeWithDashes=123;</script>
+#config
+{ "elements": ["p"], "removeAttributes": ["data-attribute-with-dashes"] }
+#document
+| <p>
+| id="p"
+| "Click."
+
+#data
+<p id='p' title='p'>P</p><div id='div' title='div'>DIV</div>
+#config
+{ "elements": [
+ { "name": "p", "attributes": ["title"] },
+ { "name": "div", "attributes": ["id"] }
+]}
+#document
+| <p>
+| title="p"
+| "P"
+| <div>
+| id="div"
+| "DIV"
+
+#data
+<p id='p' title='p'>P</p><div id='div' title='div'>DIV</div>
+#config
+{ "elements":
+ [
+ { "name": "p", "removeAttributes": ["title"] },
+ { "name": "div", "removeAttributes": ["id"] }
+ ]
+}
+#document
+| <p>
+| id="p"
+| "P"
+| <div>
+| title="div"
+| "DIV"
+
+#data
+<div id='div' title='div'>DIV</div>
+#config
+{ "elements": [{ "name": "div", "attributes": ["id"], "removeAttributes": ["id"] }]}
+#error
+TypeError
+
+#data
+<div id='div' title='div'>DIV</div>
+#config
+{ "elements": [{ "name": "div", "attributes": ["id", "title"] }],
+ "attributes": []}
+#document
+| <div>
+| id="div"
+| title="div"
+| "DIV"
+
+#data
+<div id='div' title='div'>DIV</div>
+#config
+{
+ "elements": [{ "name": "div", "attributes": [] }],
+ "removeAttributes": ["id", "title"]
+}
+#document
+| <div>
+| "DIV"
+
+#data
+<div id='div' title='div'>DIV</div>
+#config
+{
+ "elements": [{ "name": "div", "removeAttributes": ["id", "title"] }],
+ "attributes": ["id", "title"]
+}
+#document
+| <div>
+| "DIV"
+
+#data
+<p id='test' onclick='a= 123'>Click.</p>
+#config
+{ "attributes": ["id"] }
+#document
+| <p>
+| id="test"
+| "Click."
+
+#data
+<p style='color: black'>Click.</p>
+#config
+{ "removeAttributes": ["style"], "attributes": ["style"] }
+#error
+TypeError
+
+#data
+<template><script>test</script><div>hello</div></template>
+#config
+{ "elements": ["template", "div"] }
+#document
+| <template>
+| content
+| <div>
+| "hello"
+
+#data
+<a href='javascript:evil.com'>Click.</a>
+#document
+| <a>
+| "Click."
+
+#data
+<a href=' javascript:evil.com'>Click.</a>
+#document
+| <a>
+| "Click."
+
+#data
+<a href='http:evil.com'>Click.</a>
+#document
+| <a>
+| href="http:evil.com"
+| "Click."
+
+#data
+<area href='javascript:evil.com'>
+#config
+{}
+#document
+| <area>
+
+#data
+<area href=' javascript:evil.com'>
+#config
+{}
+#document
+| <area>
+
+#data
+<area href='http:evil.com'>
+#config
+{}
+#document
+| <area>
+| href="http:evil.com"
+
+#data
+<form action='javascript:evil.com'>Click.</form>
+#config
+{}
+#document
+| <form>
+| "Click."
+
+#data
+<form action=' javascript:evil.com'>Click.</form>
+#config
+{}
+#document
+| <form>
+| "Click."
+
+#data
+<form action='http:evil.com'>Click.</form>
+#config
+{}
+#document
+| <form>
+| action="http:evil.com"
+| "Click."
+
+#data
+<input formaction='javascript:evil.com'>
+#config
+{}
+#document
+| <input>
+
+#data
+<input formaction=' javascript:evil.com'>
+#config
+{}
+#document
+| <input>
+
+#data
+<input formaction='http:evil.com'>
+#config
+{}
+#document
+| <input>
+| formaction="http:evil.com"
+
+#data
+<button formaction='javascript:evil.com'>Click.</button>
+#config
+{}
+#document
+| <button>
+| "Click."
+
+#data
+<button formaction=' javascript:evil.com'>Click.</button>
+#config
+{}
+#document
+| <button>
+| "Click."
+
+#data
+<button formaction='http:evil.com'>Click.</button>
+#config
+{}
+#document
+| <button>
+| formaction="http:evil.com"
+| "Click."
+
+#data
+<p>Some text</p></body><!-- 1 --></html><!-- 2 --><p>Some more text</p>
+#document
+| <p>
+| "Some text"
+| <p>
+| "Some more text"
+
+#data
+<p>Some text</p><!-- 1 --><!-- 2 --><p>Some more text</p>
+#document
+| <p>
+| "Some text"
+| <p>
+| "Some more text"
+
+#data
+<p>Some text</p><!-- 1 --><!-- 2 --><p>Some more text</p>
+#config
+{ "comments": true }
+#document
+| <p>
+| "Some text"
+| <!-- 1 -->
+| <!-- 2 -->
+| <p>
+| "Some more text"
+
+#data
+<p>Some text</p><!-- 1 --><!-- 2 --><p>Some more text</p>
+#config
+{ "comments": false }
+#document
+| <p>
+| "Some text"
+| <p>
+| "Some more text"
+
+#data
+<p>comment<!-- hello -->in<!-- </p> -->text</p>
+#document
+| <p>
+| "commentintext"
+
+#data
+<p>comment<!-- hello -->in<!-- </p> -->text</p>
+#config
+{ "comments": true }
+#document
+| <p>
+| "comment"
+| <!-- hello -->
+| "in"
+| <!-- </p> -->
+| "text"
+
+#data
+<p>comment<!-- hello -->in<!-- </p> -->text</p>
+#config
+{ "comments": false }
+#document
+| <p>
+| "commentintext"
+
+#data
+<svg></svg>
+#config
+{ "elements": ["svg"] }
+#document
+
+#data
+<div><svg></svg></div>
+#config
+{ "elements": ["div", "svg"] }
+#document
+| <div>
+
+#data
+<div>balabala<dl>test</dl></div>
+#config
+{ "removeElements": ["I", "DL"] }
+#document
+| <div>
+| "balabala"
+| <dl>
+| "test"
+
+#data
+<div>balabala<dl>test</dl></div>
+#config
+{ "removeElements": ["i", "dl"] }
+#document
+| <div>
+| "balabala"
+
+#data
+<DIV>balabala<DL>test</DL></DIV>
+#config
+{ "removeElements": ["i", "dl"] }
+#document
+| <div>
+| "balabala"
+
+#data
+<p id="test">Click.</p>
+#config
+{ "removeAttributes": ["ID"] }
+#document
+| <p>
+| id="test"
+| "Click."
+
+#data
+<p ID="test">Click.</p>
+#config
+{ "removeAttributes": ["ID"] }
+#document
+| <p>
+| id="test"
+| "Click."
+
+#data
+<p ID="test">Click.</p>
+#config
+{ "removeAttributes": ["id"] }
+#document
+| <p>
+| "Click."
+
+#data
+<div>balabala<i>test</i></div><test>t</test><custom-element>custom-element</custom-element>
+#config
+{ "removeElements": [123, "test", "i", "custom-element"] }
+#document
+| <div>
+| "balabala"
+
+#data
+<div>balabala<i>test</i></div><test>t</test><custom-element>custom-element</custom-element>
+#config
+{ "replaceWithChildrenElements": [123, "test", "i", "custom-element"],
+ "elements": ["div"]}
+#document
+| <div>
+| "balabalatest"
+| "tcustom-element"
+
+#data
+<div>test<div>p</div>tt<p>div</p></div><test>test</test>
+#config
+{ "elements": ["p", "test"], "replaceWithChildrenElements": ["div"] }
+#document
+| "testptt"
+| <p>
+| "div"
+| <test>
+| "test"
+
+#data
+test<div>p</div>tt<p>div</p><test>test</test>
+#config
+{ "elements": ["p", "test"], "replaceWithChildrenElements": ["div"] }
+#document
+| "testptt"
+| <p>
+| "div"
+| <test>
+| "test"
+
+#data
+<div hello='1' world='2'><b hello='3' world='4'>
+#config
+{ "elements": ["div", "b"], "attributes": ["hello", "world"] }
+#document
+| <div>
+| hello="1"
+| world="2"
+| <b>
+| hello="3"
+| world="4"
+
+#data
+<div hello='1' world='2'><b hello='3' world='4'>
+#config
+{ "elements": ["div", "b"], "removeAttributes": ["hello", "world"] }
+#document
+| <div>
+| <b>
+
+#data
+<table><div><td>
+#config
+{ "replaceWithChildrenElements": ["table"] }
+#document
+| <div>
+| <tbody>
+| <tr>
+| <td>
+
+#data
+<template><div>Hello</div></template>
+#config
+{}
+#document
+| <template>
+| content
+| <div>
+| "Hello"
+
+#data
+<template><div>Hello</div></template>
+#config
+{ "elements": ["div"]}
+#document
+
+#data
+<template><div>Hello</div></template>
+#config
+{ "elements": ["template"]}
+#document
+| <template>
+| content
+
+#data
+<template><div>Hello</div></template>
+#config
+{ "elements": ["div", "template"]}
+#document
+| <template>
+| content
+| <div>
+| "Hello"
+
+#data
+<template><div>Hello</div></template>
+#config
+{ "elements": ["template"], "replaceWithChildrenElements": ["div"]}
+#document
+| <template>
+| content
+| "Hello"
+
+#data
+<a href="about:blank" rel="opener">Click.</a>
+#document
+| <a>
+| href="about:blank"
+| "Click."
+
+#data
+<div><b><em><foo><foob><fooc><aside></b></em></div>
+#config
+{ "removeElements": ["em"] }
+#document
+| <div>
+| <b>
+| <aside>
+| <b>
+
+#data
+<template><b>Hello</b></template>
+#config
+{ "replaceWithChildrenElements": ["template"] }
+#document
+
+#data
+<div><template><b>Hello</b></template>after</div>
+#config
+{ "replaceWithChildrenElements": ["template"] }
+#document
+| <div>
+| "after"
+
+#data
+<b>before</b><template><span>A</span><template><i>nested</i></template></template><b>after</b>
+#config
+{ "replaceWithChildrenElements": ["template"] }
+#document
+| <b>
+| "before"
+| <b>
+| "after"
+
+#data
+<table><template><span>A</span></template><td>cell</td></table>
+#config
+{ "replaceWithChildrenElements": ["template"] }
+#document
+| <table>
+| <tbody>
+| <tr>
+| <td>
+| "cell"
+
+#data
+<div><div><b>Hello</b></div>after</div>
+#config
+{ "replaceWithChildrenElements": ["div"] }
+#document
+| <b>
+| "Hello"
+| "after"
+
+#data
+<div><table><tr>foster<td>cell</td></tr></table></div>
+#config
+{ "replaceWithChildrenElements": ["div"] }
+#document
+| "foster"
+| <table>
+| <tbody>
+| <tr>
+| <td>
+| "cell"
+
+#data
+<table><div><span>Content</span></div><td>cell</td></table>
+#config
+{ "replaceWithChildrenElements": ["div"] }
+#document
+| <span>
+| "Content"
+| <table>
+| <tbody>
+| <tr>
+| <td>
+| "cell"
+
+#data
+<table><tr><div><span>Content</span></div><td>cell</td></tr></table>
+#config
+{ "replaceWithChildrenElements": ["div"] }
+#document
+| <span>
+| "Content"
+| <table>
+| <tbody>
+| <tr>
+| <td>
+| "cell"
+
+#data
+<table>x<tr><td>y
+#config
+{ "replaceWithChildrenElements": ["table"] }
+#document
+| "x"
+| <tbody>
+| <tr>
+| <td>
+| "y"
+
+#data
+<table><tr><td>y</td></tr>x</table>
+#config
+{ "replaceWithChildrenElements": ["table"] }
+#document
+| <tbody>
+| <tr>
+| <td>
+| "y"
+| "x"
+
+#data
+<table><tr><td>y</td></tr><div>x</div></table>
+#config
+{ "replaceWithChildrenElements": ["table"] }
+#document
+| <tbody>
+| <tr>
+| <td>
+| "y"
+| <div>
+| "x"
+
+#data
+a<table><tr><td>y</td></tr>b</table>c
+#config
+{ "replaceWithChildrenElements": ["table"] }
+#document
+| "a"
+| <tbody>
+| <tr>
+| <td>
+| "y"
+| "bc"
+
+#data
+<table><tbody><tr><td>y</td></tr>x</table>
+#config
+{ "replaceWithChildrenElements": ["table", "tbody"] }
+#document
+| <tr>
+| <td>
+| "y"
+| "x"
+
+#data
+<table><tr><div>x</div><td>y
+#config
+{ "replaceWithChildrenElements": ["div"] }
+#document
+| "x"
+| <table>
+| <tbody>
+| <tr>
+| <td>
+| "y"
+
+#data
+<table>a<b>y</b>c<tr><td>z
+#config
+{ "replaceWithChildrenElements": ["b"] }
+#document
+| "ayc"
+| <table>
+| <tbody>
+| <tr>
+| <td>
+| "z"
+
+#data
+<table><template>x</template><tr><td>y
+#config
+{ "replaceWithChildrenElements": ["template"] }
+#document
+| <table>
+| <tbody>
+| <tr>
+| <td>
+| "y"
+
+#data
+<template><table>x</table></template>
+#config
+{ "replaceWithChildrenElements": ["table"] }
+#document
+| <template>
+| content
+| "x"
+
+#data
+a<table>b<tr><td>c</table>d
+#config
+{ "removeElements": ["table"] }
+#document
+| "abd"
+
+#data
+<table><tr>x<td>y
+#config
+{ "removeElements": ["tr"] }
+#document
+| "x"
+| <table>
+| <tbody>
+
+#data
+<div><table>x
+#config
+{ "removeElements": ["div"] }
+#document
+
+#data
+<b><table>x
+#config
+{ "replaceWithChildrenElements": ["b"] }
+#document
+| "x"
+| <table>
+
+#data
+<b><table><div>x
+#config
+{ "replaceWithChildrenElements": ["b"], "removeElements": ["table"] }
+#document
+| <div>
+| "x"
+
+#data
+<table><div><input type="hidden"><td>x
+#config
+{ "replaceWithChildrenElements": ["div"] }
+#document
+| <input>
+| type="hidden"
+| <table>
+| <tbody>
+| <tr>
+| <td>
+| "x"
+
+#data
+<table><div><template>t</template><td>x
+#config
+{ "replaceWithChildrenElements": ["div"] }
+#document
+| <template>
+| content
+| "t"
+| <table>
+| <tbody>
+| <tr>
+| <td>
+| "x"
+
+#data
+<table><div><!-- c --><td>x
+#config
+{ "replaceWithChildrenElements": ["div"], "comments": true }
+#document
+| <!-- c -->
+| <table>
+| <tbody>
+| <tr>
+| <td>
+| "x"
+
+#data
+<table><tr><td>y
+#config
+{ "replaceWithChildrenElements": ["tr"] }
+#document
+| <table>
+| <tbody>
+| <td>
+| "y"
+
+#data
+<table><!-- x --><tr><td>y
+#config
+{ "replaceWithChildrenElements": ["table"], "comments": true }
+#document
+| <!-- x -->
+| <tbody>
+| <tr>
+| <td>
+| "y"
+
+#data
+<template><!-- x --></template>
+#config
+{ "comments": true }
+#document
+| <template>
+| content
+| <!-- x -->
+
+#data
+<td>a</td><div>b</div>
+#config
+{ "replaceWithChildrenElements": ["td"] }
+#document-fragment
+tr
+#document
+| "a"
+| <div>
+| "b"
+
+#data
+<select><option>a<option>b</select>
+#config
+{ "replaceWithChildrenElements": ["option"] }
+#document
+| <select>
+| "ab"
+
+#data
+<select><option>a</option></select>
+#config
+{ "replaceWithChildrenElements": ["select"] }
+#document
+| <option>
+| "a"
+
+#data
+<title>a&amp;b<b></title>c
+#config
+{ "replaceWithChildrenElements": ["title"] }
+#document
+| "a&b<b>c"
+
+#data
+<plaintext>x</plaintext>y
+#config
+{ "replaceWithChildrenElements": ["plaintext"] }
+#document
+| "x</plaintext>y"
+
+#data
+<xmp><b>x</xmp>y
+#config
+{ "removeElements": ["xmp"] }
+#document
+| "y"
+
+#data
+<image src="x">
+#config
+{ "removeElements": ["image"] }
+#document
+| <img>
+| src="x"
+
+#data
+<image src="x">
+#config
+{ "elements": ["img"] }
+#document
+| <img>
+| src="x"
+
+#data
+<table><tr><td>x
+#config
+{ "replaceWithChildrenElements": ["tbody"] }
+#document
+| <table>
+| <tr>
+| <td>
+| "x"
+
+#data
+<table><col></table>
+#config
+{ "replaceWithChildrenElements": ["colgroup"] }
+#document
+| <table>
+| <col>
+
+#data
+<p>a<div>b</div>c
+#config
+{ "removeElements": ["p"] }
+#document
+| <div>
+| "b"
+| "c"
+
+#data
+<svg><g><rect></g></svg>
+#config
+{ "replaceWithChildrenElements": [{ "name": "g", "namespace": "http://www.w3.org/2000/svg" }] }
+#document
+| <svg svg>
+| <svg rect>
+
+#data
+<svg><foreignObject><div>x</div></foreignObject></svg>
+#config
+{ "replaceWithChildrenElements": [{ "name": "foreignObject", "namespace": "http://www.w3.org/2000/svg" }] }
+#document
+| <svg svg>
+| <div>
+| "x"
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-unsafety.sub.dat b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-unsafety.sub.dat
new file mode 100644
index 00000000000..3d1977b19be
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-unsafety.sub.dat
@@ -0,0 +1,142 @@
+#data
+test
+#document-fragment
+script
+#document
+| "test"
+
+#data
+<p>Hello</p>
+#document-fragment
+script
+#document
+| "<p>Hello</p>"
+
+#data
+<div>Hello<script>World</script>xxx
+#document
+| <div>
+| "Hello"
+| <script>
+| "World"
+| "xxx"
+
+#data
+<div>Hello<script>World</script>xxx
+#config
+{ "elements": ["div", "script"] }
+#document
+| <div>
+| "Hello"
+| <script>
+| "World"
+| "xxx"
+
+#data
+<svg>Hello<script>World</script>xxx
+#document
+| <svg svg>
+| "Hello"
+| <svg script>
+| "World"
+| "xxx"
+
+#data
+<a href="https://wpt.live/" onclick="2+2" one="two">
+#document
+| <a>
+| href="https://wpt.live/"
+| one="two"
+| onclick="2+2"
+
+#data
+<a href="https://wpt.live/" onclick="2+2" one="two">
+#config
+{ "elements": ["a"], "attributes": ["href", "onclick", "one"]}
+#document
+| <a>
+| href="https://wpt.live/"
+| onclick="2+2"
+| one="two"
+
+#data
+<img src="https://wpt.live/test-image" onclick="2+2" one="two">
+#config
+{ "elements": ["img"], "attributes": ["src", "onclick", "one"]}
+#document
+| <img>
+| onclick="2+2"
+| one="two"
+| src="https://wpt.live/test-image"
+
+#data
+<p data-x="1" data-y="2" data-z="3">
+#document
+| <p>
+| data-x="1"
+| data-y="2"
+| data-z="3"
+
+#data
+<div><base href="https://example.org/"></base></div>
+#config
+{ }
+#document
+| <div>
+| <base>
+| href="https://example.org/"
+
+#data
+<div><embed src="https://example.org/"></embed></div>
+#config
+{ }
+#document
+| <div>
+| <embed>
+| src="https://example.org/"
+
+#data
+<div><iframe src="https://example.org/"></iframe></div>
+#config
+{ }
+#document
+| <div>
+| <iframe>
+| src="https://example.org/"
+
+#data
+<div><object data="https://example.org/"></object></div>
+#config
+{ }
+#document
+| <div>
+| <object>
+| data="https://example.org/"
+
+#data
+<div><script src="https://example.org/"></script></div>
+#config
+{ }
+#document
+| <div>
+| <script>
+| src="https://example.org/"
+
+#data
+<svg><script src="https://example.org/"></script></svg>
+#config
+{ }
+#document
+| <svg svg>
+| <svg script>
+| src="https://example.org/"
+
+#data
+<svg><use href="https://example.org/"></use></svg>
+#config
+{ }
+#document
+| <svg svg>
+| <svg use>
+| href="https://example.org/"
+
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-with-custom-elements.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-with-custom-elements.html
new file mode 100644
index 00000000000..33b5cae19d3
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-with-custom-elements.html
@@ -0,0 +1,245 @@
+<!DOCTYPE html>
+<head>
+<title>Test custom element callbacks with Sanitizer</title>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+</head>
+<body>
+<div></div>
+<script>
+window.constructed = 0;
+window.connected = 0;
+function cleanup() {
+ window.constructed = 0;
+ window.connected = 0;
+}
+customElements.define("x-probe", class extends HTMLElement {
+ constructor() { super(); window.constructed++; }
+ connectedCallback() { window.connected++; }
+});
+
+// Test cases involving named custom elements.
+test(t => {
+ t.add_cleanup(cleanup);
+ document.body.firstElementChild.setHTML("<x-probe></x-probe>");
+ assert_equals(window.constructed, 0);
+ assert_equals(window.connected, 0);
+}, "Custom element that is removed during sanitization.");
+
+test(t => {
+ t.add_cleanup(cleanup);
+ document.body.firstElementChild.setHTML("<x-probe></x-probe>",
+ {sanitizer: {elements: ["x-probe"]}});
+ assert_equals(window.constructed, 1);
+ assert_equals(window.connected, 1);
+}, "Custom element that is allowed.");
+
+test(t => {
+ t.add_cleanup(cleanup);
+ const div = document.createElement("div");
+ div.setHTML("<x-probe></x-probe>", {sanitizer: {elements: ["x-probe"]}});
+ assert_equals(window.constructed, 1, "constructed before setHTML() returns");
+ assert_equals(window.connected, 0);
+ assert_equals(div.firstChild.constructor.name, "", "upgraded element is not HTMLElement");
+}, "Custom element that is allowed, on a disconnected element.");
+
+test(t => {
+ t.add_cleanup(cleanup);
+ const div = document.createElement("div");
+ div.setHTMLUnsafe("<x-probe></x-probe>");
+ assert_equals(window.constructed, 1, "constructed before setHTMLUnsafe() returns");
+ assert_equals(window.connected, 0);
+}, "Custom element on a disconnected element, setHTMLUnsafe().");
+
+for (const method of ["setHTML", "setHTMLUnsafe"]) {
+ test(t => {
+ t.add_cleanup(cleanup);
+ const div = document.createElement("div");
+ div[method]("<span><x-probe></x-probe></span>",
+ {sanitizer: {elements: ["x-probe"], replaceWithChildrenElements: ["span"]}});
+ assert_equals(div.firstChild.localName, "x-probe");
+ assert_equals(window.constructed, 1, `constructed before ${method}() returns`);
+ assert_equals(window.connected, 0);
+ }, `Custom element inside an element that is replaced with its children, on a disconnected element, ${method}().`);
+
+ test(t => {
+ t.add_cleanup(cleanup);
+ const target = document.body.firstElementChild;
+ target[method]("<span><b><x-probe></x-probe></b></span>",
+ {sanitizer: {elements: ["x-probe"], replaceWithChildrenElements: ["span", "b"]}});
+ assert_equals(target.firstChild.localName, "x-probe");
+ assert_equals(window.constructed, 1);
+ assert_equals(window.connected, 1);
+ }, `Custom element inside nested elements that are replaced with their children, ${method}().`);
+
+ test(t => {
+ const scopedLog = [];
+ const registry = new CustomElementRegistry();
+ class ScopedProbe extends HTMLElement {
+ constructor() { super(); scopedLog.push("scoped"); }
+ }
+ registry.define("x-probe", ScopedProbe);
+ t.add_cleanup(cleanup);
+ const host = document.createElement("div");
+ const shadow = host.attachShadow({mode: "open", customElementRegistry: registry});
+ shadow[method]("<span><x-probe></x-probe></span>",
+ {sanitizer: {elements: ["x-probe"], replaceWithChildrenElements: ["span"]}});
+ const probe = shadow.firstChild;
+ assert_equals(probe.localName, "x-probe");
+ assert_equals(probe.customElementRegistry, registry, "element uses the scoped registry");
+ assert_true(probe instanceof ScopedProbe, "upgraded with the scoped definition");
+ assert_array_equals(scopedLog, ["scoped"]);
+ assert_equals(window.constructed, 0, "global definition is not used");
+ }, `Custom element inside an element that is replaced with its children uses the target's scoped registry, ${method}().`);
+}
+
+test(t => {
+ t.add_cleanup(cleanup);
+ const div = document.createElement("div");
+ div.setHTMLUnsafe(
+ "<span><template shadowrootmode=open><x-probe></x-probe></template></span>",
+ {sanitizer: {removeElements: ["span"]}});
+ assert_equals(div.childNodes.length, 0);
+ assert_equals(window.constructed, 0);
+ assert_equals(window.connected, 0);
+}, "Custom element in a declarative shadow root on a removed host is not constructed.");
+
+test(t => {
+ t.add_cleanup(cleanup);
+ const div = document.createElement("div");
+ div.setHTMLUnsafe("<span><x-probe></x-probe></span>",
+ {sanitizer: {removeElements: ["span"]}});
+ assert_equals(div.childNodes.length, 0);
+ assert_equals(window.constructed, 0);
+}, "Custom element inside a removed element is not constructed.");
+
+const attrLog = [];
+customElements.define("x-attrs", class extends HTMLElement {
+ static observedAttributes = ["a", "b"];
+ constructor() { super(); attrLog.push("constructor"); }
+ attributeChangedCallback(name, oldValue, newValue) {
+ attrLog.push(`attributeChanged ${name} ${oldValue} ${newValue}`);
+ }
+ connectedCallback() { attrLog.push("connected"); }
+});
+
+test(t => {
+ attrLog.length = 0;
+ const target = document.body.firstElementChild;
+ target.setHTML('<x-attrs a="1" b="2"></x-attrs>',
+ {sanitizer: {elements: ["x-attrs"], attributes: ["a"]}});
+ assert_array_equals(attrLog,
+ ["constructor", "attributeChanged a null 1", "connected"]);
+ assert_equals(target.firstChild.getAttribute("a"), "1");
+ assert_false(target.firstChild.hasAttribute("b"));
+}, "attributeChangedCallback only fires for attributes the sanitizer keeps.");
+
+// Test cases involving `is=`.
+customElements.define("x-div", class extends HTMLDivElement {
+ constructor() { super(); window.constructed++; }
+ connectedCallback() { window.connected++; }
+}, { extends: "div" });
+
+test(t => {
+ t.add_cleanup(cleanup);
+ document.body.firstElementChild.setHTML("<div is='x-div'></div>");
+ assert_equals(window.constructed, 0);
+ assert_equals(window.connected, 0);
+}, "Custom element via is-attribute, where is attribute is not default-allowed.");
+
+test(t => {
+ t.add_cleanup(cleanup);
+ document.body.firstElementChild.setHTML("<div is='x-div'></div>",
+ {sanitizer: {elements:["div"], removeAttributes:["is"]}});
+ assert_equals(window.constructed, 0);
+ assert_equals(window.connected, 0);
+}, "Custom element via is-attribute, where is attribute is removed.");
+
+test(t => {
+ t.add_cleanup(cleanup);
+ document.body.firstElementChild.setHTML("<div is='x-div'></div>",
+ {sanitizer: {elements:["div", "x-div"], removeAttributes:["is"]}});
+ assert_equals(window.constructed, 0);
+ assert_equals(window.connected, 0);
+}, "Custom element via is-attribute, where is attribute is removed but the custom element would have been allowed.");
+
+test(t => {
+ t.add_cleanup(cleanup);
+ document.body.firstElementChild.setHTML("<x-probe is='x-div'></x-probe>",
+ {sanitizer: {elements:["div", "x-probe"], removeAttributes:["is"]}});
+ assert_equals(window.constructed, 1);
+ assert_equals(window.connected, 1);
+}, "Custom element with an is-attribute, where the is=-attribute is blocked.");
+
+test(t => {
+ t.add_cleanup(cleanup);
+ document.body.firstElementChild.setHTML("<div is='x-div'></div>",
+ {sanitizer: {elements:["p", "x-div"], attributes:["is", "data-attr"]}});
+ assert_equals(window.constructed, 0);
+ assert_equals(window.connected, 0);
+}, "Custom element via is-attribute, where is attribute is allowed, but the element is not.");
+
+test(t => {
+ t.add_cleanup(cleanup);
+ document.body.firstElementChild.setHTML("<div is='x-div'></div>",
+ {sanitizer: {removeElements:["div"], attributes:["is", "data-attr"]}});
+ assert_equals(window.constructed, 0);
+ assert_equals(window.connected, 0);
+}, "Custom element via is-attribute, where is attribute is allowed, but the element is removed.");
+
+test(t => {
+ t.add_cleanup(cleanup);
+ document.body.firstElementChild.setHTML("<div is='x-div'></div>",
+ {sanitizer: {replaceWithChildrenElements:["div"], attributes:["is", "data-attr"]}});
+ assert_equals(window.constructed, 0);
+ assert_equals(window.connected, 0);
+}, "Custom element via is-attribute, where is attribute is allowed, but the element is replaced.");
+
+test(t => {
+ t.add_cleanup(cleanup);
+ document.body.firstElementChild.setHTMLUnsafe("<div is='x-div'></div>",
+ {sanitizer: "default"});
+ assert_equals(window.constructed, 0);
+ assert_equals(window.connected, 0);
+}, "Custom element via is-attribute with unsafe, where is attribute is not default-allowed.");
+
+test(t => {
+ t.add_cleanup(cleanup);
+ document.body.firstElementChild.setHTML(
+ "<div is='x-div'></div>",
+ {sanitizer: {elements:["p", "div"], attributes:["is"]}});
+ assert_equals(window.constructed, 1);
+ assert_equals(window.connected, 1);
+}, "Sanity check, that is= processing still works when allowed.");
+
+// Test cases involving `is=` with <html> or <script>
+customElements.define("x-script", class extends HTMLScriptElement {
+ constructor() { super(); window.constructed++; }
+ connectedCallback() { window.connected++; }
+}, {extends: "script"});
+
+test(t => {
+ t.add_cleanup(cleanup);
+ document.body.firstElementChild.setHTMLUnsafe(
+ "<script is='x-script'>2+2</sc" + "ript>",
+ {sanitizer: {elements: ["script"],removeAttributes:["is"]}});
+ assert_equals(window.constructed, 0);
+ assert_equals(window.connected, 0);
+}, "Custom element via is-attribute on script element, where is attribute is not allowed.");
+
+customElements.define("x-html", class extends HTMLHtmlElement {
+ constructor() { super(); window.constructed++; }
+ connectedCallback() { window.connected++; }
+}, {extends: "html"});
+
+test(t => {
+ t.add_cleanup(cleanup);
+ document.body.firstElementChild.setHTMLUnsafe(
+ "<html is='x-html'></html>",
+ {sanitizer: {elements: ["html"],removeAttributes:["is"]}});
+ assert_equals(window.constructed, 0);
+ assert_equals(window.connected, 0);
+}, "Custom element via is-attribute on html element, where is attribute is not default-allowed.");
+
+</script>
+</body>
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-with-declarative-shadow-root.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-with-declarative-shadow-root.html
new file mode 100644
index 00000000000..fb234fb6e83
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-with-declarative-shadow-root.html
@@ -0,0 +1,122 @@
+<!doctype html>
+<head>
+ <title>Sanitize template with a declarative shadow root</title>
+ <script src="../resources/testharness.js"></script>
+ <script src="../resources/testharnessreport.js"></script>
+</head>
+<body>
+ <div></div>
+ <script>
+ test((t) => {
+ const element = document.createElement("div");
+ element.setHTML("<div><template shadowrootmode='open'></template></div>");
+ assert_equals(element.firstElementChild.shadowRoot, null);
+ assert_equals(element.firstElementChild.firstElementChild, null);
+ }, "template with shadowrootmode should be removed by safe default");
+
+ test((t) => {
+ const element = document.createElement("div");
+ element.setHTMLUnsafe(
+ "<div><template shadowrootmode='open'></template></div>",
+ );
+ assert_not_equals(element.firstElementChild.shadowRoot, null);
+ }, "template with shadowrootmode should not be removed in unsafe mode");
+
+ test((t) => {
+ const element = document.createElement("div");
+ element.setHTML(
+ "<div><template shadowrootmode='open'></template></div>",
+ { sanitizer: { removeElements: ["template"] } },
+ );
+ assert_equals(element.firstElementChild.shadowRoot, null);
+ assert_equals(element.firstElementChild.firstElementChild, null);
+ }, "template with shadowrootmode should not be processed when <template> is forbidden");
+
+ test((t) => {
+ const element = document.createElement("div");
+ element.setHTML(
+ "<div><template shadowrootmode='open'></template></div>",
+ { sanitizer: { removeAttributes: ["shadowrootmode"] } },
+ );
+ assert_equals(element.firstElementChild.shadowRoot, null);
+ assert_equals(
+ element.firstElementChild.firstElementChild.localName,
+ "template",
+ );
+ }, "template with shadowrootmode should be processed as a normal template when the shadowRootMode attribute is forbidden");
+
+ test((t) => {
+ const element = document.createElement("div");
+ element.setHTMLUnsafe(
+ "<div><template shadowrootmode='open'>s</template>x</div>",
+ { sanitizer: { replaceWithChildrenElements: ["template"] } },
+ );
+ assert_equals(element.firstElementChild.shadowRoot, null);
+ assert_equals(element.firstElementChild.firstElementChild, null);
+ assert_equals(element.firstElementChild.textContent, "x");
+ }, "template with shadowrootmode replaced with its children has no children in the tree");
+
+ test((t) => {
+ const element = document.createElement("div");
+ element.setHTMLUnsafe(
+ "<div><template shadowrootmode='open'>s</template>x</div>",
+ { sanitizer: { replaceWithChildrenElements: ["div"] } },
+ );
+ assert_equals(element.shadowRoot, null);
+ assert_equals(element.childNodes.length, 2);
+ const template = element.firstChild;
+ assert_equals(template.localName, "template");
+ assert_equals(template.shadowRootMode, "open");
+ assert_equals(template.content.textContent, "s");
+ assert_equals(element.lastChild.nodeType, Node.TEXT_NODE);
+ assert_equals(element.lastChild.data, "x");
+ }, "declarative shadow root on a host replaced with its children is not attached to the parent; the template is kept as a regular template");
+
+ test((t) => {
+ const element = document.createElement("div");
+ element.setHTMLUnsafe(
+ "<div><template shadowrootmode='open'>s</template>x</div>",
+ { sanitizer: { removeElements: ["div"] } },
+ );
+ assert_equals(element.shadowRoot, null);
+ assert_equals(element.childNodes.length, 0);
+ }, "declarative shadow root on a removed host is dropped with it");
+
+ test((t) => {
+ const element = document.createElement("div");
+ element.setHTMLUnsafe(
+ "<div><template shadowrootmode='open'><span>s</span></template>x</div>",
+ { sanitizer: { removeElements: ["template"] } },
+ );
+ const host = element.firstElementChild;
+ assert_equals(host.localName, "div");
+ assert_equals(host.shadowRoot, null);
+ assert_equals(host.childNodes.length, 1);
+ assert_equals(host.firstChild.data, "x");
+ }, "template with shadowrootmode in removeElements does not attach a shadow root (setHTMLUnsafe)");
+
+ for (const [attribute, value, property, expectedValue] of [
+ ["shadowrootdelegatesfocus", "", "delegatesFocus", false],
+ ["shadowrootserializable", "", "serializable", false],
+ ["shadowrootclonable", "", "clonable", false],
+ ["shadowrootreferencetarget", "something", "referenceTarget", null],
+ ["shadowrootcustomelementregistry", "", "customElementRegistry", customElements],
+ ["shadowrootadoptedstylesheets", "style.css", "adoptedStyleSheets", []],
+ ]) {
+ test((t) => {
+ const element = document.createElement("div");
+ element.setHTML(
+ `<div><template shadowrootmode='open' ${attribute}="${value}"></template></div>`,
+ { sanitizer: { removeAttributes: [attribute] } },
+ );
+ assert_not_equals(element.firstElementChild.shadowRoot, null, `shadowRoot should exist`);
+ if (Array.isArray(expectedValue)) {
+ assert_array_equals(element.firstElementChild.shadowRoot[property], expectedValue);
+ } else {
+ assert_equals(element.firstElementChild.shadowRoot[property], expectedValue);
+ }
+ }, `shadowRoot.${property} does not propagate to the shadow root when ${attribute} is removed by sanitizer`);
+ }
+
+</script>
+</body>
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-with-trustedhtml-createParserOptions.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-with-trustedhtml-createParserOptions.html
new file mode 100644
index 00000000000..81b83a62f52
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-with-trustedhtml-createParserOptions.html
@@ -0,0 +1,691 @@
+<!doctype html>
+<html>
+ <head>
+ <script src="../resources/testharness.js"></script>
+ <script src="../resources/testharnessreport.js"></script>
+ <script src="../trusted-types/support/helper.sub.js"></script>
+
+ <meta
+ http-equiv="Content-Security-Policy"
+ content="require-trusted-types-for 'script';"
+ />
+ </head>
+ <body>
+ <div id="container"></div>
+ <script>
+ const container = document.querySelector("#container");
+ let createParserOptions = (options, sink) => options;
+ let createHTML = (html) => html;
+
+ trustedTypes.createPolicy("default", {
+ createHTML: (html) => createHTML(html),
+ createParserOptions: (options, sink) => createParserOptions(options, sink),
+ });
+
+ const testPolicy = trustedTypes.createPolicy("test-policy", {
+ createHTML: (html) => html,
+ createParserOptions: (options) => options,
+ });
+
+ function createTarget(target_type, t) {
+ t.add_cleanup(() => {
+ createParserOptions = (options, sink) => options;
+ createHTML = (html) => html;
+ });
+
+ const target = document.createElement("div");
+ container.append(target);
+ t.add_cleanup(() => target.remove());
+ switch (target_type) {
+ case "Element":
+ return target;
+ case "ShadowRoot":
+ return target.attachShadow({ mode: "open" });
+ }
+ }
+
+ function run_method(node, method, html, options) {
+ switch (method) {
+ case "setHTMLUnsafe":
+ case "appendHTMLUnsafe":
+ case "prependHTMLUnsafe":
+ node[method](html, options);
+ break;
+ case "beforeHTMLUnsafe":
+ case "afterHTMLUnsafe":
+ case "replaceWithHTMLUnsafe": {
+ const inner = document.createElement("div");
+ node.replaceChildren(inner);
+ inner[method](html, options);
+ break;
+ }
+ case "innerHTML":
+ node.innerHTML = html;
+ break;
+ case "outerHTML": {
+ const inner = document.createElement("div");
+ node.replaceChildren(inner);
+ inner.outerHTML = html;
+ break;
+ }
+ case "afterbegin":
+ case "beforeend":
+ node.insertAdjacentHTML(method, html);
+ break;
+ case "beforebegin":
+ case "afterend": {
+ const inner = document.createElement("div");
+ node.replaceChildren(inner);
+ inner.insertAdjacentHTML(method, html);
+ break;
+ }
+ case "createContextualFragment": {
+ const range = document.createRange();
+ range.setStart(node, 0);
+ range.setEnd(node, 0);
+ const fragment = range.createContextualFragment(html);
+ node.replaceChildren(fragment);
+ break;
+ }
+ case "parseHTMLUnsafe":
+ return Document.parseHTMLUnsafe(html, options);
+ }
+ return node;
+ }
+
+ for (const target of ["ShadowRoot", "Element"]) {
+ for (const method of [
+ "setHTMLUnsafe",
+ "appendHTMLUnsafe",
+ "prependHTMLUnsafe",
+ "beforeHTMLUnsafe",
+ "afterHTMLUnsafe",
+ "replaceWithHTMLUnsafe",
+ "innerHTML",
+ "outerHTML",
+ "createContextualFragment",
+ "afterbegin",
+ "beforeend",
+ "beforebegin",
+ "afterend",
+ "parseHTMLUnsafe",
+ ]) {
+ if (
+ target === "ShadowRoot" &&
+ (method === "outerHTML" ||
+ method === "afterbegin" ||
+ method === "beforeend" ||
+ method === "beforebegin" ||
+ method === "afterend" ||
+ method === "beforeHTMLUnsafe" ||
+ method === "afterHTMLUnsafe" ||
+ method === "replaceWithHTMLUnsafe" ||
+ method === "createContextualFragment")
+ ) {
+ continue;
+ }
+ if (method === "parseHTMLUnsafe" && target === "ShadowRoot") {
+ continue;
+ }
+
+ test((t) => {
+ const node = createTarget(target, t);
+ createParserOptions = (options) => ({
+ ...options,
+ sanitizer: { removeElements: ["span"] },
+ });
+ const trustedHTML = testPolicy.createHTML(
+ "<div id='allowed'><span id='forbidden'></span></div>",
+ );
+ const root = run_method(node, method, trustedHTML);
+ assert_equals(
+ root.querySelector("#forbidden"),
+ null,
+ "Default policy sanitizer must be applied even when TrustedHTML is provided",
+ );
+ assert_not_equals(root.querySelector("#allowed"), null);
+ }, `${target}.${method}: sending TrustedHTML applies sanitizer in default policy createParserOptions`);
+
+ test((t) => {
+ const node = createTarget(target, t);
+ let createHTMLCalled = false;
+ createHTML = () => {
+ createHTMLCalled = true;
+ throw new Error("default createHTML should not be called");
+ };
+ createParserOptions = (options) => options;
+ const trustedHTML = testPolicy.createHTML(
+ "<div id='allowed'><span id='forbidden'></span></div>",
+ );
+ const root = run_method(node, method, trustedHTML);
+ assert_false(createHTMLCalled, "createHTML must not be called when TrustedHTML is passed");
+ assert_not_equals(root.querySelector("#forbidden"), null);
+ assert_not_equals(root.querySelector("#allowed"), null);
+ }, `${target}.${method}: sending TrustedHTML does not call default policy createHTML`);
+
+ test((t) => {
+ const node = createTarget(target, t);
+ createParserOptions = () => {
+ throw new Error("createParserOptions failed");
+ };
+ const trustedHTML = testPolicy.createHTML("<div id='allowed'></div>");
+ assert_throws_js(Error, () => {
+ run_method(node, method, trustedHTML);
+ });
+ assert_equals(node.querySelector("#allowed"), null);
+ }, `${target}.${method}: exception in default createParserOptions rethrows when TrustedHTML is passed`);
+
+ for (const value of [null, undefined]) {
+ test((t) => {
+ const node = createTarget(target, t);
+ createParserOptions = () => value;
+ const trustedHTML = testPolicy.createHTML("<div id='allowed'></div>");
+ assert_throws_js(TypeError, () => {
+ run_method(node, method, trustedHTML);
+ });
+ assert_equals(node.querySelector("#allowed"), null);
+ }, `${target}.${method}: default createParserOptions returning ${JSON.stringify(value)} throws TypeError when TrustedHTML is passed`);
+ }
+ }
+
+ for (const method of [
+ "setHTMLUnsafe",
+ "appendHTMLUnsafe",
+ "prependHTMLUnsafe",
+ "beforeHTMLUnsafe",
+ "afterHTMLUnsafe",
+ "replaceWithHTMLUnsafe",
+ ]) {
+ if (
+ target === "ShadowRoot" &&
+ ["beforeHTMLUnsafe", "afterHTMLUnsafe", "replaceWithHTMLUnsafe"].includes(method)
+ ) {
+ continue;
+ }
+
+ // Caller-provided options with TrustedHTML
+ test((t) => {
+ const node = createTarget(target, t);
+ createParserOptions = (options) => ({
+ ...options,
+ sanitizer: { removeElements: ["span"] },
+ });
+ const trustedHTML = testPolicy.createHTML(
+ "<div id='allowed'><span id='span'></span><b id='bold'></b></div>",
+ );
+ run_method(node, method, trustedHTML, {
+ sanitizer: { removeElements: ["b"] },
+ });
+ assert_equals(
+ node.querySelector("#span"),
+ null,
+ "Default policy sanitizer must remove span",
+ );
+ assert_not_equals(
+ node.querySelector("#bold"),
+ null,
+ "Overridden caller sanitizer must not remove b",
+ );
+ assert_not_equals(node.querySelector("#allowed"), null);
+ }, `${target}.${method}: default policy createParserOptions sanitizer overrides caller sanitizer dictionary with TrustedHTML`);
+
+ test((t) => {
+ const node = createTarget(target, t);
+ createParserOptions = (options) => options;
+ const trustedHTML = testPolicy.createHTML(
+ "<div id='allowed'><span id='span'></span><b id='bold'></b></div>",
+ );
+ run_method(node, method, trustedHTML, {
+ sanitizer: { removeElements: ["b"] },
+ });
+ assert_equals(
+ node.querySelector("#bold"),
+ null,
+ "Caller-provided sanitizer dictionary passed through by default policy must remove b",
+ );
+ assert_not_equals(node.querySelector("#span"), null);
+ assert_not_equals(node.querySelector("#allowed"), null);
+ }, `${target}.${method}: caller-provided sanitizer dictionary is applied with TrustedHTML when default policy passes it through`);
+
+ test((t) => {
+ const node = createTarget(target, t);
+ let createParserOptionsCalled = false;
+ createParserOptions = (options) => {
+ createParserOptionsCalled = true;
+ return {
+ ...options,
+ sanitizer: { removeElements: ["span"] },
+ };
+ };
+ const trustedHTML = testPolicy.createHTML(
+ "<div id='allowed'><span id='span'></span><b id='bold'></b></div>",
+ );
+ const parserOptions = testPolicy.createParserOptions({
+ sanitizer: { removeElements: ["b"] },
+ });
+ run_method(node, method, trustedHTML, parserOptions);
+ assert_false(
+ createParserOptionsCalled,
+ "Default policy createParserOptions must not be called when TrustedHTMLParserOptions is passed",
+ );
+ assert_equals(
+ node.querySelector("#bold"),
+ null,
+ "Caller-provided TrustedHTMLParserOptions sanitizer must remove b",
+ );
+ assert_not_equals(
+ node.querySelector("#span"),
+ null,
+ "Default policy sanitizer is not applied when default policy is bypassed",
+ );
+ assert_not_equals(node.querySelector("#allowed"), null);
+ }, `${target}.${method}: caller-provided TrustedHTMLParserOptions sanitizer is applied with TrustedHTML while default policy is bypassed`);
+
+ // runScripts tests with TrustedHTML
+ test((t) => {
+ const node = createTarget(target, t);
+ window.trusted_script_ran = false;
+ t.add_cleanup(() => {
+ window.trusted_script_ran = false;
+ });
+ createParserOptions = (options) => ({
+ ...options,
+ runScripts: false,
+ });
+ const trustedHTML = testPolicy.createHTML(
+ "<div id='allowed'><script>window.trusted_script_ran = true;</" +
+ "script></div>",
+ );
+ run_method(node, method, trustedHTML);
+ assert_false(
+ window.trusted_script_ran,
+ "Default policy createParserOptions(runScripts=false) must disable script execution",
+ );
+ assert_not_equals(node.querySelector("#allowed"), null);
+ }, `${target}.${method}: default policy createParserOptions can disable runScripts`);
+
+ test((t) => {
+ const node = createTarget(target, t);
+ window.trusted_script_ran = false;
+ t.add_cleanup(() => {
+ window.trusted_script_ran = false;
+ });
+ createParserOptions = (options) => ({
+ ...options,
+ runScripts: true,
+ });
+ const trustedHTML = testPolicy.createHTML(
+ "<div id='allowed'><script>window.trusted_script_ran = true;</" +
+ "script></div>",
+ );
+ run_method(node, method, trustedHTML);
+ assert_true(
+ window.trusted_script_ran,
+ "Default policy createParserOptions can enable runScripts",
+ );
+ assert_not_equals(node.querySelector("#allowed"), null);
+ }, `${target}.${method}: default policy createParserOptions can enable runScripts`);
+
+ test((t) => {
+ const node = createTarget(target, t);
+ window.trusted_script_ran = false;
+ t.add_cleanup(() => {
+ window.trusted_script_ran = false;
+ });
+ createParserOptions = (options) => options;
+ const trustedHTML = testPolicy.createHTML(
+ "<div id='allowed'><script>window.trusted_script_ran = true;</" +
+ "script></div>",
+ );
+ run_method(
+ node,
+ method,
+ trustedHTML,
+ testPolicy.createParserOptions({ runScripts: true }),
+ );
+ assert_true(
+ window.trusted_script_ran,
+ "TrustedHTML with runScripts=true runs scripts when default policy allows it",
+ );
+ assert_not_equals(node.querySelector("#allowed"), null);
+ }, `${target}.${method}: TrustedHTML runs scripts when caller requests runScripts and default policy allows it`);
+ }
+
+ for (const method of [
+ "innerHTML",
+ "outerHTML",
+ "afterbegin",
+ "beforeend",
+ "beforebegin",
+ "afterend",
+ ]) {
+ if (target === "ShadowRoot" && method !== "innerHTML") {
+ continue;
+ }
+ test((t) => {
+ const node = createTarget(target, t);
+ window.trusted_script_ran = false;
+ t.add_cleanup(() => {
+ window.trusted_script_ran = false;
+ });
+ let receivedRunScripts = null;
+ createParserOptions = (options) => {
+ receivedRunScripts = options.runScripts;
+ return { runScripts: true };
+ };
+ const trustedHTML = testPolicy.createHTML(
+ "<div id='allowed'><script>window.trusted_script_ran = true;</" +
+ "script></div>",
+ );
+ run_method(node, method, trustedHTML);
+ assert_false(receivedRunScripts, "Initial runScripts option should be false");
+ assert_true(
+ window.trusted_script_ran,
+ `Default policy returning {runScripts: true} enables script execution for ${method}`,
+ );
+ assert_not_equals(node.querySelector("#allowed"), null);
+ }, `${target}.${method}: default policy createParserOptions returning {runScripts: true} enables script execution with TrustedHTML`);
+ }
+ }
+
+ // createContextualFragment runScripts tests with TrustedHTML
+ test((t) => {
+ const node = createTarget("Element", t);
+ window.trusted_script_ran = false;
+ t.add_cleanup(() => {
+ window.trusted_script_ran = false;
+ });
+ createParserOptions = (options) => ({
+ ...options,
+ runScripts: false,
+ });
+ const range = document.createRange();
+ range.selectNode(node);
+ const trustedHTML = testPolicy.createHTML(
+ "<script>window.trusted_script_ran = true;</" + "script>",
+ );
+ const fragment = range.createContextualFragment(trustedHTML);
+ node.append(fragment);
+ assert_false(
+ window.trusted_script_ran,
+ "Default policy createParserOptions(runScripts=false) disables scripts in fragment from TrustedHTML",
+ );
+ }, "Element: createContextualFragment with TrustedHTML and createParserOptions(runScripts=false) does not run scripts");
+
+ test((t) => {
+ const node = createTarget("Element", t);
+ window.trusted_script_ran = false;
+ t.add_cleanup(() => {
+ window.trusted_script_ran = false;
+ });
+ createParserOptions = (options) => options;
+ const range = document.createRange();
+ range.selectNode(node);
+ const trustedHTML = testPolicy.createHTML(
+ "<script>window.trusted_script_ran = true;</" + "script>",
+ );
+ const fragment = range.createContextualFragment(trustedHTML);
+ node.append(fragment);
+ assert_true(
+ window.trusted_script_ran,
+ "createContextualFragment with TrustedHTML runs scripts by default",
+ );
+ }, "Element: createContextualFragment with TrustedHTML runs scripts by default");
+
+ // Document.parseHTMLUnsafe with caller-provided options and TrustedHTML
+ test((t) => {
+ t.add_cleanup(() => {
+ createParserOptions = (options) => options;
+ });
+ createParserOptions = (options) => ({
+ ...options,
+ sanitizer: { removeElements: ["span"] },
+ });
+ const trustedHTML = testPolicy.createHTML(
+ "<div id='allowed'><span id='span'></span><b id='bold'></b></div>",
+ );
+ const doc = Document.parseHTMLUnsafe(trustedHTML, {
+ sanitizer: { removeElements: ["b"] },
+ });
+ assert_equals(
+ doc.querySelector("#span"),
+ null,
+ "Default policy sanitizer must remove span",
+ );
+ assert_not_equals(
+ doc.querySelector("#bold"),
+ null,
+ "Overridden caller sanitizer must not remove b",
+ );
+ assert_not_equals(doc.querySelector("#allowed"), null);
+ }, "Document.parseHTMLUnsafe: default policy createParserOptions sanitizer overrides caller sanitizer dictionary with TrustedHTML");
+
+ test((t) => {
+ t.add_cleanup(() => {
+ createParserOptions = (options) => options;
+ });
+ createParserOptions = (options) => options;
+ const trustedHTML = testPolicy.createHTML(
+ "<div id='allowed'><span id='span'></span><b id='bold'></b></div>",
+ );
+ const doc = Document.parseHTMLUnsafe(trustedHTML, {
+ sanitizer: { removeElements: ["b"] },
+ });
+ assert_equals(
+ doc.querySelector("#bold"),
+ null,
+ "Caller-provided sanitizer dictionary passed through by default policy must remove b",
+ );
+ assert_not_equals(doc.querySelector("#span"), null);
+ assert_not_equals(doc.querySelector("#allowed"), null);
+ }, "Document.parseHTMLUnsafe: caller-provided sanitizer dictionary is applied with TrustedHTML when default policy passes it through");
+
+ test((t) => {
+ t.add_cleanup(() => {
+ createParserOptions = (options) => options;
+ });
+ let createParserOptionsCalled = false;
+ createParserOptions = (options) => {
+ createParserOptionsCalled = true;
+ return {
+ ...options,
+ sanitizer: { removeElements: ["span"] },
+ };
+ };
+ const trustedHTML = testPolicy.createHTML(
+ "<div id='allowed'><span id='span'></span><b id='bold'></b></div>",
+ );
+ const parserOptions = testPolicy.createParserOptions({
+ sanitizer: { removeElements: ["b"] },
+ });
+ const doc = Document.parseHTMLUnsafe(trustedHTML, parserOptions);
+ assert_false(
+ createParserOptionsCalled,
+ "Default policy createParserOptions must not be called when TrustedHTMLParserOptions is passed",
+ );
+ assert_equals(
+ doc.querySelector("#bold"),
+ null,
+ "Caller-provided TrustedHTMLParserOptions sanitizer must remove b",
+ );
+ assert_not_equals(
+ doc.querySelector("#span"),
+ null,
+ "Default policy sanitizer is not applied when default policy is bypassed",
+ );
+ assert_not_equals(doc.querySelector("#allowed"), null);
+ }, "Document.parseHTMLUnsafe: caller-provided TrustedHTMLParserOptions sanitizer is applied with TrustedHTML while default policy is bypassed");
+
+ // XML document tests with TrustedHTML:
+ // In XML documents, documentType is "xml" so createParserOptions does not run at all for legacy XML sinks
+ // (innerHTML, outerHTML, insertAdjacentHTML, createContextualFragment). Passing TrustedHTML satisfies
+ // get trusted type compliant string without calling createHTML or createParserOptions.
+ test((t) => {
+ t.add_cleanup(() => {
+ createParserOptions = (options) => options;
+ createHTML = (html) => html;
+ });
+ let createParserOptionsCalled = false;
+ createParserOptions = (options) => {
+ createParserOptionsCalled = true;
+ return { sanitizer: { removeElements: ["span"] } };
+ };
+ createHTML = () => {
+ throw new Error("createHTML should not be called for TrustedHTML in XML document");
+ };
+
+ const doc = document.implementation.createDocument("application/xml", "xml");
+ const elem = doc.createElement("div");
+ doc.documentElement.appendChild(elem);
+
+ const trustedHTML = testPolicy.createHTML("<span id='xml-span'></span>");
+ elem.innerHTML = trustedHTML;
+ assert_false(
+ createParserOptionsCalled,
+ "createParserOptions must not be called for innerHTML on XML document",
+ );
+ assert_not_equals(
+ elem.querySelector("#xml-span"),
+ null,
+ "innerHTML on XML document does not throw and inserts TrustedHTML",
+ );
+ }, "innerHTML on XML document does not call createParserOptions or throw TypeError when TrustedHTML is passed");
+
+ test((t) => {
+ t.add_cleanup(() => {
+ createParserOptions = (options) => options;
+ createHTML = (html) => html;
+ });
+ let createParserOptionsCalled = false;
+ createParserOptions = (options) => {
+ createParserOptionsCalled = true;
+ return { sanitizer: { removeElements: ["span"] } };
+ };
+ createHTML = () => {
+ throw new Error("createHTML should not be called for TrustedHTML in XML document");
+ };
+
+ const doc = document.implementation.createDocument("application/xml", "xml");
+ const elem = doc.createElement("div");
+ doc.documentElement.appendChild(elem);
+
+ const trustedHTML = testPolicy.createHTML("<span id='xml-span'></span>");
+ elem.outerHTML = trustedHTML;
+ assert_false(
+ createParserOptionsCalled,
+ "createParserOptions must not be called for outerHTML on XML document",
+ );
+ assert_not_equals(
+ doc.querySelector("#xml-span"),
+ null,
+ "outerHTML on XML document does not throw and inserts TrustedHTML",
+ );
+ }, "outerHTML on XML document does not call createParserOptions or throw TypeError when TrustedHTML is passed");
+
+ test((t) => {
+ t.add_cleanup(() => {
+ createParserOptions = (options) => options;
+ createHTML = (html) => html;
+ });
+ let createParserOptionsCalled = false;
+ createParserOptions = (options) => {
+ createParserOptionsCalled = true;
+ return { sanitizer: { removeElements: ["span"] } };
+ };
+ createHTML = () => {
+ throw new Error("createHTML should not be called for TrustedHTML in XML document");
+ };
+
+ const doc = document.implementation.createDocument("application/xml", "xml");
+ const elem = doc.createElement("div");
+ doc.documentElement.appendChild(elem);
+
+ const trustedHTML = testPolicy.createHTML("<span id='xml-span'></span>");
+ elem.insertAdjacentHTML("beforeend", trustedHTML);
+ assert_false(
+ createParserOptionsCalled,
+ "createParserOptions must not be called for insertAdjacentHTML on XML document",
+ );
+ assert_not_equals(
+ elem.querySelector("#xml-span"),
+ null,
+ "insertAdjacentHTML on XML document does not throw and inserts TrustedHTML",
+ );
+ }, "insertAdjacentHTML on XML document does not call createParserOptions or throw TypeError when TrustedHTML is passed");
+
+ test((t) => {
+ t.add_cleanup(() => {
+ createParserOptions = (options) => options;
+ createHTML = (html) => html;
+ });
+ let createParserOptionsCalled = false;
+ createParserOptions = (options) => {
+ createParserOptionsCalled = true;
+ return { sanitizer: { removeElements: ["span"] } };
+ };
+ createHTML = () => {
+ throw new Error("createHTML should not be called for TrustedHTML in XML document");
+ };
+
+ const doc = document.implementation.createDocument("application/xml", "xml");
+ const range = doc.createRange();
+ range.selectNode(doc.documentElement);
+
+ const trustedHTML = testPolicy.createHTML("<span id='xml-span'></span>");
+ const fragment = range.createContextualFragment(trustedHTML);
+ assert_false(
+ createParserOptionsCalled,
+ "createParserOptions must not be called for createContextualFragment on XML document",
+ );
+ assert_not_equals(
+ fragment.querySelector("#xml-span"),
+ null,
+ "createContextualFragment on XML document does not throw and returns fragment for TrustedHTML",
+ );
+ }, "createContextualFragment on XML document does not call createParserOptions or throw TypeError when TrustedHTML is passed");
+
+ for (const method of [
+ "setHTMLUnsafe",
+ "appendHTMLUnsafe",
+ "prependHTMLUnsafe",
+ "beforeHTMLUnsafe",
+ "afterHTMLUnsafe",
+ "replaceWithHTMLUnsafe",
+ ]) {
+ test((t) => {
+ t.add_cleanup(() => {
+ createParserOptions = (options) => options;
+ createHTML = (html) => html;
+ });
+ let createParserOptionsCalled = false;
+ createParserOptions = (options) => {
+ createParserOptionsCalled = true;
+ return { sanitizer: { removeElements: ["span"] } };
+ };
+ createHTML = () => {
+ throw new Error("createHTML should not be called for TrustedHTML in XML document");
+ };
+
+ const doc = document.implementation.createDocument("application/xml", "xml");
+ const elem = doc.createElement("div");
+ doc.documentElement.appendChild(elem);
+ let receiver = elem;
+ if (["beforeHTMLUnsafe", "afterHTMLUnsafe", "replaceWithHTMLUnsafe"].includes(method)) {
+ const ref = doc.createElement("div");
+ elem.appendChild(ref);
+ receiver = ref;
+ }
+
+ const trustedHTML = testPolicy.createHTML("<div id='allowed'><span id='forbidden'></span></div>");
+ receiver[method](trustedHTML);
+ assert_true(
+ createParserOptionsCalled,
+ `createParserOptions must be called for ${method} even on XML document`,
+ );
+ assert_not_equals(elem.querySelector("#allowed"), null);
+ assert_equals(elem.querySelector("#forbidden"), null);
+ }, `${method} on XML document calls createParserOptions and applies sanitizer when TrustedHTML is passed`);
+ }
+ </script>
+ </body>
+</html>
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-with-trustedtypes-createParserOptions-null.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-with-trustedtypes-createParserOptions-null.html
new file mode 100644
index 00000000000..94dabde829a
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-with-trustedtypes-createParserOptions-null.html
@@ -0,0 +1,30 @@
+<!doctype html>
+<html>
+ <head>
+ <script src="../resources/testharness.js"></script>
+ <script src="../resources/testharnessreport.js"></script>
+ <meta
+ http-equiv="Content-Security-Policy"
+ content="require-trusted-types-for 'script';"
+ />
+ </head>
+ <body>
+ <div id="container"></div>
+ <script>
+ const container = document.querySelector("#container");
+
+ for (const returnValue of [null, undefined]) {
+ const policy = trustedTypes.createPolicy(`returns-${returnValue}`, {
+ createHTML: (html) => html,
+ createParserOptions: () => returnValue,
+ });
+
+ test(() => {
+ assert_throws_js(TypeError, () => {
+ policy.createParserOptions({});
+ });
+ }, `Named policy createParserOptions returning ${returnValue} throws TypeError`);
+ }
+ </script>
+ </body>
+</html>
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-with-trustedtypes-createParserOptions.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-with-trustedtypes-createParserOptions.html
new file mode 100644
index 00000000000..550297c3749
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-with-trustedtypes-createParserOptions.html
@@ -0,0 +1,372 @@
+<!doctype html>
+<html>
+ <head>
+ <script src="../resources/testharness.js"></script>
+ <script src="../resources/testharnessreport.js"></script>
+ <script src="../trusted-types/support/helper.sub.js"></script>
+
+ <meta
+ http-equiv="Content-Security-Policy"
+ content="require-trusted-types-for 'script';"
+ />
+ </head>
+ <body>
+ <div id="container"></div>
+ <script>
+ const container = document.querySelector("#container");
+ // We have to replace this global because we are overriding the default policy from within the test.
+ let createParserOptions = (options) => ({
+ sanitizer: { removeElements: ["div"] },
+ });
+ let createHTML = (html) => html;
+
+ trustedTypes.createPolicy("default", {
+ createHTML: (html) => createHTML(html),
+ createParserOptions: (options) => createParserOptions(options),
+ });
+
+ const passthrough = trustedTypes.createPolicy("passthrough", {
+ createHTML: (html) => createHTML(html),
+ createParserOptions: (options) => options,
+ });
+
+ function createTarget(target_type, t) {
+ t.add_cleanup(() => {
+ createParserOptions = (options) => ({
+ sanitizer: { removeElements: ["div"] },
+ });
+ createHTML = (html) => html;
+ });
+
+ const target = document.createElement("div");
+ container.append(target);
+ t.add_cleanup(() => target.remove());
+ switch (target_type) {
+ case "Element":
+ return target;
+ case "ShadowRoot":
+ return target.attachShadow({ mode: "open" });
+ }
+ }
+
+ const noCreateHTMLPolicy = trustedTypes.createPolicy("no-create-html", {
+ createParserOptions: (options) => options,
+ });
+
+ const noSanitizerPolicy = trustedTypes.createPolicy("no-sanitizer", {
+ createParserOptions: (options) => ({}),
+ });
+
+ function createMethodTarget(target_type, method, t) {
+ const root = createTarget(target_type, t);
+ if (["beforeHTMLUnsafe", "afterHTMLUnsafe", "replaceWithHTMLUnsafe"].includes(method)) {
+ const ref = document.createElement("div");
+ root.appendChild(ref);
+ return { receiver: ref, root };
+ }
+ return { receiver: root, root };
+ }
+
+ for (const target of ["ShadowRoot", "Element"]) {
+ for (const method of [
+ "setHTMLUnsafe",
+ "appendHTMLUnsafe",
+ "prependHTMLUnsafe",
+ "beforeHTMLUnsafe",
+ "afterHTMLUnsafe",
+ "replaceWithHTMLUnsafe",
+ ]) {
+ if (
+ target === "ShadowRoot" &&
+ ["beforeHTMLUnsafe", "afterHTMLUnsafe", "replaceWithHTMLUnsafe"].includes(method)
+ ) {
+ continue;
+ }
+
+ test((t) => {
+ const { receiver, root } = createMethodTarget(target, method, t);
+ receiver[method](
+ "<div id='allowed'><span id=forbidden></span></div>",
+ passthrough.createParserOptions({
+ sanitizer: { removeElements: ["span"] },
+ }),
+ );
+ assert_equals(root.querySelector("#forbidden"), null);
+ assert_not_equals(root.querySelector("#allowed"), null);
+ }, `${target}.${method}: passing a TrustedHTMLParserOptions overrides default policy`);
+
+ test((t) => {
+ const { receiver, root } = createMethodTarget(target, method, t);
+ receiver[method](
+ "<div id='allowed'><span id=forbidden></span></div>",
+ noCreateHTMLPolicy.createParserOptions({
+ sanitizer: { removeElements: ["span"] },
+ }),
+ );
+ assert_equals(root.querySelector("#forbidden"), null);
+ assert_not_equals(root.querySelector("#allowed"), null);
+ }, `${target}.${method}: policy with only createParserOptions allows raw strings when sanitizer is present`);
+
+ test((t) => {
+ const { receiver, root } = createMethodTarget(target, method, t);
+ receiver[method](
+ "<div id='allowed'><span id='child'></span></div>",
+ noCreateHTMLPolicy.createParserOptions({}),
+ );
+ assert_not_equals(root.querySelector("#allowed"), null);
+ assert_not_equals(root.querySelector("#child"), null);
+ }, `${target}.${method}: policy with only createParserOptions allows raw strings without sanitizer`);
+
+ test((t) => {
+ const { receiver, root } = createMethodTarget(target, method, t);
+ createHTML = (html) => {
+ throw new Error("createHTML should not be called when TrustedHTMLParserOptions is passed");
+ };
+ receiver[method](
+ "<div id='allowed'><span id='allowed-child'></span></div>",
+ noSanitizerPolicy.createParserOptions({}),
+ );
+ assert_not_equals(root.querySelector("#allowed"), null);
+ assert_not_equals(root.querySelector("#allowed-child"), null);
+ }, `${target}.${method}: TrustedHTMLParserOptions without sanitizer satisfies Trusted Types and does not require createHTML`);
+
+ test((t) => {
+ const { receiver } = createMethodTarget(target, method, t);
+ let createHTMLCalled = false;
+ createParserOptions = (options) => {
+ throw new Error("createParserOptions failed");
+ };
+ createHTML = (html) => {
+ createHTMLCalled = true;
+ return html;
+ };
+ assert_throws_js(Error, () => {
+ receiver[method]("<div id='allowed'></div>");
+ });
+ assert_false(
+ createHTMLCalled,
+ "createHTML should not have been called",
+ );
+ }, `${target}.${method}: exception in default createParserOptions prevents createHTML from running`);
+
+ test((t) => {
+ const { receiver, root } = createMethodTarget(target, method, t);
+ createParserOptions = (options) => ({
+ sanitizer: { removeElements: ["span"] },
+ });
+ createHTML = (html) => {
+ throw new Error(
+ "createHTML should not be called when sanitizer is present",
+ );
+ };
+ receiver[method](
+ "<div id='allowed'><span id=forbidden></span></div>",
+ );
+ assert_equals(root.querySelector("#forbidden"), null);
+ assert_not_equals(root.querySelector("#allowed"), null);
+ }, `${target}.${method}: default policy createParserOptions with sanitizer prevents createHTML from running`);
+
+ test((t) => {
+ const { receiver, root } = createMethodTarget(target, method, t);
+ createParserOptions = (options) => ({});
+ createHTML = (html) => {
+ throw new Error("createHTML should not be called when default policy provides createParserOptions");
+ };
+ receiver[method](
+ "<div id='allowed'><span id='allowed-child'></span></div>",
+ );
+ assert_not_equals(root.querySelector("#allowed"), null);
+ assert_not_equals(root.querySelector("#allowed-child"), null);
+ }, `${target}.${method}: default policy createParserOptions without sanitizer prevents createHTML from running`);
+
+ test((t) => {
+ const { receiver, root } = createMethodTarget(target, method, t);
+ window.did_run = false;
+ t.add_cleanup(() => {
+ window.did_run = false;
+ });
+ createParserOptions = (options) => ({
+ runScripts: true,
+ });
+ createHTML = (html) => html;
+ receiver[method](
+ "<div id='allowed'><script>window.did_run = true;<" +
+ "/script></div>",
+ { runScripts: false },
+ );
+ assert_true(
+ window.did_run,
+ "Default policy createParserOptions can enable runScripts even if caller passed false",
+ );
+ assert_not_equals(root.querySelector("#allowed"), null);
+ }, `${target}.${method}: default policy createParserOptions can override runScripts from false to true`);
+
+ test((t) => {
+ const { receiver, root } = createMethodTarget(target, method, t);
+ window.did_run = false;
+ t.add_cleanup(() => {
+ window.did_run = false;
+ });
+ createParserOptions = (options) => ({
+ runScripts: false,
+ });
+ createHTML = (html) => html;
+ receiver[method](
+ "<div id='allowed'><script>window.did_run = true;<" +
+ "/script></div>",
+ { runScripts: true },
+ );
+ assert_false(
+ window.did_run,
+ "Default policy createParserOptions can override runScripts from true to false",
+ );
+ assert_not_equals(root.querySelector("#allowed"), null);
+ }, `${target}.${method}: default policy createParserOptions can override runScripts from true to false`);
+ }
+ }
+
+ test((t) => {
+ let capturedArgs = [];
+ const policy = trustedTypes.createPolicy("extra-args-policy", {
+ createParserOptions: (options, ...args) => {
+ capturedArgs = args;
+ return options;
+ },
+ });
+ policy.createParserOptions({}, "arg1", 42, { extra: true });
+ assert_equals(capturedArgs.length, 3);
+ assert_equals(capturedArgs[0], "arg1");
+ assert_equals(capturedArgs[1], 42);
+ assert_true(capturedArgs[2].extra);
+ }, "TrustedTypePolicy.createParserOptions forwards extra arguments to callback");
+
+ test((t) => {
+ let capturedOptions = null;
+ const policy = trustedTypes.createPolicy("options-inspect-policy", {
+ createParserOptions: (options) => {
+ capturedOptions = options;
+ return options;
+ },
+ });
+ const sanitizer = new Sanitizer();
+ policy.createParserOptions({ runScripts: true, sanitizer });
+ assert_true(capturedOptions.runScripts);
+ assert_true(capturedOptions.sanitizer instanceof Sanitizer);
+ }, "TrustedTypePolicy.createParserOptions callback receives converted options dictionary");
+
+ test((t) => {
+ const policy = trustedTypes.createPolicy("runscripts-reflect-policy", {
+ createParserOptions: (options) => options,
+ });
+ const optionsDefault = policy.createParserOptions({});
+ assert_true(optionsDefault instanceof TrustedHTMLParserOptions);
+ assert_false("runScripts" in optionsDefault, "TrustedHTMLParserOptions has no public runScripts member");
+
+ const optionsTrue = policy.createParserOptions({ runScripts: true });
+ assert_true(optionsTrue instanceof TrustedHTMLParserOptions);
+ assert_false("runScripts" in optionsTrue, "TrustedHTMLParserOptions has no public runScripts member");
+
+ const optionsFalse = policy.createParserOptions({ runScripts: false });
+ assert_true(optionsFalse instanceof TrustedHTMLParserOptions);
+ assert_false("runScripts" in optionsFalse, "TrustedHTMLParserOptions has no public runScripts member");
+
+ const div = document.createElement("div");
+ document.body.appendChild(div);
+ t.add_cleanup(() => div.remove());
+
+ window.did_run = false;
+ t.add_cleanup(() => { delete window.did_run; });
+
+ div.setHTMLUnsafe("<script>window.did_run = true;<" + "/script>", optionsDefault);
+ assert_false(window.did_run, "runScripts defaults to false in TrustedHTMLParserOptions");
+
+ div.setHTMLUnsafe("<script>window.did_run = true;<" + "/script>", optionsFalse);
+ assert_false(window.did_run, "runScripts false is respected in TrustedHTMLParserOptions");
+
+ div.setHTMLUnsafe("<script>window.did_run = true;<" + "/script>", optionsTrue);
+ assert_true(window.did_run, "runScripts true is respected in TrustedHTMLParserOptions");
+ }, "TrustedHTMLParserOptions applies runScripts option without exposing public members");
+
+ for (const value of [0, 123, true, false, "string"]) {
+ test((t) => {
+ const policy = trustedTypes.createPolicy(`non-object-cpo-${String(value)}`, {
+ createParserOptions: () => value,
+ });
+ assert_throws_js(TypeError, () => {
+ policy.createParserOptions({});
+ });
+ }, `TrustedTypePolicy.createParserOptions returning something other than an object (${typeof value}: ${JSON.stringify(value)}) throws a TypeError`);
+
+ test((t) => {
+ t.add_cleanup(() => {
+ createParserOptions = (options) => ({
+ sanitizer: { removeElements: ["div"] },
+ });
+ createHTML = (html) => html;
+ });
+ createParserOptions = () => value;
+ createHTML = (html) => html;
+ const node = createTarget("Element", t);
+ assert_throws_js(TypeError, () => {
+ node.setHTMLUnsafe("<div id='allowed'></div>");
+ });
+ }, `Element.setHTMLUnsafe: default policy createParserOptions returning something other than an object (${typeof value}: ${JSON.stringify(value)}) throws a TypeError`);
+ }
+
+ test((t) => {
+ t.add_cleanup(() => {
+ createParserOptions = (options) => ({
+ sanitizer: { removeElements: ["div"] },
+ });
+ createHTML = (html) => html;
+ });
+ createHTML = (html) => {
+ throw new Error("createHTML should not be called when TrustedHTMLParserOptions is passed");
+ };
+ const doc = Document.parseHTMLUnsafe(
+ "<div id='allowed'><span id='allowed-child'></span></div>",
+ noSanitizerPolicy.createParserOptions({}),
+ );
+ assert_not_equals(doc.querySelector("#allowed"), null);
+ assert_not_equals(doc.querySelector("#allowed-child"), null);
+ }, "Document.parseHTMLUnsafe: TrustedHTMLParserOptions without sanitizer satisfies Trusted Types and does not require createHTML");
+
+ test((t) => {
+ t.add_cleanup(() => {
+ createParserOptions = (options) => ({
+ sanitizer: { removeElements: ["div"] },
+ });
+ createHTML = (html) => html;
+ });
+ createParserOptions = (options) => ({});
+ createHTML = (html) => {
+ throw new Error("createHTML should not be called when default policy provides createParserOptions");
+ };
+ const doc = Document.parseHTMLUnsafe(
+ "<div id='allowed'><span id='allowed-child'></span></div>",
+ );
+ assert_not_equals(doc.querySelector("#allowed"), null);
+ assert_not_equals(doc.querySelector("#allowed-child"), null);
+ }, "Document.parseHTMLUnsafe: default policy createParserOptions without sanitizer prevents createHTML from running");
+
+ promise_test(async (t) => {
+ const iframe = document.createElement("iframe");
+ document.body.appendChild(iframe);
+ t.add_cleanup(() => iframe.remove());
+
+ let createHTMLCalled = false;
+ iframe.contentWindow.trustedTypes.createPolicy("default", {
+ createHTML: (html) => {
+ createHTMLCalled = true;
+ return html;
+ },
+ });
+
+ const target = iframe.contentDocument.createElement("div");
+ target.setHTMLUnsafe("<div id='allowed'></div>");
+ assert_true(createHTMLCalled, "createHTML must be called when default policy lacks createParserOptions");
+ assert_not_equals(target.querySelector("#allowed"), null);
+ }, "Element.setHTMLUnsafe: default policy without createParserOptions falls back to createHTML");
+ </script>
+ </body>
+</html>
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-with-trustedtypes-immutable.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-with-trustedtypes-immutable.html
new file mode 100644
index 00000000000..62523dea88d
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-with-trustedtypes-immutable.html
@@ -0,0 +1,167 @@
+<!doctype html>
+<html>
+ <head>
+ <script src="../resources/testharness.js"></script>
+ <script src="../resources/testharnessreport.js"></script>
+ <script src="../trusted-types/support/helper.sub.js"></script>
+
+ <meta
+ http-equiv="Content-Security-Policy"
+ content="require-trusted-types-for 'script';"
+ />
+ </head>
+ <body>
+ <div id="container"></div>
+ <script>
+ const container = document.querySelector("#container");
+ // We have to replace this global because we are overriding the default policy from within the test.
+ trustedTypes.createPolicy("default", {
+ createHTML: (html) => html,
+ createParserOptions: (options) => {
+ options.modified = true;
+ if (options.sanitizer instanceof Sanitizer) {
+ options.sanitizer.removeElement("span");
+ options.sanitizer.allowAttribute("id");
+ } else if (
+ options.sanitizer &&
+ typeof options.sanitizer === "object"
+ ) {
+ options.sanitizer.removeElements = ["span"];
+ }
+ return options;
+ },
+ });
+
+ function createMethodTarget(method, t) {
+ const parent = document.createElement("div");
+ document.querySelector("#container").appendChild(parent);
+ t.add_cleanup(() => parent.remove());
+ if (["beforeHTMLUnsafe", "afterHTMLUnsafe", "replaceWithHTMLUnsafe"].includes(method)) {
+ const ref = document.createElement("div");
+ parent.appendChild(ref);
+ return { receiver: ref, root: parent };
+ }
+ return { receiver: parent, root: parent };
+ }
+
+ for (const method of [
+ "setHTMLUnsafe",
+ "appendHTMLUnsafe",
+ "prependHTMLUnsafe",
+ "beforeHTMLUnsafe",
+ "afterHTMLUnsafe",
+ "replaceWithHTMLUnsafe",
+ ]) {
+ test((t) => {
+ const { receiver, root } = createMethodTarget(method, t);
+ const options = { sanitizer: {}, modified: false };
+ receiver[method](
+ "<div id='allowed'><span id=forbidden></span></div>",
+ options,
+ );
+ assert_false(
+ options.modified,
+ "trusted types policy should not modify given options",
+ );
+ assert_false(
+ "removeElements" in options.sanitizer,
+ "trusted types policy should not modify sanitizer",
+ );
+ assert_equals(root.querySelector("#forbidden"), null);
+ assert_not_equals(root.querySelector("#allowed"), null);
+ }, `${method}: createParserOptions doesn't mutate original object`);
+
+ test((t) => {
+ const { receiver, root } = createMethodTarget(method, t);
+ const options = { sanitizer: new Sanitizer() };
+ receiver[method](
+ "<div id=allowed><span id=forbidden></span></div>",
+ options,
+ );
+ const elements = options.sanitizer.get().elements;
+ const hasSpan = elements.some(el => el.name === "span");
+ assert_true(
+ hasSpan,
+ "trusted types policy should not modify original sanitizer elements list",
+ );
+ assert_false(
+ "removeElements" in options.sanitizer.get(),
+ "trusted types policy should not modify sanitizer structure",
+ );
+ assert_equals(root.querySelector("#forbidden"), null);
+ assert_not_equals(root.querySelector("#allowed"), null);
+ }, `${method}: createParserOptions doesn't mutate sanitizer object`);
+ }
+
+ test(() => {
+ assert_true("TrustedHTMLParserOptions" in window, "TrustedHTMLParserOptions should be exposed on window");
+ assert_false("TrustedParserOptions" in window, "TrustedParserOptions should not be exposed on window");
+ const protoNames = Object.getOwnPropertyNames(TrustedHTMLParserOptions.prototype);
+ assert_array_equals(protoNames, ["constructor"], "TrustedHTMLParserOptions must have no public members");
+ }, "TrustedHTMLParserOptions interface has no public members");
+
+ test((t) => {
+ let callback_sanitizer = null;
+ const policy = trustedTypes.createPolicy("p1", {
+ createHTML: (html) => html,
+ createParserOptions: (options) => {
+ callback_sanitizer = options.sanitizer;
+ return options;
+ }
+ });
+
+ // 1. Passing a config, check that the callback receives a Sanitizer object.
+ const options = policy.createParserOptions({ sanitizer: { removeElements: ["span"] } });
+ assert_true(callback_sanitizer instanceof Sanitizer, "callback should receive a Sanitizer object");
+
+ // 2. Check that the returned object is a TrustedHTMLParserOptions with no public members.
+ assert_true(options instanceof TrustedHTMLParserOptions, "createParserOptions should return a TrustedHTMLParserOptions");
+ assert_false("sanitizer" in options, "TrustedHTMLParserOptions should have no public sanitizer member");
+ assert_false("runScripts" in options, "TrustedHTMLParserOptions should have no public runScripts member");
+
+ const d = document.createElement("div");
+ document.querySelector("#container").appendChild(d);
+ t.add_cleanup(() => d.remove());
+
+ d.setHTMLUnsafe("<div>Allowed<span>Forbidden</span></div>", options);
+
+ assert_not_equals(d.querySelector("div"), null, "div should not be removed");
+ assert_equals(d.querySelector("span"), null, "span should be removed by original sanitizer configuration");
+ }, "TrustedHTMLParserOptions with config input applies sanitization without public members");
+
+ test((t) => {
+ let callback_sanitizer = null;
+ const policy = trustedTypes.createPolicy("p2", {
+ createHTML: (html) => html,
+ createParserOptions: (options) => {
+ callback_sanitizer = options.sanitizer;
+ return options;
+ }
+ });
+
+ const s = new Sanitizer();
+ const options = policy.createParserOptions({ sanitizer: s });
+ assert_true(callback_sanitizer instanceof Sanitizer, "callback should receive a Sanitizer object");
+ assert_not_equals(callback_sanitizer, s, "callback sanitizer should be a clone, not the original");
+ assert_true(options instanceof TrustedHTMLParserOptions, "should return a TrustedHTMLParserOptions");
+ assert_false("sanitizer" in options, "TrustedHTMLParserOptions should have no public sanitizer member");
+ }, "TrustedHTMLParserOptions clone testing with Sanitizer object input");
+
+ test((t) => {
+ let callback_sanitizer = null;
+ const policy = trustedTypes.createPolicy("p3", {
+ createHTML: (html) => html,
+ createParserOptions: (options) => {
+ callback_sanitizer = options.sanitizer;
+ return options;
+ }
+ });
+
+ const options = policy.createParserOptions({ sanitizer: "default" });
+ assert_true(callback_sanitizer instanceof Sanitizer, "callback should receive a Sanitizer object when preset is passed");
+ assert_true(options instanceof TrustedHTMLParserOptions, "should return a TrustedHTMLParserOptions");
+ assert_false("sanitizer" in options, "TrustedHTMLParserOptions should have no public sanitizer member");
+ }, "TrustedHTMLParserOptions with Preset string input");
+ </script>
+ </body>
+</html>
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-with-trustedtypes.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-with-trustedtypes.html
new file mode 100644
index 00000000000..1f853fe5424
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-with-trustedtypes.html
@@ -0,0 +1,434 @@
+<!doctype html>
+<html>
+ <head>
+ <script src="../resources/testharness.js"></script>
+ <script src="../resources/testharnessreport.js"></script>
+ <script src="../trusted-types/support/helper.sub.js"></script>
+
+ <meta
+ http-equiv="Content-Security-Policy"
+ content="require-trusted-types-for 'script';"
+ />
+ </head>
+ <body>
+ <div id="container"></div>
+ <script>
+ const container = document.querySelector("#container");
+ // We have to replace this global because we are overriding the default policy from within the test.
+ let createParserOptions = (options, type, sink) => options;
+ let createHTML = (html, ...args) => html;
+
+ trustedTypes.createPolicy("default", {
+ createHTML: (html, ...args) => createHTML(html, ...args),
+ createParserOptions: (options, ...args) => createParserOptions(options, ...args),
+ });
+
+ function createTarget(target_type, t) {
+ t.add_cleanup(() => {
+ createParserOptions = (options, type, sink) => options;
+ createHTML = (html, ...args) => html;
+ });
+
+ const target = document.createElement("div");
+ container.append(target);
+ t.add_cleanup(() => target.remove());
+ switch (target_type) {
+ case "Element":
+ return target;
+ case "ShadowRoot":
+ return target.attachShadow({ mode: "open" });
+ }
+ }
+
+ /**
+ *
+ * @param {Element|ShadowRoot} node
+ * @param {string} method
+ * @param {string} html
+ * @param {Object} [options]
+ */
+ function run_method(node, method, html, options) {
+ switch (method) {
+ case "innerHTML":
+ node[method] = html;
+ break;
+ case "outerHTML": {
+ const inner = document.createElement("div");
+ node.replaceChildren(inner);
+ inner[method] = html;
+ break;
+ }
+ case "afterbegin":
+ case "beforeend": {
+ node.insertAdjacentHTML(method, html);
+ break;
+ }
+ case "beforebegin":
+ case "afterend": {
+ const inner = document.createElement("div");
+ node.replaceChildren(inner);
+ inner.insertAdjacentHTML(method, html);
+ break;
+ }
+ case "beforeHTMLUnsafe":
+ case "afterHTMLUnsafe":
+ case "replaceWithHTMLUnsafe": {
+ const inner = document.createElement("div");
+ node.replaceChildren(inner);
+ inner[method](html, options);
+ break;
+ }
+ case "createContextualFragment":
+ const range = document.createRange();
+ range.setStart(node, 0);
+ range.setEnd(node, 0);
+ range.insertNode(range.createContextualFragment(html));
+ break;
+ default:
+ node[method](html, options);
+ }
+ }
+
+ const unsafe_methods_with_options = [
+ "setHTMLUnsafe",
+ "appendHTMLUnsafe",
+ "prependHTMLUnsafe",
+ "beforeHTMLUnsafe",
+ "afterHTMLUnsafe",
+ "replaceWithHTMLUnsafe",
+ "parseHTMLUnsafe",
+ ];
+
+ for (const target of ["ShadowRoot", "Element"]) {
+ for (const method of [
+ "setHTMLUnsafe",
+ "appendHTMLUnsafe",
+ "prependHTMLUnsafe",
+ "beforeHTMLUnsafe",
+ "afterHTMLUnsafe",
+ "replaceWithHTMLUnsafe",
+ "innerHTML",
+ "outerHTML",
+ "createContextualFragment",
+ "afterbegin",
+ "beforeend",
+ "beforebegin",
+ "afterend",
+ "parseHTMLUnsafe",
+ ]) {
+ if (
+ target === "ShadowRoot" &&
+ (method === "outerHTML" ||
+ method === "afterbegin" ||
+ method === "beforeend" ||
+ method === "beforebegin" ||
+ method === "afterend" ||
+ method === "beforeHTMLUnsafe" ||
+ method === "afterHTMLUnsafe" ||
+ method === "replaceWithHTMLUnsafe" ||
+ method === "createContextualFragment")
+ ) {
+ continue;
+ }
+ if (method === "parseHTMLUnsafe" && target === "ShadowRoot") {
+ continue; // Static method, run only once.
+ }
+
+ function get_root(node, method, html, options) {
+ if (method === "parseHTMLUnsafe") {
+ return Document.parseHTMLUnsafe(html, options);
+ } else {
+ run_method(node, method, html, options);
+ return node;
+ }
+ }
+
+ test((t) => {
+ const node = createTarget(target, t);
+ createParserOptions = (options) => ({
+ ...options,
+ sanitizer: { removeElements: ["span"] },
+ });
+ const root = get_root(
+ node,
+ method,
+ "<div id='allowed'><span id=forbidden></span></div>",
+ );
+ assert_equals(root.querySelector("#forbidden"), null);
+ assert_not_equals(root.querySelector("#allowed"), null);
+ }, `${target}.${method}: createParserOptions can inject a sanitizer config`);
+
+ test((t) => {
+ const node = createTarget(target, t);
+ let capturedSink = null;
+ let capturedType = null;
+ createParserOptions = (options, type, sink) => {
+ capturedType = type;
+ capturedSink = sink;
+ return options;
+ };
+ get_root(node, method, "<div id='allowed'></div>");
+ const expectedSink = method === "parseHTMLUnsafe"
+ ? "Document parseHTMLUnsafe"
+ : method === "createContextualFragment"
+ ? "Range createContextualFragment"
+ : method === "afterbegin" || method === "beforeend" || method === "beforebegin" || method === "afterend"
+ ? "Element insertAdjacentHTML"
+ : method === "beforeHTMLUnsafe" || method === "afterHTMLUnsafe" || method === "replaceWithHTMLUnsafe"
+ ? `Node ${method}`
+ : `${target} ${method}`;
+ assert_equals(capturedType, "TrustedHTMLParserOptions");
+ assert_equals(capturedSink, expectedSink);
+ }, `${target}.${method}: createParserOptions receives correct type and sink name`);
+
+ test((t) => {
+ const node = createTarget(target, t);
+ createParserOptions = (options) => ({
+ ...options,
+ sanitizer: new Sanitizer({ removeElements: ["span"] }),
+ });
+ const root = get_root(
+ node,
+ method,
+ "<div id=allowed><span id=forbidden></span></div>",
+ );
+ assert_equals(root.querySelector("#forbidden"), null);
+ assert_not_equals(root.querySelector("#allowed"), null);
+ }, `${target}.${method}: createParserOptions can inject a sanitizer`);
+
+ if (unsafe_methods_with_options.includes(method)) {
+ test((t) => {
+ const node = createTarget(target, t);
+ createParserOptions = (options) => ({
+ sanitizer: { removeElements: ["span"] },
+ });
+ const root = get_root(
+ node,
+ method,
+ "<div id=allowed><span id=forbidden></span></div>",
+ {
+ sanitizer: { removeElements: ["div"] },
+ },
+ );
+ assert_equals(root.querySelector("#forbidden"), null);
+ assert_not_equals(root.querySelector("#allowed"), null);
+ }, `${target}.${method}: createParserOptions can override a sanitizer config`);
+
+ test((t) => {
+ const node = createTarget(target, t);
+ createParserOptions = (options) => ({});
+ const root = get_root(node, method, "<div id=allowed></div>", {
+ sanitizer: { removeElements: ["div"] },
+ });
+ assert_not_equals(root.querySelector("#allowed"), null);
+ }, `${target}.${method}: createParserOptions can remove a sanitizer`);
+ }
+
+ for (const value of [null, undefined, 0, 123, "foo", true, false]) {
+ test((t) => {
+ const node = createTarget(target, t);
+ createParserOptions = (options) => value;
+ assert_throws_js(TypeError, () => {
+ get_root(
+ node,
+ method,
+ "<div id='allowed'><span id=forbidden></span></div>",
+ );
+ });
+ assert_equals(node.querySelector("#forbidden"), null);
+ assert_equals(node.textContent, "");
+ }, `${target}.${method}: createParserOptions returning ${JSON.stringify(value)} fails`);
+ }
+ }
+
+ for (const method of [
+ "setHTMLUnsafe",
+ "appendHTMLUnsafe",
+ "prependHTMLUnsafe",
+ "beforeHTMLUnsafe",
+ "afterHTMLUnsafe",
+ "replaceWithHTMLUnsafe",
+ ]) {
+ if (
+ target === "ShadowRoot" &&
+ ["beforeHTMLUnsafe", "afterHTMLUnsafe", "replaceWithHTMLUnsafe"].includes(method)
+ ) {
+ continue;
+ }
+
+ test((t) => {
+ const node = createTarget(target, t);
+ window.did_run = false;
+ t.add_cleanup(() => {
+ window.did_run = false;
+ });
+ createParserOptions = (options) => ({
+ runScripts: false,
+ });
+ run_method(
+ node,
+ method,
+ "<div id=allowed><script>window.did_run = true;<" +
+ "/script></div>",
+ { runScripts: true },
+ );
+ assert_false(window.did_run, "Default policy can override runScripts from true to false");
+ assert_not_equals(node.querySelector("#allowed"), null);
+ }, `${target}.${method}: createParserOptions can override runScripts from true to false`);
+
+ test((t) => {
+ const node = createTarget(target, t);
+ window.did_run = false;
+ t.add_cleanup(() => {
+ window.did_run = false;
+ });
+ createParserOptions = (options) => ({
+ runScripts: true,
+ });
+ run_method(
+ node,
+ method,
+ "<div id=allowed><script>window.did_run = true;<" +
+ "/script></div>",
+ { runScripts: false },
+ );
+ assert_true(window.did_run, "Default policy can override runScripts from false to true");
+ assert_not_equals(node.querySelector("#allowed"), null);
+ }, `${target}.${method}: createParserOptions can override runScripts from false to true`);
+
+ test((t) => {
+ const node = createTarget(target, t);
+ let createHTMLCalled = false;
+ createParserOptions = (options) => ({
+ ...options,
+ sanitizer: new Sanitizer({ removeElements: ["span"] }),
+ });
+ createHTML = (html) => {
+ createHTMLCalled = true;
+ return html.replaceAll("cat", "<span id=forbidden2></span><p>dog</p>");
+ };
+ run_method(
+ node,
+ method,
+ "<div id=allowed><span id=forbidden></span><div>cat</div></div>",
+ );
+ assert_equals(node.querySelector("#forbidden"), null);
+ assert_equals(node.querySelector("#forbidden2"), null);
+ assert_equals(node.textContent, "cat", node.innerHTML);
+ assert_not_equals(node.querySelector("#allowed"), null);
+ assert_false(createHTMLCalled, "createHTML should not be called when createParserOptions provides a sanitizer");
+ }, `${target}.${method}: createParserOptions with sanitizer prevents createHTML from running`);
+ }
+
+ for (const method of [
+ "innerHTML",
+ "outerHTML",
+ "afterbegin",
+ "beforeend",
+ "beforebegin",
+ "afterend",
+ ]) {
+ if (target === "ShadowRoot" && method !== "innerHTML") {
+ continue;
+ }
+ test((t) => {
+ const node = createTarget(target, t);
+ window.did_run = false;
+ t.add_cleanup(() => {
+ window.did_run = false;
+ });
+ let receivedRunScripts = null;
+ createParserOptions = (options) => {
+ receivedRunScripts = options.runScripts;
+ return { runScripts: true };
+ };
+ run_method(
+ node,
+ method,
+ "<div id=allowed><script>window.did_run = true;<" +
+ "/script></div>",
+ );
+ assert_false(receivedRunScripts, "Initial runScripts option should be false");
+ assert_true(
+ window.did_run,
+ `Default policy returning {runScripts: true} enables script execution for ${method}`,
+ );
+ assert_not_equals(node.querySelector("#allowed"), null);
+ }, `${target}.${method}: createParserOptions returning {runScripts: true} enables script execution`);
+ }
+
+ if (target === "Element") {
+ test((t) => {
+ const node = createTarget(target, t);
+ window.did_run = false;
+ t.add_cleanup(() => {
+ window.did_run = false;
+ });
+ createParserOptions = (options) => ({
+ runScripts: false,
+ });
+ run_method(node, "createContextualFragment", "<script>window.did_run = true;<" + "/script>");
+ assert_false(window.did_run);
+ }, `${target}: createContextualFragment with createParserOptions(runScripts=false) does not run scripts`);
+
+ test((t) => {
+ const node = createTarget(target, t);
+ window.did_run = false;
+ t.add_cleanup(() => {
+ window.did_run = false;
+ });
+ createParserOptions = (options) => options;
+ run_method(node, "createContextualFragment", "<script>window.did_run = true;<" + "/script>");
+ assert_true(window.did_run);
+ }, `${target}: createContextualFragment runs scripts by default`);
+ }
+
+ for (const method of [
+ "setHTMLUnsafe",
+ "appendHTMLUnsafe",
+ "prependHTMLUnsafe",
+ "beforeHTMLUnsafe",
+ "afterHTMLUnsafe",
+ "replaceWithHTMLUnsafe",
+ "innerHTML",
+ "outerHTML",
+ "createContextualFragment",
+ "afterbegin",
+ "beforeend",
+ "beforebegin",
+ "afterend",
+ ]) {
+ if (
+ target === "ShadowRoot" &&
+ (method === "outerHTML" ||
+ method === "afterbegin" ||
+ method === "beforeend" ||
+ method === "beforebegin" ||
+ method === "afterend" ||
+ method === "beforeHTMLUnsafe" ||
+ method === "afterHTMLUnsafe" ||
+ method === "replaceWithHTMLUnsafe" ||
+ method === "createContextualFragment")
+ ) {
+ continue;
+ }
+ test((t) => {
+ const node = createTarget(target, t);
+ let createHTMLCalled = false;
+ createParserOptions = (options) => {
+ throw new Error("createParserOptions oops");
+ };
+ createHTML = (html) => {
+ createHTMLCalled = true;
+ return html;
+ };
+ assert_throws_js(Error, () => {
+ run_method(node, method, "test string");
+ });
+ assert_false(createHTMLCalled, "createHTML should not have been called");
+ }, `${target}.${method}: exception in createParserOptions is rethrown and prevents createHTML`);
+ }
+ }
+ </script>
+ </body>
+</html>
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-xml-document-sanitizer.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-xml-document-sanitizer.html
new file mode 100644
index 00000000000..baa24d656af
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-xml-document-sanitizer.html
@@ -0,0 +1,454 @@
+<!doctype html>
+<html>
+ <head>
+ <script src="../resources/testharness.js"></script>
+ <script src="../resources/testharnessreport.js"></script>
+ <meta
+ http-equiv="Content-Security-Policy"
+ content="require-trusted-types-for 'script';"
+ />
+ </head>
+ <body>
+ <script>
+ let createHTML = null;
+ let createParserOptions = null;
+
+ trustedTypes.createPolicy("default", {
+ createHTML: (html, ...args) => (createHTML ? createHTML(html, ...args) : null),
+ createParserOptions: (options, ...args) => (createParserOptions ? createParserOptions(options, ...args) : null),
+ });
+
+ const testPolicy = trustedTypes.createPolicy("test-policy", {
+ createHTML: (html) => html,
+ createParserOptions: (options) => options,
+ });
+
+ function createXmlDoc() {
+ return document.implementation.createDocument("application/xml", "xml");
+ }
+
+ function createXmlElem(doc) {
+ const elem = doc.createElement("div");
+ doc.documentElement.appendChild(elem);
+ return elem;
+ }
+
+ /* -------------------------------------------------------------
+ * Scenario 1: Default policy supplies ONLY createParserOptions
+ * (with a sanitizer), but NO createHTML (createHTML returns null).
+ * In XML documents, get trusted type compliant input falls through
+ * to get trusted type compliant string. Because createHTML is not
+ * defined (or returns null), it triggers the CSP violation check,
+ * throwing TypeError in enforcement mode.
+ * ----------------------------------------------------------- */
+
+ test((t) => {
+ t.add_cleanup(() => {
+ createParserOptions = null;
+ createHTML = null;
+ });
+ let createParserOptionsCalled = false;
+ createParserOptions = (options) => {
+ createParserOptionsCalled = true;
+ return { sanitizer: { removeElements: ["span"] } };
+ };
+ createHTML = null;
+
+ const doc = createXmlDoc();
+ const elem = createXmlElem(doc);
+
+ assert_throws_js(TypeError, () => {
+ elem.innerHTML = "<span></span>";
+ });
+ assert_false(createParserOptionsCalled, "createParserOptions should not be called for XML sink");
+ }, "innerHTML on XML document throws TypeError without calling createParserOptions if default policy provides only a sanitizer without createHTML");
+
+ test((t) => {
+ t.add_cleanup(() => {
+ createParserOptions = null;
+ createHTML = null;
+ });
+ let createParserOptionsCalled = false;
+ createParserOptions = (options) => {
+ createParserOptionsCalled = true;
+ return { sanitizer: { removeElements: ["span"] } };
+ };
+ createHTML = null;
+
+ const doc = createXmlDoc();
+ const elem = createXmlElem(doc);
+
+ assert_throws_js(TypeError, () => {
+ elem.outerHTML = "<span></span>";
+ });
+ assert_false(createParserOptionsCalled, "createParserOptions should not be called for XML sink");
+ }, "outerHTML on XML document throws TypeError without calling createParserOptions if default policy provides only a sanitizer without createHTML");
+
+ test((t) => {
+ t.add_cleanup(() => {
+ createParserOptions = null;
+ createHTML = null;
+ });
+ let createParserOptionsCalled = false;
+ createParserOptions = (options) => {
+ createParserOptionsCalled = true;
+ return { sanitizer: { removeElements: ["span"] } };
+ };
+ createHTML = null;
+
+ const doc = createXmlDoc();
+ const elem = createXmlElem(doc);
+
+ assert_throws_js(TypeError, () => {
+ elem.insertAdjacentHTML("beforeend", "<span></span>");
+ });
+ assert_false(createParserOptionsCalled, "createParserOptions should not be called for XML sink");
+ }, "insertAdjacentHTML on XML document throws TypeError without calling createParserOptions if default policy provides only a sanitizer without createHTML");
+
+ test((t) => {
+ t.add_cleanup(() => {
+ createParserOptions = null;
+ createHTML = null;
+ });
+ let createParserOptionsCalled = false;
+ createParserOptions = (options) => {
+ createParserOptionsCalled = true;
+ return { sanitizer: { removeElements: ["span"] } };
+ };
+ createHTML = null;
+
+ const doc = createXmlDoc();
+ const range = doc.createRange();
+ range.selectNode(doc.documentElement);
+
+ assert_throws_js(TypeError, () => {
+ range.createContextualFragment("<span></span>");
+ });
+ assert_false(createParserOptionsCalled, "createParserOptions should not be called for XML sink");
+ }, "createContextualFragment on XML document throws TypeError without calling createParserOptions if default policy provides only a sanitizer without createHTML");
+
+ test((t) => {
+ t.add_cleanup(() => {
+ createParserOptions = null;
+ createHTML = null;
+ });
+ let createParserOptionsCalled = false;
+ createParserOptions = (options) => {
+ createParserOptionsCalled = true;
+ return { sanitizer: { removeElements: ["span"] } };
+ };
+ createHTML = null;
+
+ const parser = new DOMParser();
+ const doc = parser.parseFromString(testPolicy.createHTML("<xml></xml>"), "application/xml");
+ const elem = createXmlElem(doc);
+
+ assert_throws_js(TypeError, () => {
+ elem.innerHTML = "<span></span>";
+ });
+ assert_false(createParserOptionsCalled, "createParserOptions should not be called for XML sink");
+ }, "innerHTML on XML document created by DOMParser throws TypeError without calling createParserOptions if default policy provides only a sanitizer without createHTML");
+
+ async_test((t) => {
+ t.add_cleanup(() => {
+ createParserOptions = null;
+ createHTML = null;
+ });
+
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", "data:application/xml,<xml></xml>");
+ xhr.onload = t.step_func_done(() => {
+ let createParserOptionsCalled = false;
+ createParserOptions = (options) => {
+ createParserOptionsCalled = true;
+ return { sanitizer: { removeElements: ["span"] } };
+ };
+ createHTML = null;
+
+ const doc = xhr.responseXML;
+ const elem = createXmlElem(doc);
+
+ assert_throws_js(TypeError, () => {
+ elem.innerHTML = "<span></span>";
+ });
+ assert_false(createParserOptionsCalled, "createParserOptions should not be called for XML sink");
+ });
+ xhr.send();
+ }, "innerHTML on XML document from XHR response throws TypeError without calling createParserOptions if default policy provides only a sanitizer without createHTML");
+
+ for (const method of [
+ "setHTMLUnsafe",
+ "appendHTMLUnsafe",
+ "prependHTMLUnsafe",
+ "beforeHTMLUnsafe",
+ "afterHTMLUnsafe",
+ "replaceWithHTMLUnsafe",
+ ]) {
+ test((t) => {
+ t.add_cleanup(() => {
+ createParserOptions = null;
+ createHTML = null;
+ });
+ let createParserOptionsCalled = false;
+ createParserOptions = (options) => {
+ createParserOptionsCalled = true;
+ return { sanitizer: { removeElements: ["span"] } };
+ };
+ createHTML = null;
+
+ const doc = createXmlDoc();
+ const elem = createXmlElem(doc);
+ let receiver = elem;
+ if (["beforeHTMLUnsafe", "afterHTMLUnsafe", "replaceWithHTMLUnsafe"].includes(method)) {
+ const ref = doc.createElement("div");
+ elem.appendChild(ref);
+ receiver = ref;
+ }
+
+ // Unsafe HTML methods parse as HTML, so they use createParserOptions and do NOT throw TypeError
+ receiver[method]("<div id='allowed'><span id='forbidden'></span></div>");
+ assert_true(createParserOptionsCalled, `createParserOptions must be called for ${method} on XML document`);
+ assert_not_equals(elem.querySelector("#allowed"), null);
+ assert_equals(elem.querySelector("#forbidden"), null);
+ }, `${method} on XML document does not throw TypeError and applies createParserOptions sanitizer`);
+
+ test((t) => {
+ t.add_cleanup(() => {
+ createParserOptions = null;
+ createHTML = null;
+ });
+ let createParserOptionsCalled = false;
+ createParserOptions = (options) => {
+ createParserOptionsCalled = true;
+ return {};
+ };
+ createHTML = null;
+
+ const doc = createXmlDoc();
+ const elem = createXmlElem(doc);
+ let receiver = elem;
+ if (["beforeHTMLUnsafe", "afterHTMLUnsafe", "replaceWithHTMLUnsafe"].includes(method)) {
+ const ref = doc.createElement("div");
+ elem.appendChild(ref);
+ receiver = ref;
+ }
+
+ // Unsafe HTML methods parse as HTML, so they use createParserOptions and do NOT throw TypeError even without a sanitizer
+ receiver[method]("<div id='allowed'><span id='allowed-child'></span></div>");
+ assert_true(createParserOptionsCalled, `createParserOptions must be called for ${method} on XML document`);
+ assert_not_equals(elem.querySelector("#allowed"), null);
+ assert_not_equals(elem.querySelector("#allowed-child"), null);
+ }, `${method} on XML document does not throw TypeError when createParserOptions has no sanitizer`);
+ }
+
+ /* -------------------------------------------------------------
+ * Scenario 2: Default policy supplies BOTH createParserOptions
+ * (with a sanitizer) AND createHTML.
+ * In XML documents, the sanitizer cannot be used, but createHTML
+ * executes and transforms the input string without throwing.
+ * ----------------------------------------------------------- */
+
+ test((t) => {
+ t.add_cleanup(() => {
+ createParserOptions = null;
+ createHTML = null;
+ });
+ let createHTMLCalled = false;
+ let createParserOptionsCalled = false;
+ createParserOptions = (options) => {
+ createParserOptionsCalled = true;
+ return { sanitizer: { removeElements: ["span"] } };
+ };
+ createHTML = (html) => {
+ createHTMLCalled = true;
+ return html.replace("cat", "<span id='preserved'>dog</span>");
+ };
+
+ const doc = createXmlDoc();
+ const elem = createXmlElem(doc);
+
+ elem.innerHTML = "<div id='target'>cat</div>";
+ assert_true(createHTMLCalled, "createHTML should have been called for XML sink");
+ assert_false(createParserOptionsCalled, "createParserOptions should not be called for XML sink");
+ assert_not_equals(elem.querySelector("#preserved"), null, "span should not be removed by sanitizer in XML doc");
+ assert_equals(elem.querySelector("#preserved").textContent, "dog");
+ }, "innerHTML on XML document executes createHTML and does not call createParserOptions when default policy provides both");
+
+ test((t) => {
+ t.add_cleanup(() => {
+ createParserOptions = null;
+ createHTML = null;
+ });
+ let createHTMLCalled = false;
+ let createParserOptionsCalled = false;
+ createParserOptions = (options) => {
+ createParserOptionsCalled = true;
+ return { sanitizer: { removeElements: ["span"] } };
+ };
+ createHTML = (html) => {
+ createHTMLCalled = true;
+ return html;
+ };
+
+ const doc = createXmlDoc();
+ const elem = createXmlElem(doc);
+
+ elem.outerHTML = "<span id='xml-span'></span>";
+ assert_true(createHTMLCalled, "createHTML should have been called for XML sink");
+ assert_false(createParserOptionsCalled, "createParserOptions should not be called for XML sink");
+ assert_not_equals(doc.querySelector("#xml-span"), null);
+ }, "outerHTML on XML document executes createHTML and does not call createParserOptions when default policy provides both");
+
+ test((t) => {
+ t.add_cleanup(() => {
+ createParserOptions = null;
+ createHTML = null;
+ });
+ let createHTMLCalled = false;
+ let createParserOptionsCalled = false;
+ createParserOptions = (options) => {
+ createParserOptionsCalled = true;
+ return { sanitizer: { removeElements: ["span"] } };
+ };
+ createHTML = (html) => {
+ createHTMLCalled = true;
+ return html;
+ };
+
+ const doc = createXmlDoc();
+ const elem = createXmlElem(doc);
+
+ elem.insertAdjacentHTML("beforeend", "<span id='xml-span'></span>");
+ assert_true(createHTMLCalled, "createHTML should have been called for XML sink");
+ assert_false(createParserOptionsCalled, "createParserOptions should not be called for XML sink");
+ assert_not_equals(elem.querySelector("#xml-span"), null);
+ }, "insertAdjacentHTML on XML document executes createHTML and does not call createParserOptions when default policy provides both");
+
+ test((t) => {
+ t.add_cleanup(() => {
+ createParserOptions = null;
+ createHTML = null;
+ });
+ let createHTMLCalled = false;
+ let createParserOptionsCalled = false;
+ createParserOptions = (options) => {
+ createParserOptionsCalled = true;
+ return { sanitizer: { removeElements: ["span"] } };
+ };
+ createHTML = (html) => {
+ createHTMLCalled = true;
+ return html;
+ };
+
+ const doc = createXmlDoc();
+ const range = doc.createRange();
+ range.selectNode(doc.documentElement);
+
+ const fragment = range.createContextualFragment("<span id='xml-span'></span>");
+ assert_true(createHTMLCalled, "createHTML should have been called for XML sink");
+ assert_false(createParserOptionsCalled, "createParserOptions should not be called for XML sink");
+ assert_not_equals(fragment.querySelector("#xml-span"), null);
+ }, "createContextualFragment on XML document executes createHTML and does not call createParserOptions when default policy provides both");
+
+ test((t) => {
+ t.add_cleanup(() => {
+ createParserOptions = null;
+ createHTML = null;
+ });
+ let createHTMLCalled = false;
+ let createParserOptionsCalled = false;
+ createParserOptions = (options) => {
+ createParserOptionsCalled = true;
+ return { sanitizer: { removeElements: ["span"] } };
+ };
+ createHTML = (html) => {
+ createHTMLCalled = true;
+ return html;
+ };
+
+ const parser = new DOMParser();
+ const doc = parser.parseFromString(testPolicy.createHTML("<xml></xml>"), "application/xml");
+ const elem = createXmlElem(doc);
+
+ elem.innerHTML = "<span id='xml-span'></span>";
+ assert_true(createHTMLCalled, "createHTML should have been called for XML sink");
+ assert_false(createParserOptionsCalled, "createParserOptions should not be called for XML sink");
+ assert_not_equals(elem.querySelector("#xml-span"), null);
+ }, "innerHTML on XML document created by DOMParser executes createHTML and does not call createParserOptions when default policy provides both");
+
+ async_test((t) => {
+ t.add_cleanup(() => {
+ createParserOptions = null;
+ createHTML = null;
+ });
+
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", "data:application/xml,<xml></xml>");
+ xhr.onload = t.step_func_done(() => {
+ let createHTMLCalled = false;
+ let createParserOptionsCalled = false;
+ createParserOptions = (options) => {
+ createParserOptionsCalled = true;
+ return { sanitizer: { removeElements: ["span"] } };
+ };
+ createHTML = (html) => {
+ createHTMLCalled = true;
+ return html;
+ };
+
+ const doc = xhr.responseXML;
+ const elem = createXmlElem(doc);
+
+ elem.innerHTML = "<span id='xml-span'></span>";
+ assert_true(createHTMLCalled, "createHTML should have been called for XML sink");
+ assert_false(createParserOptionsCalled, "createParserOptions should not be called for XML sink");
+ assert_not_equals(elem.querySelector("#xml-span"), null);
+ });
+ xhr.send();
+ }, "innerHTML on XML document from XHR response executes createHTML and does not call createParserOptions when default policy provides both");
+
+ test((t) => {
+ t.add_cleanup(() => {
+ createParserOptions = null;
+ createHTML = null;
+ });
+ createParserOptions = () => {
+ throw new Error("createParserOptions should not be called on XML document");
+ };
+ createHTML = (html) => html;
+
+ const doc = createXmlDoc();
+ const elem = createXmlElem(doc);
+
+ elem.innerHTML = "<span id='xml-span'></span>";
+ assert_not_equals(elem.querySelector("#xml-span"), null);
+ }, "innerHTML on XML document does not invoke throwing createParserOptions");
+
+ /* -------------------------------------------------------------
+ * Scenario 3: Passing TrustedHTML directly to XML sinks
+ * bypasses default policy and never calls createParserOptions or throws TypeError.
+ * ----------------------------------------------------------- */
+
+ test((t) => {
+ t.add_cleanup(() => {
+ createParserOptions = null;
+ createHTML = null;
+ });
+ let createParserOptionsCalled = false;
+ createParserOptions = (options) => {
+ createParserOptionsCalled = true;
+ return { sanitizer: { removeElements: ["span"] } };
+ };
+ createHTML = null;
+
+ const doc = createXmlDoc();
+ const elem = createXmlElem(doc);
+
+ const trustedHTML = testPolicy.createHTML("<span id='xml-span'></span>");
+ elem.innerHTML = trustedHTML;
+ assert_false(createParserOptionsCalled, "createParserOptions should not be called for XML sink with TrustedHTML");
+ assert_not_equals(elem.querySelector("#xml-span"), null);
+ }, "innerHTML on XML document accepts TrustedHTML without calling createParserOptions or throwing even if createHTML is missing");
+ </script>
+ </body>
+</html>
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-xml-document.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-xml-document.html
new file mode 100644
index 00000000000..41c933d2c23
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtml-xml-document.html
@@ -0,0 +1,53 @@
+<!DOCTYPE html>
+<html>
+<head>
+<title>Test that setHTML parses as HTML even in an XML document</title>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="support/html5lib-testcase-support.js"></script>
+</head>
+<body>
+<script type="html5lib-tests">
+#data
+Hello!
+#document
+| "Hello!"
+
+#data
+<br>
+#document
+| <br>
+
+#data
+<p>Hi</p>
+#document
+| <p>
+| "Hi"
+
+#data
+<iframe></iframe><p>text</p>
+#document
+| <p>
+| "text"
+
+</script>
+<script>
+html5lib_testcases_from_script().forEach((testcase, index) => {
+ test(_ => {
+ const doc = document.implementation.createDocument("application/xml", "xml");
+ const context = doc.documentElement;
+ context.setHTML(testcase.data);
+ assert_testcase(context, testcase);
+ }, `Testcase #${index} with xmlDoc.setHTML("${testcase.data}")`);
+
+ test(_ => {
+ const doc = document.implementation.createDocument("application/xml", "xml");
+ doc.documentElement.appendChild(doc.createElement("div"));
+ context = doc.documentElement.firstElementChild.attachShadow({mode: "open"});
+ context.setHTML(testcase.data);
+ assert_testcase(context, testcase);
+ }, `Testcase #${index}, shadow inside xmlDoc, shadowroot.setHTML("${testcase.data}")`);
+});
+</script>
+</body>
+</html>
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtmlunsafe-toplevel-template-script.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtmlunsafe-toplevel-template-script.html
new file mode 100644
index 00000000000..323ba52d0e5
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtmlunsafe-toplevel-template-script.html
@@ -0,0 +1,57 @@
+<!DOCTYPE html>
+<html>
+<head>
+<meta charset="utf-8">
+<title>Sanitizer: Top-level &lt;template&gt; and &lt;script&gt; parsed through setHTMLUnsafe</title>
+<link rel="help" href="https://github.com/whatwg/html/pull/12756">
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="support/html5lib-testcase-support.js"></script>
+</head>
+<body>
+<script>
+promise_test(async () => {
+ const testcases = await html5lib_testcases_from_response(
+ fetch("sethtmlunsafe-toplevel-template-script.sub.dat"));
+ testcases.forEach((testcase, index) => {
+ test(() => {
+ const context = document.createElement(testcase["document-fragment"] ?? "div");
+ let config = undefined;
+ if (testcase.config) {
+ config = { sanitizer: JSON.parse(testcase.config) };
+ }
+ const method = testcase.method ?? "setHTMLUnsafe";
+ context[method](testcase.data, config);
+ assert_testcase(context, testcase);
+ }, `Testcase #${index} [${testcase.method ?? "setHTMLUnsafe"}], "${testcase.data}", config: "${testcase.config ?? "{}"}"`);
+ });
+}, "Top-level template and script testcases from sub.dat");
+
+test((t) => {
+ window.toplevelScriptRan = false;
+ t.add_cleanup(() => { delete window.toplevelScriptRan; });
+
+ const container = document.createElement("div");
+ container.setHTMLUnsafe("<script>window.toplevelScriptRan = true;<" + "/script>");
+ assert_false(window.toplevelScriptRan, "Script should not execute without runScripts: true");
+ assert_equals(container.children.length, 1, "Script element should be inserted");
+ assert_equals(container.firstElementChild.tagName, "SCRIPT");
+}, "Top-level <script> parsed through setHTMLUnsafe() without runScripts does not execute");
+
+test((t) => {
+ window.toplevelScriptRan = false;
+ t.add_cleanup(() => { delete window.toplevelScriptRan; });
+
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ t.add_cleanup(() => { container.remove(); });
+
+ container.setHTMLUnsafe(
+ "<script>window.toplevelScriptRan = true;<" + "/script>",
+ { runScripts: true }
+ );
+ assert_true(window.toplevelScriptRan, "Script should execute with runScripts: true");
+}, "Top-level <script> parsed through setHTMLUnsafe() with runScripts: true executes");
+</script>
+</body>
+</html>
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtmlunsafe-toplevel-template-script.sub.dat b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtmlunsafe-toplevel-template-script.sub.dat
new file mode 100644
index 00000000000..43b91fe9510
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/sethtmlunsafe-toplevel-template-script.sub.dat
@@ -0,0 +1,66 @@
+#data
+<template><b>Hello</b></template>
+#method
+setHTMLUnsafe
+#document
+| <template>
+| content
+| <b>
+| "Hello"
+
+#data
+<template shadowrootmode="open"><span>Inside</span></template>
+#method
+setHTMLUnsafe
+#document
+| <template>
+| shadowrootmode="open"
+| content
+| <span>
+| "Inside"
+
+#data
+<template><b>Hello</b></template>
+#method
+setHTMLUnsafe
+#config
+{ "replaceWithChildrenElements": ["template"] }
+#document
+
+#data
+<template><b>Hello</b></template>
+#method
+setHTMLUnsafe
+#config
+{ "removeElements": ["template"] }
+#document
+
+#data
+<script>alert(1);</script>
+#method
+setHTMLUnsafe
+#document
+| <script>
+| "alert(1);"
+
+#data
+<script><b>Hello</b></script>
+#method
+setHTMLUnsafe
+#config
+{ "replaceWithChildrenElements": ["script"] }
+#document
+| "<b>Hello</b>"
+
+#data
+<template><p>Text</p><div>More</div></template>
+#method
+setHTMLUnsafe
+#document
+| <template>
+| content
+| <p>
+| "Text"
+| <div>
+| "More"
+
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/support/html5lib-testcase-support.js b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/support/html5lib-testcase-support.js
new file mode 100644
index 00000000000..b198006bd17
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/support/html5lib-testcase-support.js
@@ -0,0 +1,245 @@
+// This library supports HTML5lib-style test cases.
+//
+// The HTMLlib test case format describes an actual DOM tree. For testing, and
+// particular for testing of DOM parsers and DOM parser-related functionality,
+// this has the advantage of being able to represent edge cases.
+//
+// Example: If `.replaceWithChildren` is called on the `<span>` element as a
+// result of parsing `"<p>Hello<span>World</span></p>"`, then this results in
+// a tree with two adjacent text nodes. This behaviour will affect subsequent
+// DOM operations and should thus be tested. The HTML5lib format makes it easy
+// to describe the expected result unambiguously.
+//
+// References:
+// - HTML5lib: https://github.com/html5lib
+// - HTML5lib testcases: https://github.com/html5lib/html5lib-tests/tree/master/tree-construction
+// - test case format description:
+// https://github.com/html5lib/html5lib-tests/blob/master/tree-construction/README.md
+//
+// The main "API" is:
+//
+// - parse_html5lib_testcases(string)
+// This returns an array of dictionaries, where the dictionary contains the
+// the text of the test file, keyed by the lines starting with a hashtag.
+//
+// E.g. #data\nbla results in [{data: "bla"}].
+//
+// - html5lib_testcases_from_script()
+// Wrapper for parse_html5lib_testcases that gets the test data from a script
+// element with type "html5lib-tests". This allows to specify the test data
+// in the test file, but requires working around closing script tags.
+//
+// - html5lib_testcases_from_response(response_promise)
+// Wrapper for parse_html5lib_testcases that gets the data from a Response
+// Promise, as is returned from `fetch()`, and returns a Promise for the array
+// of testcases. This allows getting the test dat from a text resource.
+//
+// - build_node_tree(node, documentstr)
+// This builds a node tree from the "#document" string from a testcase, and
+// appends it to the node argument. Returns node.
+//
+// - assert_subtree_equals(node1, node2)
+// Asserts that the child trees of node1 and node2 are equals. This
+// recursively descends the trees.
+//
+// - assert_testcase(node, testcase)
+// Wrapper for build_node_tree and assert_subtree_equals, for use with a
+// result of parse_html5lib_testcases.
+//
+
+function html5lib_testcases_from_script() {
+ return parse_html5lib_testcases(
+ document.querySelector("script[type='html5lib-tests']").textContent);
+}
+
+function html5lib_testcases_from_response(response_promise) {
+ return response_promise
+ .then(response => response.text())
+ .then(parse_html5lib_testcases);
+}
+
+function add_html5lib_testcase(testcases, current) {
+ for (const item in current) {
+ current[item] = current[item].join("\n");
+ }
+ if (Object.entries(current).length) {
+ testcases.push(current);
+ }
+}
+
+function parse_html5lib_testcases(content) {
+ const testcases = [];
+ var state = undefined;
+ var current = {};
+ for (const line of content.split("\n")) {
+ if (!line) {
+ add_html5lib_testcase(testcases, current);
+ state = undefined;
+ current = {};
+ } else if (line[0] == "#") {
+ state = line.substring(1);
+ current[state] = [];
+ } else if (state) {
+ current[state].push(line);
+ } else {
+ // Error handling is for another day.
+ }
+ }
+ // Flush the last testcase if the content doesn't end with an empty line.
+ add_html5lib_testcase(testcases, current);
+ return testcases;
+}
+
+function get_child_at(node, level) {
+ for (i = 0; i < level; i++) {
+ if (is_html_template(node)) {
+ // For <template>, continue with the content fragment.
+ node = node.content;
+ } else {
+ node = node.lastChild;
+ }
+ }
+ return node;
+}
+
+function append_child_at(node, level, child) {
+ get_child_at(node, level).appendChild(child);
+}
+
+function is_element(node) {
+ return node.tagName && node.namespaceURI;
+}
+
+function is_html_template(node) {
+ return is_element(node) && node.tagName == "TEMPLATE" &&
+ node.namespaceURI == "http://www.w3.org/1999/xhtml";
+}
+
+function create_element(name, maybe_namespace) {
+ // `For the HTML namespace, the namespace designator is the empty string,
+ // i.e. there's no prefix. For the SVG namespace, the namespace designator is
+ // "svg ". For the MathML namespace, the namespace designator is "math ".
+ if (maybe_namespace == "svg ") {
+ return document.createElementNS("http://www.w3.org/2000/svg", name);
+ } else if (maybe_namespace == "math ") {
+ return document.createElementNS("http://www.w3.org/1998/Math/MathML", name);
+ } else if (!maybe_namespace) {
+ return document.createElement(name);
+ } else {
+ assert_unreached(`Invalid element name: "${maybe_namespace}${name}"`);
+ }
+}
+
+function set_attribute(node, name, maybe_namespace, value) {
+ // `The attribute name string is the local name prefixed by a namespace
+ // designator. For no namespace, the namespace designator is the empty string,
+ // i.e. there's no prefix. For the XLink namespace, the namespace designator
+ // is "xlink " [Likewise, "xml " and "xmlns ".]
+ if (maybe_namespace == "xlink ") {
+ node.setAttributeNS("http://www.w3.org/1999/xlink", name, value);
+ } else if (maybe_namespace == "xml ") {
+ node.setAttributeNS("http://www.w3.org/XML/1998/namespace", name, value);
+ } else if (maybe_namespace == "xmlns ") {
+ node.setAttributeNS("http://www.w3.org/2000/xmlns/", name, value);
+ } else if (!maybe_namespace) {
+ node.setAttribute(name, value);
+ } else {
+ assert_unreached(`Invalid attribute name: "${maybe_namespace}${name}"`);
+ }
+}
+
+function build_node_tree(root, docstr) {
+ // Format described here:
+ // https://github.com/html5lib/html5lib-tests/blob/master/tree-construction/README.md
+
+ // Special-case empty string: Don't build anything.
+ // (Happens for test docs that cause parse errors, but also for genuinely
+ // empty expectation documents.)
+ if (!docstr) return root;
+
+ for (const line of docstr.split("\n")) {
+ const [_, indent, remainder] = line.match(/^\| ( *)(.*)/);
+ const level = indent.length / 2;
+ if (match = remainder.match(/^<([a-z]* )?([a-zA-Z0-9_-]*)>$/)) {
+ // `Element nodes must be represented by a "<, the tag name string, ">".`
+ append_child_at(root, level, create_element(match[2], match[1]));
+ } else if (match = remainder.match(/^"([^"]*)"$/)) {
+ // `Text nodes must be the string, in double quotes.`
+ append_child_at(root, level, document.createTextNode(match[1]));
+ } else if (match = remainder.match(/^([a-z]* )?(.*)="(.*)"$/)) {
+ // `Attribute nodes must have the attribute name string, then an "=" sign,
+ // then the attribute value in double quotes (").`
+ set_attribute(get_child_at(root, level), match[2], match[1], match[3]);
+ } else if (match = remainder.match(/^<!--(.*)-->$/)) {
+ // `Comments must be "<" then "!-- " then the data then " -->".`
+ append_child_at(root, level, document.createComment(match[1]));
+ } else if (match = remainder.match(
+ /^<!DOCTYPE ([^ ]*)( "([^"]*)"( "([^"]*)")?)?>$/)) {
+ // `DOCTYPEs must be "<!DOCTYPE " then [... bla bla ...]`
+ append_child_at(root, level,
+ document.implementation.createDocumentType(match[1], match[3], match[5]));
+ } else if (match = remainder.match(/^<\?([a-zA-Z0-9_-]*)(?:\s+(.*?))?\?>$/)) {
+ // `Processing instructions must be "<?", then the target, then [...], ending in "?>"`
+ append_child_at(root, level, document.createProcessingInstruction(
+ match[1], match[2] || ""));
+ } else if (remainder == "content") {
+ // Template contents are represented by the string "content" with the
+ // children below it.
+ // Nothing to do here; so let's just check we're actually in a template.
+ assert_true(is_html_template(get_child_at(root, level)),
+ "\"content\" only expected as child of a <template>.");
+ } else {
+ assert_unreached(
+ `Unknown line type. Maybe test data is malformed. ("${line}")`);
+ }
+ }
+ return root;
+}
+
+function assert_subtree_equals(node1, node2) {
+ // Iterate in parallel over both trees.
+ const tree1 = document.createNodeIterator(node1);
+ const tree2 = document.createNodeIterator(node2);
+ // Skip the root/context node, so that we can re-use the test with different
+ // context types.
+ var current1 = tree1.nextNode();
+ var current2 = tree2.nextNode();
+ do {
+ current1 = tree1.nextNode();
+ current2 = tree2.nextNode();
+
+ if (!current1) break;
+
+ // Conceptually, we only want to check whether a.isEqualNode(b). But that
+ // yields terrible error messages ("expected true but got false"). With
+ // this being a test suite and all, let's invest a bit of effort into nice
+ // error messages.
+ if (!current1.isEqualNode(current2)) {
+ let breadcrumbs = "";
+ let current = current1;
+ while (current) {
+ const here = is_element(current) ? `<${current.tagName}>` : `${current}`;
+ breadcrumbs = `${here} / ${breadcrumbs}`;
+ current = current.parentNode;
+ }
+ breadcrumbs = breadcrumbs.substring(0, breadcrumbs.length - 3);
+ assert_true(current1.isEqualNode(current2),
+ `${current1}.isEqual(${current2}) fails. Path: ${breadcrumbs}.`);
+ }
+
+ // NodeIterator does not recurse into template contents. So we need to do
+ // this manually.
+ if (is_html_template(current1) && is_html_template(current2)) {
+ assert_subtree_equals(current1.content, current2.content);
+ }
+ } while (current1);
+
+ // Ensure that both iterators have come to an end.
+ assert_false(!!current2, "Additional nodes at the of node2.\n");
+}
+
+function assert_testcase(node, testcase) {
+ const context = document.createElement(testcase["document-fragment"] ?? "div");
+ const tree = build_node_tree(context, testcase.document);
+ assert_subtree_equals(node, tree);
+}
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/support/trustedhtml-parser-options.js b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/support/trustedhtml-parser-options.js
new file mode 100644
index 00000000000..16dbade1f17
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/support/trustedhtml-parser-options.js
@@ -0,0 +1,107 @@
+const markup = "<div id=wrapper><span id=inner></span></div>";
+const scriptMarkup = "<script>window.scriptRan = true;<" + "/script>";
+
+const NO_OPTIONS = Symbol("no options");
+
+const sinks = [
+ ...["setHTMLUnsafe", "appendHTMLUnsafe", "prependHTMLUnsafe"].map(method => ({
+ name: `Element.${method}`,
+ sample: `Element ${method}`,
+ hasRunScripts: true,
+ createTarget(t) {
+ const element = document.createElement("div");
+ document.body.append(element);
+ t.add_cleanup(() => element.remove());
+ return element;
+ },
+ parse(target, html, options) {
+ if (options === NO_OPTIONS) {
+ target[method](html);
+ } else {
+ target[method](html, options);
+ }
+ return target;
+ },
+ })),
+ ...["setHTMLUnsafe", "appendHTMLUnsafe", "prependHTMLUnsafe"].map(method => ({
+ name: `ShadowRoot.${method}`,
+ sample: `ShadowRoot ${method}`,
+ hasRunScripts: true,
+ createTarget(t) {
+ const host = document.createElement("div");
+ document.body.append(host);
+ t.add_cleanup(() => host.remove());
+ return host.attachShadow({ mode: "open" });
+ },
+ parse(target, html, options) {
+ if (options === NO_OPTIONS) {
+ target[method](html);
+ } else {
+ target[method](html, options);
+ }
+ return target;
+ },
+ })),
+ ...["beforeHTMLUnsafe", "afterHTMLUnsafe", "replaceWithHTMLUnsafe"].map(method => ({
+ name: `Node.${method}`,
+ sample: `Node ${method}`,
+ hasRunScripts: true,
+ createTarget(t) {
+ const parent = document.createElement("div");
+ const target = document.createElement("div");
+ parent.append(target);
+ document.body.append(parent);
+ t.add_cleanup(() => parent.remove());
+ return target;
+ },
+ parse(target, html, options) {
+ const parent = target.parentNode;
+ if (options === NO_OPTIONS) {
+ target[method](html);
+ } else {
+ target[method](html, options);
+ }
+ return parent;
+ },
+ })),
+ {
+ name: "Document.parseHTMLUnsafe",
+ sample: "Document parseHTMLUnsafe",
+ hasRunScripts: false,
+ createTarget(t) {
+ return null;
+ },
+ parse(target, html, options) {
+ if (options === NO_OPTIONS) {
+ return Document.parseHTMLUnsafe(html);
+ }
+ return Document.parseHTMLUnsafe(html, options);
+ },
+ },
+];
+
+// Options that need vetting by a default policy's createParserOptions.
+const unvettedSanitizerOptions = [
+ ["a sanitizer config", () => ({ sanitizer: { replaceWithChildrenElements: ["div"] } })],
+ ["a sanitizer config without effect", () => ({ sanitizer: { removeElements: [] } })],
+ ["a Sanitizer", () => ({ sanitizer: new Sanitizer({}) })],
+ ['the "default" sanitizer preset', () => ({ sanitizer: "default" })],
+ ["a sanitizer config and runScripts false", () => ({ sanitizer: { removeElements: ["span"] }, runScripts: false })],
+];
+const unvettedRunScriptsOptions = [
+ ["runScripts true", () => ({ runScripts: true })],
+ ["runScripts true and an empty sanitizer config", () => ({ sanitizer: {}, runScripts: true })],
+];
+
+// Options that don't need vetting.
+const vettingFreeOptions = [
+ ["no options", () => NO_OPTIONS],
+ ["an empty dictionary", () => ({})],
+ ["an empty sanitizer config", () => ({ sanitizer: {} })],
+ ["runScripts false", () => ({ runScripts: false })],
+];
+
+function resetScriptRan(t) {
+ window.scriptRan = false;
+ t.add_cleanup(() => { delete window.scriptRan; });
+}
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/support/util.js b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/support/util.js
new file mode 100644
index 00000000000..20323e0241a
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/support/util.js
@@ -0,0 +1,412 @@
+const XHTML_NS = "http://www.w3.org/1999/xhtml";
+
+// https://wicg.github.io/sanitizer-api/#built-in-non-replaceable-elements-list
+const NON_REPLACEABLE_ELEMENTS = [
+ "html", // Cover both spellings
+ { name: "html", namespace: XHTML_NS },
+ { name: "svg", namespace: "http://www.w3.org/2000/svg" },
+ { name: "math", namespace: "http://www.w3.org/1998/Math/MathML" },
+];
+
+function is_same_sanitizer_name(a, b) {
+ return a.name === b.name && a.namespace === b.namespace;
+}
+
+function is_same_sanitizer_target(a, b) {
+ return a.target === b.target;
+}
+
+function is_data_attribute(attribute) {
+ return attribute.name.startsWith("data-") && attribute.namespace === null;
+}
+
+function has_duplicates(list) {
+ if (!list) {
+ return false;
+ }
+
+ for (let i = 0; i < list.length; i++) {
+ for (let j = i + 1; j < list.length; j++) {
+ if (is_same_sanitizer_name(list[i], list[j])) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+}
+
+function has_duplicate_targets(list) {
+ if (!list) {
+ return false;
+ }
+
+ for (let i = 0; i < list.length; i++) {
+ for (let j = i + 1; j < list.length; j++) {
+ if (is_same_sanitizer_target(list[i], list[j])) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+}
+
+function has_intersection(list1, list2) {
+ if (!list1 || !list2) {
+ return false;
+ }
+
+ for (let item1 of list1) {
+ for (let item2 of list2) {
+ if (is_same_sanitizer_name(item1, item2)) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+}
+
+function is_subset(subset, superset) {
+ if (!subset) {
+ return true;
+ }
+
+ for (let item of subset) {
+ if (!superset.some(superItem => is_same_sanitizer_name(item, superItem))) {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+// https://wicg.github.io/sanitizer-api/#sanitizerconfig-valid
+function assert_config_is_valid(config) {
+ // 1. Assert: config["elements"] exists or config["removeElements"] exists.
+ assert_true(
+ "elements" in config || "removeElements" in config,
+ 'Assert: config["elements"] exists or config["removeElements"] exists.',
+ );
+
+ // 2. If config["elements"] exists and config["removeElements"] exists, then return false.
+ assert_false(
+ "elements" in config && "removeElements" in config,
+ 'If config["elements"] exists and config["removeElements"] exists, then return false.',
+ );
+
+ // 3. Assert: Either config["processingInstructions"] exists or config["removeProcessingInstructions"] exists.
+ assert_true(
+ "processingInstructions" in config || "removeProcessingInstructions" in config,
+ 'Assert: Either config["processingInstructions"] exists or config["removeProcessingInstructions"] exists.',
+ );
+
+ // 4. If config["processingInstructions"] exists and config["removeProcessingInstructions"] exists, then return false.
+ assert_false(
+ "processingInstructions" in config && "removeProcessingInstructions" in config,
+ 'If config["processingInstructions"] exists and config["removeProcessingInstructions"] exists, then return false.',
+ );
+
+ // 5. Assert: Either config["attributes"] exists or config["removeAttributes"] exists.
+ assert_true(
+ "attributes" in config || "removeAttributes" in config,
+ 'Assert: Either config["attributes"] exists or config["removeAttributes"] exists.',
+ );
+
+ // 6. If config["attributes"] exists and config["removeAttributes"] exists, then return false.
+ assert_false(
+ "attributes" in config && "removeAttributes" in config,
+ 'If config["attributes"] exists and config["removeAttributes"] exists, then return false.',
+ );
+
+ // 7. Assert: All SanitizerElementNamespaceWithAttributes, SanitizerElementNamespace, SanitizerProcessingInstruction, and SanitizerAttributeNamespace items in config are canonical, meaning they have been run through canonicalize a sanitizer element, canonicalize a sanitizer processing instruction, or canonicalize a sanitizer attribute, as appropriate.
+
+ // 8. If config["elements"] exists:
+ if ("elements" in config) {
+ // 8.1. If config["elements"] has duplicates, then return false.
+ assert_false(has_duplicates(config.elements), 'If config["elements"] has duplicates, then return false.');
+ } else {
+ // 9. Otherwise:
+ // 9.1. If config["removeElements"] has duplicates, then return false.
+ assert_false(has_duplicates(config.removeElements), 'If config["removeElements"] has duplicates, then return false.');
+ }
+
+ // 10. If config["replaceWithChildrenElements"] exists and has duplicates, then return false.
+ if (config.replaceWithChildrenElements) {
+ assert_false(has_duplicates(config.replaceWithChildrenElements), 'If config["replaceWithChildrenElements"] exists and has duplicates, then return false.');
+ }
+
+ // 11. If config["processingInstructions"] exists:
+ if ("processingInstructions" in config) {
+ // 11.1. If config["processingInstructions"] has duplicate targets, then return false.
+ assert_false(has_duplicate_targets(config.processingInstructions), 'If config["processingInstructions"] has duplicate targets, then return false.')
+ } else {
+ // 12. Otherwise:
+ // 12.1. If config["removeProcessingInstructions"] has duplicate targets, then return false.
+ assert_false(has_duplicate_targets(config.removeProcessingInstructions), 'If config["removeProcessingInstructions"] has duplicate targets, then return false.')
+ }
+
+ // 13. If config["attributes"] exists:
+ if ("attributes" in config) {
+ // 13.1. If config["attributes"] has duplicates, then return false.
+ assert_false(has_duplicates(config.attributes), 'If config["attributes"] has duplicates, then return false.');
+ } else {
+ // 14. Otherwise:
+ // 14.1. If config["removeAttributes"] has duplicates, then return false.
+ assert_false(has_duplicates(config.removeAttributes), 'If config["removeAttributes"] has duplicates, then return false.');
+ }
+
+ // 15. If config["replaceWithChildrenElements"] exists:
+ if (config.replaceWithChildrenElements) {
+ // 15.1. If config["elements"] exists:
+ if (config.elements) {
+ // 15.1.1. If the intersection of config["elements"] and config["replaceWithChildrenElements"] is not empty, then return false.
+ assert_false(
+ has_intersection(config.elements, config.replaceWithChildrenElements),
+ 'If the intersection of config["elements"] and config["replaceWithChildrenElements"] is not empty, then return false.',
+ );
+ } else {
+ // 15.2. Otherwise:
+ // 15.2.1. If the intersection of config["removeElements"] and config["replaceWithChildrenElements"] is not empty, then return false.
+ assert_false(
+ has_intersection(config.removeElements, config.replaceWithChildrenElements),
+ 'If the intersection of config["removeElements"] and config["replaceWithChildrenElements"] is not empty, then return false.',
+ );
+ }
+ }
+
+ // 16. If config["attributes"] exists:
+ if (config.attributes) {
+ // 16.1. Assert: config["dataAttributes"] exists.
+ assert_true("dataAttributes" in config, 'Assert: config["dataAttributes"] exists.');
+
+ // 16.2. If config["elements"] exists:
+ if (config.elements) {
+ // 16.2.1. For each element of config["elements"]:
+ for (let element of config.elements) {
+ // 16.2.1.1. If element["attributes"] exists and element["attributes"] has duplicates, then return false.
+ if (element.attributes) {
+ assert_false(has_duplicates(element.attributes),
+ `If element["attributes"] exists and element["attributes"] has duplicates, then return false. (element: ${element.name})`);
+ }
+
+ // 16.2.1.2. If element["removeAttributes"] exists and element["removeAttributes"] has duplicates, then return false.
+ if (element.removeAttributes) {
+ assert_false(has_duplicates(element.removeAttributes),
+ `If element["removeAttributes"] exists and element["removeAttributes"] has duplicates, then return false. (element: ${element.name})`);
+ }
+
+ // 16.2.1.3. If the intersection of config["attributes"] and element["attributes"] with default « » is not empty, then return false.
+ assert_false(has_intersection(config.attributes, element.attributes),
+ `If the intersection of config["attributes"] and element["attributes"] with default « » is not empty, then return false. (element: ${element.name})`);
+
+ // 16.2.1.4. If element["removeAttributes"] with default « » is not a subset of config["attributes"], then return false.
+ assert_true(is_subset(element.removeAttributes, config.attributes),
+ `If element["removeAttributes"] with default « » is not a subset of config["attributes"], then return false. (element: ${element.name})`);
+
+ // 16.2.1.5. If config["dataAttributes"] is true and element["attributes"] contains a custom data attribute, then return false.
+ if (config.dataAttributes && element.attributes) {
+ for (let attr of element.attributes) {
+ assert_false(is_data_attribute(attr),
+ `If config["dataAttributes"] is true and element["attributes"] contains a custom data attribute, then return false. (element: ${element.name}, attribute: ${attr.name})`);
+ }
+ }
+ }
+ }
+
+ // 16.3. If config["dataAttributes"] is true and config["attributes"] contains a custom data attribute, then return false.
+ if (config.dataAttributes) {
+ for (let attr of config.attributes) {
+ assert_false(is_data_attribute(attr),
+ `If config["dataAttributes"] is true and config["attributes"] contains a custom data attribute, then return false. (attribute: ${attr.name})`);
+ }
+ }
+ } else {
+ // 17. Otherwise:
+ // 17.1. If config["elements"] exists:
+ if (config.elements) {
+ // 17.1.1. For each element of config["elements"]:
+ for (let element of config.elements) {
+ // 17.1.1.1. If element["attributes"] exists and element["removeAttributes"] exists, then return false.
+ assert_false("attributes" in element && "removeAttributes" in element,
+ `If element["attributes"] exists and element["removeAttributes"] exists, then return false. (element: ${element.name})`);
+
+ // 17.1.1.2. If element["attributes"] exist and element["attributes"] has duplicates, then return false.
+ if (element.attributes) {
+ assert_false(has_duplicates(element.attributes),
+ `If element["attributes"] exist and element["attributes"] has duplicates, then return false. (element: ${element.name})`);
+ }
+
+ // 17.1.1.3. If element["removeAttributes"] exist and element["removeAttributes"] has duplicates, then return false.
+ if (element.removeAttributes) {
+ assert_false(has_duplicates(element.removeAttributes),
+ `If element["removeAttributes"] exist and element["removeAttributes"] has duplicates, then return false. (element: ${element.name})`);
+ }
+
+ // 17.1.1.4. If the intersection of config["removeAttributes"] and element["attributes"] with default « » is not empty, then return false.
+ if (element.attributes) {
+ assert_false(has_intersection(config.removeAttributes, element.attributes),
+ `If the intersection of config["removeAttributes"] and element["attributes"] with default « » is not empty, then return false. (element: ${element.name})`);
+ }
+
+ // 17.1.1.5. If the intersection of config["removeAttributes"] and element["removeAttributes"] with default « » is not empty, then return false.
+ if (element.removeAttributes) {
+ assert_false(has_intersection(config.removeAttributes, element.removeAttributes),
+ `If the intersection of config["removeAttributes"] and element["removeAttributes"] with default « » is not empty, then return false. (element: ${element.name})`);
+ }
+ }
+ }
+
+ // 17.2. If config["dataAttributes"] exists, then return false.
+ assert_false("dataAttributes" in config, 'If config["dataAttributes"] exists, then return false.');
+ }
+
+ // 18. Return true.
+}
+
+function assert_config(config, expected) {
+ const PROPERTIES = [
+ "attributes",
+ "removeAttributes",
+ "processingInstructions",
+ "removeProcessingInstructions",
+ "elements",
+ "removeElements",
+ "replaceWithChildrenElements",
+ "comments",
+ "dataAttributes",
+ "javascriptURLs",
+ ];
+
+ // Prevent some typos in the expected config.
+ for (let key of Object.keys(expected)) {
+ assert_in_array(key, PROPERTIES, "expected");
+ }
+ for (let key of Object.keys(config)) {
+ assert_in_array(key, PROPERTIES, "config");
+ }
+
+ assert_config_is_valid(config);
+
+ function assert_attrs(key, config, expected, prefix = "config") {
+ // XXX we allow specifying only a subset for expected.
+ if (!(key in expected)) {
+ return;
+ }
+
+ if (expected[key] === undefined) {
+ assert_false(key in config, `Unexpected '${key}' in ${prefix}`);
+ return;
+ }
+
+ assert_true(key in config, `Missing '${key}' from ${prefix}`);
+ assert_equals(config[key]?.length, expected[key].length, `${prefix}.${key}.length`);
+ for (let i = 0; i < expected[key].length; i++) {
+ let attribute = expected[key][i];
+ if (typeof attribute === "string") {
+ assert_object_equals(
+ config[key][i],
+ { name: attribute, namespace: null },
+ `${prefix}.${key}[${i}] should match`,
+ );
+ } else {
+ assert_object_equals(
+ config[key][i],
+ attribute,
+ `${prefix}.${key}[${i}] should match`,
+ );
+ }
+ }
+ }
+
+ assert_attrs("attributes", config, expected);
+ assert_attrs("removeAttributes", config, expected);
+
+ function assert_pis(key, config, expected, prefix = "config") {
+ if (!(key in expected)) {
+ return;
+ }
+
+ if (expected[key] === undefined) {
+ assert_false(key in config, `Unexpected '${key}' in ${prefix}`);
+ return;
+ }
+
+ assert_true(key in config, `Missing '${key}' from ${prefix}`);
+ assert_equals(config[key]?.length, expected[key].length, `${prefix}.${key}.length`);
+ for (let i = 0; i < expected[key].length; i++) {
+ let processingInstructions = expected[key][i];
+ if (typeof processingInstructions === "string") {
+ assert_object_equals(
+ config[key][i],
+ { target: processingInstructions },
+ `${prefix}.${key}[${i}] should match`,
+ );
+ } else {
+ assert_object_equals(
+ config[key][i],
+ processingInstructions,
+ `${prefix}.${key}[${i}] should match`,
+ );
+ }
+ }
+ }
+
+ assert_pis("processingInstructions", config, expected);
+ assert_pis("removeProcessingInstructions", config, expected);
+
+ function assert_elems(key) {
+ if (!(key in expected)) {
+ return;
+ }
+
+ if (expected[key] === undefined) {
+ assert_false(key in config, `Unexpected '${key}' in config`);
+ return;
+ }
+
+ assert_true(key in config, `Missing '${key}' from config`);
+ assert_equals(config[key]?.length, expected[key].length, `${key}.length`);
+
+ for (let i = 0; i < expected[key].length; i++) {
+ let element = expected[key][i];
+ // To make writing tests a bit easier we also support the shorthand string syntax.
+ if (typeof element === "string") {
+ let extra = key === "elements" ? { removeAttributes: [] } : { };
+ assert_object_equals(
+ config[key][i],
+ { name: element, namespace: XHTML_NS, ...extra },
+ `${key}[${i}] should match`,
+ );
+ } else {
+ if (key === "elements") {
+ assert_equals(config[key][i].name, element.name, `${key}[${i}].name should match`);
+ let ns = "namespace" in element ? element.namespace : XHTML_NS;
+ assert_equals(config[key][i].namespace, ns, `${key}[${i}].namespace should match`);
+
+ assert_attrs("attributes", config[key][i], element, `config.elements[${i}]`);
+ assert_attrs("removeAttributes", config[key][i], element, `config.elements[${i}]`);
+ } else {
+ assert_object_equals(config[key][i], element, `${key}[${i}] should match`);
+ }
+ }
+ }
+ }
+
+ assert_elems("elements");
+ assert_elems("removeElements");
+ assert_elems("replaceWithChildrenElements");
+
+ if ("comments" in expected) {
+ assert_equals(config.comments, expected.comments, "comments should match");
+ }
+
+ if ("dataAttributes" in expected) {
+ assert_equals(config.dataAttributes, expected.dataAttributes, "dataAttributes should match");
+ }
+
+ if ("javascriptURLs" in expected) {
+ assert_equals(config.javascriptURLs, expected.javascriptURLs, "javascriptURLs should match");
+ }
+}
diff --git a/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/trustedhtml-unvetted-parser-options-no-enforcement.html b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/trustedhtml-unvetted-parser-options-no-enforcement.html
new file mode 100644
index 00000000000..57acdb0c0d9
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/sanitizer-api/trustedhtml-unvetted-parser-options-no-enforcement.html
@@ -0,0 +1,32 @@
+<!doctype html>
+<meta charset="utf-8">
+<title>TrustedHTML with parser options that would need vetting, without Trusted Types enforcement</title>
+<link rel="help" href="https://w3c.github.io/trusted-types/dist/spec/#get-trusted-type-compliant-parser-options-algorithm">
+<link rel="help" href="https://github.com/w3c/trusted-types/issues/615">
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="support/trustedhtml-parser-options.js"></script>
+<body>
+<script>
+ const policy = trustedTypes.createPolicy("policy", { createHTML: s => s });
+
+ for (const sink of sinks) {
+ for (const [inputLabel, getInput] of [["TrustedHTML", () => policy.createHTML(markup)], ["string", () => markup]]) {
+ test(t => {
+ const target = sink.createTarget(t);
+ const root = sink.parse(target, getInput(), { sanitizer: { replaceWithChildrenElements: ["div"] } });
+ assert_equals(root.querySelector("#wrapper"), null, "sanitizer was applied");
+ assert_not_equals(root.querySelector("#inner"), null);
+ }, `${sink.name}: ${inputLabel} with a sanitizer config is allowed`);
+ }
+
+ if (sink.hasRunScripts) {
+ test(t => {
+ resetScriptRan(t);
+ const target = sink.createTarget(t);
+ sink.parse(target, policy.createHTML(scriptMarkup), { runScripts: true });
+ assert_true(window.scriptRan, "script ran");
+ }, `${sink.name}: TrustedHTML with runScripts true is allowed`);
+ }
+ }
+</script>