Skip to content

Commit fe9e910

Browse files
voidstackloopclaude
andcommitted
Find and check forms rendered inside an open shadow root
The last real, previously-documented-as-out-of-scope gap: a form built with web components (a genuinely common pattern in modern government design systems) renders its <form> and fields inside an open shadow root, which plain document.querySelectorAll/querySelector can never see into — it only ever searches light-DOM descendants. Every check reported "No <form> element found", indistinguishable from the page genuinely having no form at all. Added a deep-query JS helper (DEEP_QUERY_JS) that recursively walks both light-DOM children and open shadowRoot children, and applied it everywhere a check queries from `document` or the resolved target form: TARGET_FORM_JS's own form discovery and candidate ranking, fill_form_fields, visible_buttons_js, check_mobile_usability's tap-target scan, check_validation_errors' required/invalid lookups, check_required_documents' and check_autofill_hints' file-input/label lookups, and check_input_persistence's field lookup. check_accessibility needed no change — axe-core already pierces shadow DOM natively. Found a second, independent bug while verifying the fix end-to-end against a real shadow-DOM fixture: TARGET_FORM_JS caches the picked form on `window` and, on every later call, re-checks it's still on the page via `document.contains(...)` before reusing it — but `document.contains()` is defined in terms of ordinary (non-shadow- including) descendants, so it's false for a shadow-rooted form even while the form is very much still there. This silently broke every check after the very first `page.evaluate()` call on such a page (the form would resolve once, then "vanish" on every subsequent lookup). Verified this empirically against the real fixture (not just reasoned about) before fixing it: confirmed `document.contains()` returns false while the shadow-rooted form's own `isConnected` correctly returns true, then switched the cache-reuse check to `isConnected`, which is shadow-aware by spec. Both fixes were verified independently by reverting each one in turn (via `git stash`, and via a one-line edit) and confirming the same fixture reproduces the exact predicted failure each time, before restoring. Updated README's "known limitations" section: narrowed from "Shadow DOM or iframe content is invisible" to the two limits that are actually permanent (closed shadow roots, cross-origin iframes — real platform boundaries, not formwatch gaps) now that open shadow roots work. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
1 parent 66a9793 commit fe9e910

5 files changed

Lines changed: 160 additions & 30 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,13 @@ the bug, not just reasoned about:
8282
its own private temp directory and atomically renames it into place;
8383
whichever caller loses that race discards its own copy instead of
8484
colliding with the winner's.
85+
- A form (or field, or label) rendered inside an *open* shadow root —
86+
common in modern government-site design systems built on web
87+
components — was completely invisible to every check, which reported
88+
"No `<form>` element found" as if the page had no form at all. Every
89+
selector-based lookup now pierces open shadow roots. Closed shadow
90+
roots and cross-origin `<iframe>`s remain genuinely out of reach (real
91+
platform limits, not gaps), and are documented as such.
8592

8693
### Changed
8794

