auditmysite 1.3.0

Resource-efficient WCAG 2.1 Accessibility Checker in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
//! Violation enrichment — resolves AX node IDs to human-readable DOM locations
//!
//! After WCAG rules produce violations (which only know AX node IDs), this module
//! uses CDP `DOM.describeNode` with the AXNode's `backend_dom_node_id` to fetch
//! the actual DOM element and writes a useful `selector` string
//! (e.g. `img#banner [src: …/hero.jpg]`, `a.nav-link > svg`) back into each violation.
//!
//! For elements with no id/class/attributes, a second pass uses
//! `DOM.resolveNode` + `Runtime.callFunctionOn` to include parent context
//! so the developer can locate the element in the DOM.

use chromiumoxide::cdp::browser_protocol::dom::{
    BackendNodeId, DescribeNodeParams, GetOuterHtmlParams, ResolveNodeParams,
};
use chromiumoxide::cdp::js_protocol::runtime::{CallFunctionOnParams, RemoteObjectId};
use chromiumoxide::Page;
use tracing::warn;

use super::code_gen::{generate_suggested_code, truncate_html};
use super::tree::AXTree;
use crate::wcag::types::Violation;

/// Identifies the DOM node evidence should be resolved from: either a plain
/// backend node id, or a live JS object reference (used when we've redirected
/// to a shadow host — see [`effective_node_ref`]).
enum NodeRef {
    Backend(i64),
    Object(RemoteObjectId),
}

// ─── Public entry point ──────────────────────────────────────────────────────

/// Enrich all violations in-place with readable selectors from the live DOM.
///
/// For each violation that has no selector yet, looks up the corresponding AXNode
/// in `ax_tree`, extracts its `backend_dom_node_id`, and calls `DOM.describeNode`
/// via CDP to get the element's tag name and attributes. Contrast violations
/// (1.4.3) already carry selectors from the style extractor and are skipped.
pub async fn enrich_violations_with_page(
    page: &Page,
    violations: &mut [Violation],
    ax_tree: &AXTree,
) {
    for violation in violations.iter_mut() {
        if violation.selector.is_some() {
            continue; // already enriched (e.g. contrast rule)
        }

        let backend_id = match ax_tree
            .get_node(&violation.node_id)
            .and_then(|n| n.backend_dom_node_id)
        {
            Some(id) => id,
            None => {
                // Two different situations land here, and only one is a real
                // "ghost element": either `node_id` names a real AX node that
                // has no backend DOM node id (element vanished — genuinely
                // unconfirmable, demote), or `node_id` is one of the
                // well-known page-level placeholders ("page"/"root"/
                // "document") that dozens of page-wide checks (skip-link,
                // css-orientation-lock, location, css-order-reading-sequence,
                // …) intentionally use for findings that were never tied to
                // one specific DOM element in the first place — those were
                // never "resolvable" to begin with, so failing to resolve
                // them isn't evidence of anything and must not silently
                // downgrade an otherwise-confident violation to a warning
                // (#562: this was the actual root cause of a violation→
                // warning downgrade affecting many unrelated rule files).
                if !is_page_level_placeholder_node_id(&violation.node_id) {
                    violation.kind = crate::wcag::types::FindingKind::Warning;
                }
                continue;
            }
        };

        let node_ref = effective_node_ref(page, backend_id).await;

        match describe_node_selector(page, &node_ref).await {
            Some((sel, dom_path)) => {
                violation
                    .evidence
                    .push(crate::wcag::types::ViolationEvidence::ax_tree(&sel));
                violation.selector = Some(sel);
                // A short, always-computed DOM path (evidence-grade findings)
                // — distinct from `selector`'s tag/id/hint shorthand, this is
                // the up-to-3-level ancestor chain a developer can paste into
                // devtools to locate the element.
                if let Some(path) = dom_path.filter(|p| !p.is_empty()) {
                    violation
                        .evidence
                        .push(crate::wcag::types::ViolationEvidence {
                            source: "ax_tree".to_string(),
                            field: Some("dom_path".to_string()),
                            value: Some(path),
                        });
                }
            }
            None => {
                warn!(
                    "Could not resolve backend DOM node {} for violation {}",
                    backend_id, violation.rule
                );
                // Element not locatable in live DOM — cannot be confirmed.
                violation.kind = crate::wcag::types::FindingKind::Warning;
            }
        }

        // Fetch outer HTML and generate a concrete code fix
        if let Some(raw_html) = get_outer_html(page, &node_ref).await {
            // Two 1.1.1 false-positive classes are demoted to warnings so they do
            // not inflate violation counts or scoring (#487):
            //   1. Lazy-load <img> placeholders (data-src/data-srcset/lazyload)
            //      receive their real src+alt only on scroll, which a headless
            //      audit never triggers.
            //   2. Decorative inline SVG icons (<svg><use …> sprite refs with no
            //      <title>/aria-label) — almost always UI chrome that should carry
            //      aria-hidden. A meaningful SVG has a title/label and thus an
            //      accessible name, so it never reaches this check.
            if violation.rule == "1.1.1"
                && (is_lazyload_image_placeholder(&raw_html) || is_decorative_svg_icon(&raw_html))
            {
                violation.kind = crate::wcag::types::FindingKind::Warning;
            }
            let snippet = truncate_html(raw_html);
            let suggested = generate_suggested_code(
                &violation.rule,
                Some(&snippet),
                violation.role.as_deref(),
                violation.fix_suggestion.as_deref(),
            );
            violation.html_snippet = Some(snippet);
            violation.suggested_code = suggested;
        } else {
            // No live DOM available — still try to generate a template fix
            violation.suggested_code = generate_suggested_code(
                &violation.rule,
                None,
                violation.role.as_deref(),
                violation.fix_suggestion.as_deref(),
            );
        }
    }
}

/// True for a `node_id` that could never have come from CDP in the first
/// place — real `Accessibility.AXNodeId` values are always non-negative
/// integer strings (confirmed by `extractor.rs`'s own parsing: a fresh tree's
/// first node is literally `"1"`). Dozens of page-wide WCAG checks
/// (skip-link, css-orientation-lock, location, css-order-reading-sequence,
/// visual-presentation's `"stylesheet"`, and others) intentionally use a
/// word like `"page"`/`"root"`/`"document"`/`"stylesheet"` as the `node_id`
/// for findings that were never tied to one specific DOM element — those
/// were never resolvable to begin with, so failing to look them up in the AX
/// tree isn't evidence the underlying element vanished (#562). Checking "is
/// this a real CDP id shape" instead of matching a fixed word list is
/// deliberate: it stays correct for whichever placeholder word some new rule
/// file picks next, without needing this list edited every time.
fn is_page_level_placeholder_node_id(node_id: &str) -> bool {
    !node_id.is_empty() && !node_id.bytes().all(|b| b.is_ascii_digit())
}

/// Detects JS lazy-load `<img>` placeholders whose real source/alt is deferred to
/// a `data-*` attribute and only swapped in on scroll. Native `loading="lazy"`
/// images keep a real `src`/`alt` and are intentionally *not* matched here, so a
/// genuinely missing alt on a native-lazy image still counts (#487).
fn is_lazyload_image_placeholder(html: &str) -> bool {
    let lower = html.to_ascii_lowercase();
    if !lower.trim_start().starts_with("<img") {
        return false;
    }
    const LAZY_MARKERS: &[&str] = &[
        "data-src",
        "data-srcset",
        "data-lazy",
        "data-original",
        "lazyload",
    ];
    LAZY_MARKERS.iter().any(|marker| lower.contains(marker))
}

/// Detects decorative inline SVG icons: an `<svg>` that references a sprite via
/// `<use>` and carries no `<title>` or `aria-label`. These are UI chrome that
/// should be `aria-hidden`; flagging each as a missing-alt 1.1.1 barrier inflates
/// counts on icon-heavy sites. A meaningful SVG exposes a name (title/aria-label)
/// and therefore never reaches the 1.1.1 check at all (#487).
fn is_decorative_svg_icon(html: &str) -> bool {
    let lower = html.to_ascii_lowercase();
    lower.trim_start().starts_with("<svg")
        && lower.contains("<use")
        && !lower.contains("<title")
        && !lower.contains("aria-label")
}