‎README.md‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -147,9 +147,12 @@ not deployed.
147147
controls are labeled in some other language won't be walked past the
148148
first step — it'll report "found no Next/Continue or submit button"
149149
even though the form works fine for a real user in that language.
150-
- Every check operates on regular DOM (`document.querySelectorAll`).
151-
Content inside a Shadow DOM or an `<iframe>` is invisible — a form
152-
built with web components will report "No `<form>` element found"
153-
rather than a real result. This shows up as a loud, unambiguous
154-
failure rather than a misleading pass, but it's still a coverage gap
155-
worth knowing about for component-library-based sites.
150+
- A form rendered inside an *open* shadow root (common in modern
151+
government-site design systems built on web components) is found and
152+
checked normally — every selector-based lookup pierces open shadow
153+
roots. A *closed* shadow root remains genuinely invisible (that's the
154+
platform's own encapsulation working as designed, not a formwatch
155+
gap — a closed root can't be inspected from outside by any tool), and
156+
a cross-origin `<iframe>` remains out of reach (a separate browsing
157+
context this page's JS has no access to at all). Both show up as a
158+
loud "No `<form>` element found" rather than a misleading pass.

‎fixtures/shadow-dom-form.html‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head><meta charset="utf-8"><title>Shadow DOM Form</title></head>
4+
<body>
5+
<!-- The actual form lives inside an OPEN shadow root on a custom
6+
element, the way many modern government-site design systems render
7+
forms — plain document.querySelectorAll('form') can't see into it
8+
at all; this is the real case formwatch's deep-query fix targets. -->
9+
<div id="host"></div>
10+
<script>
11+
const host = document.getElementById('host');
12+
const shadow = host.attachShadow({ mode: 'open' });
13+
shadow.innerHTML = `
14+
<form>
15+
<label for="fullname">Full name</label>
16+
<input id="fullname" name="fullname" type="text" required>
17+
18+
<label for="id-scan">Upload a scan of your ID (PDF, max 5MB)</label>
19+
<input type="file" id="id-scan" name="idfile">
20+
21+
<button type="submit" style="width:20px;height:20px;font-size:8px;">Go</button>
22+
</form>
23+
`;
24+
shadow.querySelector('form').addEventListener('submit', (e) => {
25+
e.preventDefault();
26+
shadow.innerHTML += '<p>Thank you, your application was received.</p>';
27+
});
28+
</script>
29+
</body>
30+
</html>

‎src/checks.rs‎

Lines changed: 75 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,31 @@ impl std::fmt::Display for Status {
7676
}
7777
}
7878

79+
/// Recursively finds every element under `root` matching `sel`, descending
80+
/// into *open* shadow roots as well as regular light-DOM children — plain
81+
/// `querySelectorAll` only ever sees the latter, since a shadow root is by
82+
/// design invisible to selectors run from outside it. A form (or a field,
83+
/// or a label) rendered inside a web component's shadow DOM — common in
84+
/// modern government-site design systems — was previously indistinguishable
85+
/// from a form that plain didn't exist: every check saw an empty page.
86+
///
87+
/// This can't and doesn't reach into a *closed* shadow root (the platform's
88+
/// own encapsulation, deliberately impossible to inspect from outside) or
89+
/// across into a cross-origin `<iframe>` (a separate browsing context this
90+
/// page's JS has no access to at all) — both are real, permanent limits,
91+
/// not bugs, and are called out in the README rather than silently
92+
/// mishandled.
93+
const DEEP_QUERY_JS: &str = "(root, sel) => {
94+
const out = [];
95+
const visit = (node) => {
96+
if (node.matches && node.matches(sel)) out.push(node);
97+
if (node.shadowRoot) for (const c of node.shadowRoot.children) visit(c);
98+
for (const c of node.children) visit(c);
99+
};
100+
visit(root);
101+
return out;
102+
}";
103+
79104
/// Resolves to "the form under test": the `<form>` with the most input/
80105
/// select/textarea descendants, not just the first one in document order.
81106
/// A real page often has an incidental header/footer search box as its
@@ -85,13 +110,35 @@ impl std::fmt::Display for Status {
85110
/// session and cached on `window` so every check agrees on the same
86111
/// form, and so "the form disappeared" means specifically this form is
87112
/// gone, not merely that some other form on the page still exists.
113+
///
114+
/// Searches with a self-contained copy of [`DEEP_QUERY_JS`]'s logic (not a
115+
/// spliced-in reference to it — this string is used verbatim by callers
116+
/// that also need to embed `DEEP_QUERY_JS` itself alongside it, and Rust's
117+
/// `format!` can't nest one captured `const` inside another) so a form
118+
/// living inside a web component's open shadow root is found at all.
88119
const TARGET_FORM_JS: &str = "(() => {
89120
if (window.__formwatchFormPicked) {
90-
return document.contains(window.__formwatchForm) ? window.__formwatchForm : null;
121+
// Not document.contains(): that's defined in terms of ordinary
122+
// (non-shadow-including) descendants, so it's false for a form
123+
// living inside an open shadow root even while the form is very
124+
// much still on the page — isConnected is the one DOM primitive
125+
// that's actually shadow-aware, walking the shadow-including root
126+
// chain up to the document.
127+
return window.__formwatchForm?.isConnected ? window.__formwatchForm : null;
91128
}
92129
window.__formwatchFormPicked = true;
93-
const forms = Array.from(document.querySelectorAll('form'));
94-
forms.sort((a, b) => b.querySelectorAll('input, select, textarea').length - a.querySelectorAll('input, select, textarea').length);
130+
const deepQueryAll = (root, sel) => {
131+
const out = [];
132+
const visit = (node) => {
133+
if (node.matches && node.matches(sel)) out.push(node);
134+
if (node.shadowRoot) for (const c of node.shadowRoot.children) visit(c);
135+
for (const c of node.children) visit(c);
136+
};
137+
visit(root);
138+
return out;
139+
};
140+
const forms = deepQueryAll(document, 'form');
141+
forms.sort((a, b) => deepQueryAll(b, 'input, select, textarea').length - deepQueryAll(a, 'input, select, textarea').length);
95142
window.__formwatchForm = forms[0] ?? null;
96143
return window.__formwatchForm;
97144
})()";
@@ -104,7 +151,7 @@ async fn fill_form_fields(page: &Page) -> Result<usize> {
104151
.evaluate(format!(
105152
r#"(() => {{
106153
const form = {TARGET_FORM_JS};
107-
const fields = form ? form.querySelectorAll('input, textarea, select') : [];
154+
const fields = form ? ({DEEP_QUERY_JS})(form, 'input, textarea, select') : [];
108155
let count = 0;
109156
for (const el of fields) {{
110157
if (el.disabled || el.type === 'hidden' || el.type === 'submit' || el.type === 'button' || el.type === 'file') continue;
@@ -189,7 +236,7 @@ async fn wait_for_text_change(page: &Page, before: &str, max_wait: Duration) ->
189236
/// could get misclassified as this form's Next/submit control.
190237
fn visible_buttons_js() -> String {
191238
format!(
192-
"(() => {{ const f = {TARGET_FORM_JS}; return f ? Array.from(f.querySelectorAll('button, input[type=submit], input[type=button]')).filter(b => b.offsetParent !== null) : []; }})()"
239+
"(() => {{ const f = {TARGET_FORM_JS}; return f ? ({DEEP_QUERY_JS})(f, 'button, input[type=submit], input[type=button]').filter(b => b.offsetParent !== null) : []; }})()"
193240
)
194241
}
195242

@@ -489,18 +536,18 @@ pub async fn check_mobile_usability(page: &Page) -> Result<CheckResult> {
489536
.into_value()?;
490537

491538
let small_targets: i64 = page
492-
.evaluate(
493-
r#"(() => {
494-
const els = document.querySelectorAll('a, button, input, select, textarea');
539+
.evaluate(format!(
540+
r#"(() => {{
541+
const els = ({DEEP_QUERY_JS})(document, 'a, button, input, select, textarea');
495542
let small = 0;
496-
for (const el of els) {
543+
for (const el of els) {{
497544
const r = el.getBoundingClientRect();
498545
if (r.width === 0 && r.height === 0) continue;
499546
if (r.width < 44 || r.height < 44) small += 1;
500-
}
547+
}}
501548
return small;
502-
})()"#,
503-
)
549+
}})()"#,
550+
))
504551
.await?
505552
.into_value()?;
506553

@@ -549,7 +596,7 @@ pub async fn check_input_persistence(page: &Page, wait_secs: u64) -> Result<Chec
549596
.evaluate(format!(
550597
r#"(() => {{
551598
const f = {TARGET_FORM_JS};
552-
const el = f?.querySelector('input[type=text], input:not([type]), textarea');
599+
const el = f ? ({DEEP_QUERY_JS})(f, 'input[type=text], input:not([type]), textarea')[0] : undefined;
553600
if (!el) return false;
554601
el.value = '{marker}';
555602
el.dispatchEvent(new Event('input', {{ bubbles: true }}));
@@ -571,7 +618,11 @@ pub async fn check_input_persistence(page: &Page, wait_secs: u64) -> Result<Chec
571618

572619
let still_there: bool = page
573620
.evaluate(format!(
574-
"({TARGET_FORM_JS})?.querySelector('input[type=text], input:not([type]), textarea')?.value === '{marker}'"
621+
r#"(() => {{
622+
const f = {TARGET_FORM_JS};
623+
const el = f ? ({DEEP_QUERY_JS})(f, 'input[type=text], input:not([type]), textarea')[0] : undefined;
624+
return el?.value === '{marker}';
625+
}})()"#
575626
))
576627
.await?
577628
.into_value()?;
@@ -616,7 +667,7 @@ pub async fn check_input_persistence(page: &Page, wait_secs: u64) -> Result<Chec
616667
pub async fn check_validation_errors(page: &Page) -> Result<CheckResult> {
617668
let required_count: i64 = page
618669
.evaluate(format!(
619-
"(() => {{ const f = {TARGET_FORM_JS}; return f ? f.querySelectorAll('[required], [aria-required=true]').length : 0; }})()"
670+
"(() => {{ const f = {TARGET_FORM_JS}; return f ? ({DEEP_QUERY_JS})(f, '[required], [aria-required=true]').length : 0; }})()"
620671
))
621672
.await?
622673
.into_value()?;
@@ -627,7 +678,7 @@ pub async fn check_validation_errors(page: &Page) -> Result<CheckResult> {
627678
// them. Tracked separately so an all-aria-required form doesn't get
628679
// a false Pass just because nothing native-invalid was found.
629680
let native_required_count: i64 = page
630-
.evaluate(format!("(() => {{ const f = {TARGET_FORM_JS}; return f ? f.querySelectorAll('[required]').length : 0; }})()"))
681+
.evaluate(format!("(() => {{ const f = {TARGET_FORM_JS}; return f ? ({DEEP_QUERY_JS})(f, '[required]').length : 0; }})()"))
631682
.await?
632683
.into_value()?;
633684

@@ -640,7 +691,7 @@ pub async fn check_validation_errors(page: &Page) -> Result<CheckResult> {
640691
r#"(() => {{
641692
const f = {TARGET_FORM_JS};
642693
if (!f) return false;
643-
const req = f.querySelector('[required], [aria-required=true]');
694+
const req = ({DEEP_QUERY_JS})(f, '[required], [aria-required=true]')[0];
644695
if (req) {{
645696
if (req.type === 'checkbox' || req.type === 'radio') {{
646697
req.checked = false;
@@ -662,7 +713,7 @@ pub async fn check_validation_errors(page: &Page) -> Result<CheckResult> {
662713
r#"(() => {{
663714
const f = {TARGET_FORM_JS};
664715
if (!f) return 0;
665-
const invalid = f.querySelectorAll(':invalid, [aria-invalid=true]');
716+
const invalid = ({DEEP_QUERY_JS})(f, ':invalid, [aria-invalid=true]');
666717
let unlabeled = 0;
667718
for (const el of invalid) {{
668719
const describedBy = el.getAttribute('aria-describedby');
@@ -722,7 +773,7 @@ pub async fn check_required_documents(page: &Page) -> Result<CheckResult> {
722773

723774
let file_inputs: i64 = page
724775
.evaluate(format!(
725-
"(() => {{ const f = {TARGET_FORM_JS}; return f ? f.querySelectorAll('input[type=file]').length : 0; }})()"
776+
"(() => {{ const f = {TARGET_FORM_JS}; return f ? ({DEEP_QUERY_JS})(f, 'input[type=file]').length : 0; }})()"
726777
))
727778
.await?
728779
.into_value()?;
@@ -747,13 +798,13 @@ pub async fn check_required_documents(page: &Page) -> Result<CheckResult> {
747798
.evaluate(format!(
748799
r#"(() => {{
749800
const f = {TARGET_FORM_JS};
750-
const inputs = f ? f.querySelectorAll('input[type=file]') : [];
801+
const inputs = f ? ({DEEP_QUERY_JS})(f, 'input[type=file]') : [];
751802
let unlabeled = 0;
752803
for (const el of inputs) {{
753804
// Not a `label[for="${{el.id}}"]` selector: an id containing a
754805
// double quote (legal in HTML) breaks that selector with a
755806
// DOMException instead of just not matching.
756-
const byFor = el.id && Array.from(document.querySelectorAll('label')).find((l) => l.htmlFor === el.id)?.textContent.trim();
807+
const byFor = el.id && ({DEEP_QUERY_JS})(document, 'label').find((l) => l.htmlFor === el.id)?.textContent.trim();
757808
const byWrap = el.closest('label')?.textContent.trim();
758809
const byAria = el.getAttribute('aria-label');
759810
if (!byFor && !byWrap && !byAria) unlabeled += 1;
@@ -768,7 +819,7 @@ pub async fn check_required_documents(page: &Page) -> Result<CheckResult> {
768819
.evaluate(format!(
769820
r#"(() => {{
770821
const f = {TARGET_FORM_JS};
771-
const inputs = f ? f.querySelectorAll('input[type=file]') : [];
822+
const inputs = f ? ({DEEP_QUERY_JS})(f, 'input[type=file]') : [];
772823
let missing = 0;
773824
for (const el of inputs) {{
774825
if (el.hasAttribute('accept')) continue;
@@ -810,14 +861,14 @@ pub async fn check_autofill_hints(page: &Page) -> Result<CheckResult> {
810861
r#"(() => {{
811862
const guesses = [/name/i, /e-?mail/i, /tel|phone/i, /postal|zip/i, /address/i];
812863
const f = {TARGET_FORM_JS};
813-
const fields = f ? f.querySelectorAll(
864+
const fields = f ? ({DEEP_QUERY_JS})(f,
814865
'input[type=text], input[type=email], input[type=tel], input:not([type])'
815866
) : [];
816867
let missing = 0;
817868
for (const el of fields) {{
818869
if (el.disabled || el.offsetParent === null || el.hasAttribute('autocomplete')) continue;
819870
const label = (
820-
Array.from(document.querySelectorAll('label')).find((l) => l.htmlFor === el.id)?.textContent
871+
({DEEP_QUERY_JS})(document, 'label').find((l) => l.htmlFor === el.id)?.textContent
821872
|| el.name
822873
|| el.id
823874
|| ''

‎tests/checks_test.rs‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -523,3 +523,42 @@ async fn run_custom_checks_runs_every_script_and_names_by_filename() {
523523
malformed.detail
524524
);
525525
}
526+
527+
#[tokio::test]
528+
async fn form_inside_an_open_shadow_root_is_found_and_checked() {
529+
// fixtures/shadow-dom-form.html renders its actual <form> inside an
530+
// open shadow root on a custom element — the way many modern
531+
// government-site design systems structure forms. Plain
532+
// document.querySelectorAll('form') can't see into a shadow root at
533+
// all, so before the deep-query fix every check here silently saw an
534+
// empty page (0 fields, 0 required, no upload field) instead of a
535+
// real result.
536+
let (_browser, page, _handle) = open_fixture("shadow-dom-form.html").await;
537+
let results = checks::run_all(&page, false, 1).await;
538+
539+
let submission = find(&results, "Submission flow");
540+
assert_eq!(
541+
submission.status,
542+
checks::Status::Pass,
543+
"got: {submission:?}"
544+
);
545+
assert!(
546+
submission.detail.contains("filled 1 field"),
547+
"expected the shadow-rooted text field to be found and filled, got: {}",
548+
submission.detail
549+
);
550+
551+
let validation = find(&results, "Validation errors");
552+
assert!(
553+
validation.detail.starts_with("1 required field(s)"),
554+
"expected the shadow-rooted required field to be counted, got: {}",
555+
validation.detail
556+
);
557+
558+
let documents = find(&results, "Required documents");
559+
assert!(
560+
documents.detail.starts_with("1 upload field(s)"),
561+
"expected the shadow-rooted file input to be found, got: {}",
562+
documents.detail
563+
);
564+
}

0 commit comments

Comments
 (0)