// ─── CDP element resolution ───────────────────────────────────────────────────

/// Detects whether `backend_node_id` refers to a node inside a shadow root —
/// e.g. Chrome's own UA-internal rendering for `<input type="image">`, whose
/// exposed "image" AX node resolves to an internal shadow element that
/// doesn't exist anywhere in the author's markup (#QA-037: a finding cited
/// `<img id="alttext-image" …>`, a Chrome-internal broken-image placeholder,
/// while the actual authored element — the `<input type="image">` itself —
/// was reported correctly by a separate DOM-based check). When found,
/// redirects evidence resolution to the shadow host element instead, which
/// IS part of the author's DOM. Falls back to the original backend node id
/// on any resolution failure or when the node isn't inside a shadow root.
async fn effective_node_ref(page: &Page, backend_node_id: i64) -> NodeRef {
    let fallback = NodeRef::Backend(backend_node_id);

    let Some(object_id) = resolve_object_id(page, &fallback).await else {
        return fallback;
    };

    let js = r#"function() {
        var root = this.getRootNode();
        return (root && root.host) ? root.host : null;
    }"#;
    let Ok(call) = CallFunctionOnParams::builder()
        .function_declaration(js)
        .object_id(object_id)
        .build()
    else {
        return fallback;
    };

    let Ok(result) = page.execute(call).await else {
        return fallback;
    };

    match result.result.result.object_id.clone() {
        Some(host_object_id) => NodeRef::Object(host_object_id),
        None => fallback,
    }
}

/// Resolve a [`NodeRef`] to a live JS object id, via `DOM.resolveNode` for a
/// backend node id or directly for an already-resolved object reference.
async fn resolve_object_id(page: &Page, node_ref: &NodeRef) -> Option<RemoteObjectId> {
    match node_ref {
        NodeRef::Object(object_id) => Some(object_id.clone()),
        NodeRef::Backend(id) => {
            let resolve = ResolveNodeParams::builder()
                .backend_node_id(BackendNodeId::new(*id))
                .build();

            let resolved = page
                .execute(resolve)
                .await
                .map_err(|e| warn!("DOM.resolveNode failed: {}", e))
                .ok()?;

            resolved.object.object_id.clone()
        }
    }
}

/// Call CDP `DOM.describeNode` for the given node and build a human-readable
/// selector string from the returned element data. Falls back to a
/// parent-context lookup for bare elements with no id/class/attrs.
///
/// Returns `(selector, dom_path)`: `selector` is the existing tag/id/hint
/// shorthand (unchanged behavior); `dom_path` is the up-to-3-level ancestor
/// chain from [`parent_context_selector`], now always computed (not just as
/// a bare-tag fallback) so every violation carries a locatable DOM path for
/// the PDF's evidence block (evidence-grade findings, slice 3).
async fn describe_node_selector(
    page: &Page,
    node_ref: &NodeRef,
) -> Option<(String, Option<String>)> {
    let builder = DescribeNodeParams::builder();
    let builder = match node_ref {
        NodeRef::Backend(id) => builder.backend_node_id(BackendNodeId::new(*id)),
        NodeRef::Object(object_id) => builder.object_id(object_id.clone()),
    };
    let params = builder.build();

    let response = page
        .execute(params)
        .await
        .map_err(|e| warn!("DOM.describeNode failed: {}", e))
        .ok()?;

    let node = &response.node;
    let tag = node.node_name.to_lowercase();

    // Attributes arrive as a flat array: [name0, val0, name1, val1, …]
    let attrs: Vec<String> = node.attributes.as_deref().unwrap_or(&[]).to_vec();
    let attr_pairs: Vec<(&str, &str)> = attrs
        .chunks(2)
        .filter_map(|p| {
            if p.len() == 2 {
                Some((p[0].as_str(), p[1].as_str()))
            } else {
                None
            }
        })
        .collect();

    let get = |name: &str| -> Option<&str> {
        attr_pairs.iter().find(|(k, _)| *k == name).map(|(_, v)| *v)
    };

    // Build base selector: tag + id, or tag + first class
    let base = if let Some(id) = get("id").filter(|v| !v.is_empty()) {
        format!("{}#{}", tag, id)
    } else if let Some(cls) = get("class").filter(|v| !v.is_empty()) {
        let first = cls.split_whitespace().next().unwrap_or("");
        format!("{}.{}", tag, first)
    } else {
        tag.clone()
    };

    // Append a short contextual hint for common element types
    let hint = match tag.as_str() {
        "img" => get("src").map(|s| format!("src: {}", short_url(s))),
        "a" => get("href").map(|s| format!("href: {}", short_url(s))),
        "input" => get("type")
            .map(|t| format!("type={}", t))
            .or_else(|| get("name").map(|n| format!("name={}", n))),
        "svg" => get("viewBox")
            .map(|vb| format!("viewBox={}", vb))
            .or_else(|| get("width").map(|w| format!("width={}", w))),
        _ => None,
    };

    let selector = if let Some(h) = hint {
        format!("{} [{}]", base, h)
    } else {
        base.clone()
    };

    // Always compute the multi-level ancestor path (dom_path evidence), and —
    // for a bare tag with no distinguishing info — also use it as the
    // selector itself, so the developer can still locate the element.
    let dom_path = parent_context_selector(page, node_ref).await;

    if selector == tag {
        if let Some(ctx) = &dom_path {
            return Some((ctx.clone(), dom_path));
        }
    }

    Some((selector, dom_path))
}

/// Use `Runtime.callFunctionOn` to run JS on the element and return
/// `"parentSel > tag"` (e.g. `a.nav-link > svg`).
async fn parent_context_selector(page: &Page, node_ref: &NodeRef) -> Option<String> {
    let object_id = resolve_object_id(page, node_ref).await?;

    // Run JS on the element: returns a precise path up to 3 levels deep,
    // including :nth-of-type when siblings of the same tag exist.
    let js = r#"function() {
        function seg(el) {
            if (!el) return '';
            const tag = el.tagName.toLowerCase();
            if (el.id) return tag + '#' + el.id;
            const cls = (typeof el.className === 'string' && el.className.trim())
                ? '.' + el.className.trim().split(/\s+/)[0]
                : '';
            // Add :nth-of-type when there are multiple siblings with the same tag
            const p = el.parentElement;
            if (p) {
                const siblings = Array.from(p.children).filter(c => c.tagName === el.tagName);
                if (siblings.length > 1) {
                    const idx = siblings.indexOf(el) + 1;
                    return tag + cls + ':nth-of-type(' + idx + ')';
                }
            }
            return tag + cls;
        }
        const parts = [];
        let cur = this;
        for (let i = 0; i < 3 && cur && cur !== document.documentElement && cur !== document.body; i++) {
            parts.unshift(seg(cur));
            // Stop early if this segment is already unique (has id or unique class)
            if (cur.id) break;
            cur = cur.parentElement;
        }
        return parts.join(' > ');
    }"#;

    let call = match CallFunctionOnParams::builder()
        .function_declaration(js)
        .object_id(object_id)
        .return_by_value(true)
        .build()
    {
        Ok(p) => p,
        Err(e) => {
            warn!("CallFunctionOn build failed: {}", e);
            return None;
        }
    };

    let result = page
        .execute(call)
        .await
        .map_err(|e| warn!("Runtime.callFunctionOn failed: {}", e))
        .ok()?;

    result
        .result
        .result
        .value
        .as_ref()
        .and_then(serde_json::Value::as_str)
        .filter(|s| !s.is_empty())
        .map(|s| s.to_string())
}

/// Call CDP `DOM.getOuterHTML` for the given node.
/// Returns the raw HTML string, or `None` on failure.
async fn get_outer_html(page: &Page, node_ref: &NodeRef) -> Option<String> {
    let builder = GetOuterHtmlParams::builder();
    let builder = match node_ref {
        NodeRef::Backend(id) => builder.backend_node_id(BackendNodeId::new(*id)),
        NodeRef::Object(object_id) => builder.object_id(object_id.clone()),
    };
    let params = builder.build();

    let response = page
        .execute(params)
        .await
        .map_err(|e| warn!("DOM.getOuterHTML failed: {}", e))
        .ok()?;

    let html = response.outer_html.trim().to_string();
    if html.is_empty() {
        None
    } else {
        Some(html)
    }
}

/// Truncate a URL to at most 55 characters, keeping the tail.
fn short_url(s: &str) -> String {
    if s.len() > 55 {
        format!("\u{2026}{}", &s[s.len() - 52..])
    } else {
        s.to_string()
    }
}

// ─── Tests ───────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn short_url_truncates_long_src() {
        let long = "https://example.com/assets/images/hero-banner-2024-large.jpg";
        let result = short_url(long);
        assert!(result.starts_with('\u{2026}'));
        assert!(result.chars().count() <= 53);
    }

    #[test]
    fn short_url_keeps_short_src() {
        let short = "/img/logo.png";
        assert_eq!(short_url(short), short);
    }

    #[test]
    fn page_level_placeholder_node_ids_are_recognized() {
        // Every known placeholder word in use across the rule files, plus a
        // hypothetical new one — the point of the numeric-shape heuristic is
        // that it doesn't need this list maintained.
        assert!(is_page_level_placeholder_node_id("page"));
        assert!(is_page_level_placeholder_node_id("root"));
        assert!(is_page_level_placeholder_node_id("document"));
        assert!(is_page_level_placeholder_node_id("stylesheet"));
        assert!(is_page_level_placeholder_node_id("some-future-placeholder"));
    }

    #[test]
    fn real_ax_node_ids_are_not_page_level_placeholders() {
        // Real CDP AX node ids look like small integers-as-strings
        // (extractor.rs's own parsing: a fresh tree's first node is "1").
        assert!(!is_page_level_placeholder_node_id("42"));
        assert!(!is_page_level_placeholder_node_id("1"));
        // Empty is treated as a genuine unknown, not a placeholder — still
        // demoted, since there's no signal it was ever an intentional
        // page-wide reference rather than a bug.
        assert!(!is_page_level_placeholder_node_id(""));
    }

    #[test]
    fn lazyload_placeholder_detection() {
        // JS lazy-load placeholders → demoted.
        assert!(is_lazyload_image_placeholder(
            r#"<img class="lazyload" alt="" src="data:image/svg+xml,...">"#
        ));
        assert!(is_lazyload_image_placeholder(
            r#"<img data-src="/real.jpg" src="/placeholder.gif">"#
        ));
        assert!(is_lazyload_image_placeholder(
            r#"<img data-srcset="/real-2x.jpg 2x">"#
        ));
        // Native lazy + real image, and non-img elements → not matched.
        assert!(!is_lazyload_image_placeholder(
            r#"<img loading="lazy" src="/real.jpg">"#
        ));
        assert!(!is_lazyload_image_placeholder(r#"<img src="/real.jpg">"#));
        assert!(!is_lazyload_image_placeholder(
            r#"<div data-src="/x.jpg"></div>"#
        ));
    }

    #[test]
    fn decorative_svg_icon_detection() {
        // Sprite-ref icon with no title/label → decorative.
        assert!(is_decorative_svg_icon(
            r##"<svg width="16" height="16"><use xlink:href="#spon-text-m"></use></svg>"##
        ));
        // Labelled / titled SVGs are meaningful → not demoted.
        assert!(!is_decorative_svg_icon(
            r##"<svg aria-label="Search"><use xlink:href="#search"></use></svg>"##
        ));
        assert!(!is_decorative_svg_icon(
            r#"<svg><title>Chart</title><path d="…"/></svg>"#
        ));
        // Not an SVG / no sprite ref.
        assert!(!is_decorative_svg_icon(r#"<img src="/x.jpg">"#));
        assert!(!is_decorative_svg_icon(r#"<svg><path d="…"/></svg>"#));
    }
}