auditmysite 1.7.3

Resource-efficient WCAG 2.2 AA 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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
//! Accessibility-Journey-Layer — runs interactive journeys against a page
//! after the static AXTree-based audit has finished.
//!
//! `run()` is the **single** pipeline hook; phases 2–5 extend its body
//! without changing the signature.
//!
//! Phase 2: tab-walk evaluation, skip-link, disclosure, modal, tabs, menu journeys.
//! Phase 3: form-error announcement, SPA-navigation detection, link/heading/landmark inventory.

pub mod add_to_cart;
pub mod disclosure_journey;
pub mod evaluate;
pub mod form_error;
pub mod link_inventory;
pub mod menu_journey;
pub mod modal_journey;
pub mod quantity_stepper;
pub mod skip_link;
pub mod spa_navigation;
pub mod tab_walk;
pub mod tabs_journey;

use std::time::Instant;

use chromiumoxide::cdp::js_protocol::runtime::EvaluateParams;
use chromiumoxide::Page;

use crate::accessibility::AXTree;
use crate::audit::normalized::{AccessibilityJourney, InteractiveFinding};
use crate::cli::InteractiveMode;
use crate::commerce::{CommerceAnalysis, CommercePageKind};
use crate::error::Result;
use crate::patterns::{JourneyCandidate, JourneyKind, PatternAnalysis};

/// Inputs the journey orchestrator needs. Kept narrow on purpose so the
/// pipeline only has to pass what is actually used.
pub struct RunContext<'a> {
    pub page: &'a Page,
    pub mode: InteractiveMode,
    /// Pattern analysis from the static phase — provides journey candidates.
    pub patterns: Option<&'a PatternAnalysis>,
    /// Initial AXTree snapshot — used by pure-analysis passes (link inventory,
    /// heading outline, landmark inventory) that don't need browser interaction.
    pub ax_tree: &'a AXTree,
    /// URL at audit start (used for SPA-navigation detection).
    pub initial_url: &'a str,
    /// Report locale (e.g. "de", "en") — drives which FTL stopword lists are
    /// loaded for link-text detection in addition to the always-merged defaults.
    pub locale: &'a str,
    /// Maximum wall-clock time the journey phase is allowed to consume.
    pub budget_ms: u64,
    /// Commerce analysis for this page, when derived (shop context detected).
    /// Used only to gate commerce-specific journeys (e.g. `AddToCart` to
    /// `CommercePageKind::ProductDetail`) — `patterns::analyze()` itself has
    /// no commerce context (it runs before the commerce module derives this).
    pub commerce: Option<&'a CommerceAnalysis>,
}

/// Output of one journey run. The trace bundle and findings are kept
/// separate so the caller can route them to the right slots on
/// `AuditReport` / `NormalizedReport` (`accessibility_journey` vs.
/// `interactive_findings`).
#[derive(Default)]
pub struct RunOutput {
    pub journey: AccessibilityJourney,
    pub findings: Vec<InteractiveFinding>,
}

/// Default journey budget per URL (ms).
///
/// Gemessen an 48 Seiten ohne Grenze (Plan 53): mit 5 s liefen 22 % der Seiten
/// ins Limit und nur 55 % der Befunde wurden erfasst, weil allein der Tab-Walk
/// rund 2 s braucht. 15 s erfassen 92 % bei im Mittel +1 s je Seite — das
/// Budget greift nur auf schweren Seiten, der Median der Phase liegt bei 2,8 s.
pub const DEFAULT_BUDGET_MS: u64 = 15_000;

/// Harte Obergrenze je Journey (ms).
///
/// Die Deadline wird nur vor dem Start einer Journey geprüft. Hängt die Seite,
/// läuft jeder CDP-Aufruf in seinen eigenen 30-s-Timeout — auf www.dm.de
/// brauchte so eine einzelne Accordion-Journey 180 s. Die langsamste Journey
/// ohne Hänger lag bei 5,6 s (Modal).
const JOURNEY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);

fn journey_allowed(mode: InteractiveMode, journey: JourneyKind) -> bool {
    match mode {
        InteractiveMode::Off => false,
        InteractiveMode::Basic => !matches!(
            journey,
            JourneyKind::FormErrorSubmit | JourneyKind::AddToCart | JourneyKind::QuantityStepper
        ),
        InteractiveMode::Full => true,
    }
}

/// Commerce-specific gate for journeys that must never run outside their
/// intended shop context, on top of `journey_allowed`'s mode check — e.g.
/// `AddToCart`/`QuantityStepper` only make sense (and are only safe to
/// interpret) on a detected shop's product-detail page. Both are restricted
/// to `ProductDetail` only — `CommercePageKind::Cart` was removed (see its
/// doc comment): this tool has no cross-page cart/session state, so a cart
/// page reached cold is (almost) always empty, meaning a Cart-gated
/// `QuantityStepper` run would essentially never find a real line item to
/// test in practice.
fn commerce_gate_allows(journey: JourneyKind, commerce: Option<&CommerceAnalysis>) -> bool {
    match journey {
        JourneyKind::AddToCart | JourneyKind::QuantityStepper => commerce
            .map(|c| c.page_kind == CommercePageKind::ProductDetail)
            .unwrap_or(false),
        _ => true,
    }
}

/// Die Reihenfolge, in der Kandidaten abgearbeitet werden: absteigend nach
/// Konfidenz.
///
/// Das Zeitbudget schneidet die Liste hinten ab — gemessen an 160 Seiten
/// fielen so 122 von 1384 Kandidaten weg, 9 % der Seiten liefen ins Limit.
/// Wen es trifft, war bis dahin eine Frage der Erkennungsreihenfolge: die
/// nativen `<details>` etwa standen hinter allen ARIA-Auslösern und fielen
/// damit zuerst heraus. Muss geschnitten werden, sollen die unsichersten
/// Kandidaten fallen, nicht die zuletzt erkannten.
///
/// Stabil sortiert: innerhalb einer Konfidenzstufe bleibt die Reihenfolge der
/// Erkennung erhalten.
fn by_descending_confidence(candidates: &[JourneyCandidate]) -> Vec<&JourneyCandidate> {
    let mut ordered: Vec<&JourneyCandidate> = candidates.iter().collect();
    ordered.sort_by(|a, b| {
        b.confidence
            .partial_cmp(&a.confidence)
            .unwrap_or(std::cmp::Ordering::Equal)
    });
    ordered
}

/// Single entry point invoked from `audit/pipeline.rs::audit_page`.
///
/// Returns `None` for `--interactive=off` so the rest of the pipeline
/// pays zero cost. Otherwise records journeys, evaluates them, and
/// returns both pieces.
pub async fn run(ctx: RunContext<'_>) -> Result<Option<RunOutput>> {
    if !ctx.mode.is_enabled() {
        return Ok(None);
    }

    let deadline = Instant::now() + std::time::Duration::from_millis(ctx.budget_ms);
    let mut out = RunOutput::default();
    out.journey.execution.mode = format!("{:?}", ctx.mode).to_lowercase();
    out.journey.execution.budget_ms = ctx.budget_ms;

    let max_steps = match ctx.mode {
        InteractiveMode::Off => 0,
        InteractiveMode::Basic => 25,
        InteractiveMode::Full => 60,
    };

    // ── Tab walk + evaluation ────────────────────────────────────────────────
    out.journey.execution.candidates_detected += 1;
    out.journey.execution.attempted += 1;
    match tokio::time::timeout(JOURNEY_TIMEOUT, tab_walk::record(ctx.page, max_steps)).await {
        Ok(Ok(record)) => {
            out.findings
                .extend(evaluate::tab_walk(&record.trace, &record.snapshots));
            out.findings
                .extend(evaluate::tab_walk_order(&record.trace, &record.dom_order));
            out.findings.extend(evaluate::video_controls_reachability(
                &record.trace,
                &record.dom_order,
            ));
            out.journey.focus_evidence = record.snapshots;
            out.journey.traces.push(record.trace);
            out.journey.execution.completed += 1;
            out.journey
                .execution
                .runs
                .push(crate::audit::normalized::JourneyRun {
                    journey: "tab_walk".to_string(),
                    status: crate::audit::ExecutionStatus::Completed,
                    reason_code: None,
                });
        }
        Ok(Err(e)) => {
            tracing::warn!("Tab-walk journey failed: {}", e);
            out.journey.execution.failed += 1;
            out.journey
                .execution
                .runs
                .push(crate::audit::normalized::JourneyRun {
                    journey: "tab_walk".to_string(),
                    status: crate::audit::ExecutionStatus::Failed,
                    reason_code: Some("tab_walk_failed".to_string()),
                });
        }
        Err(_) => {
            tracing::warn!("Tab-walk journey timed out after {:?}", JOURNEY_TIMEOUT);
            out.journey.execution.failed += 1;
            out.journey
                .execution
                .runs
                .push(crate::audit::normalized::JourneyRun {
                    journey: "tab_walk".to_string(),
                    status: crate::audit::ExecutionStatus::Failed,
                    reason_code: Some("journey_timeout".to_string()),
                });
        }
    }

    // ── Pattern-based journeys ───────────────────────────────────────────────
    if let Some(patterns) = ctx.patterns {
        let mut skip_link_idx = 0usize;
        let mut disclosure_idx = 0usize;
        let mut modal_idx = 0usize;
        let mut tabs_idx = 0usize;
        let mut menu_idx = 0usize;
        let mut form_idx = 0usize;
        let mut add_to_cart_idx = 0usize;
        let mut quantity_stepper_idx = 0usize;

        out.journey.execution.candidates_detected += patterns.journey_candidates.len();

        let ordered = by_descending_confidence(&patterns.journey_candidates);

        for (candidate_index, candidate) in ordered.iter().enumerate() {
            if Instant::now() >= deadline {
                tracing::info!("Journey budget exhausted, stopping pattern journeys early.");
                out.journey.execution.budget_exhausted = true;
                for remaining in &ordered[candidate_index..] {
                    out.journey.execution.skipped += 1;
                    out.journey
                        .execution
                        .runs
                        .push(crate::audit::normalized::JourneyRun {
                            journey: format!("{:?}", remaining.required_journey).to_lowercase(),
                            status: crate::audit::ExecutionStatus::Skipped,
                            reason_code: Some("budget_exhausted".to_string()),
                        });
                }
                break;
            }
            let skip_reason = if candidate.confidence < 0.7 {
                Some("low_confidence")
            } else if !journey_allowed(ctx.mode, candidate.required_journey) {
                Some("mode_excluded")
            } else if !commerce_gate_allows(candidate.required_journey, ctx.commerce) {
                Some("commerce_gate")
            } else {
                None
            };
            if let Some(reason) = skip_reason {
                out.journey.execution.skipped += 1;
                out.journey
                    .execution
                    .runs
                    .push(crate::audit::normalized::JourneyRun {
                        journey: format!("{:?}", candidate.required_journey).to_lowercase(),
                        status: crate::audit::ExecutionStatus::Skipped,
                        reason_code: Some(reason.to_string()),
                    });
                continue;
            }

            out.journey.execution.attempted += 1;

            let journey = async {
                match candidate.required_journey {
                    JourneyKind::SkipLinkActivate => {
                        let idx = skip_link_idx;
                        skip_link_idx += 1;
                        skip_link::test(ctx.page, candidate, idx).await
                    }
                    JourneyKind::DisclosureToggle | JourneyKind::AccordionToggle => {
                        let idx = disclosure_idx;
                        disclosure_idx += 1;
                        disclosure_journey::test(ctx.page, candidate, idx).await
                    }
                    JourneyKind::ModalOpen => {
                        let idx = modal_idx;
                        modal_idx += 1;
                        modal_journey::test(ctx.page, candidate, idx).await
                    }
                    JourneyKind::TabsNavigate => {
                        let idx = tabs_idx;
                        tabs_idx += 1;
                        tabs_journey::test(ctx.page, candidate, idx).await
                    }
                    JourneyKind::MenuOpen => {
                        let idx = menu_idx;
                        menu_idx += 1;
                        menu_journey::test(ctx.page, candidate, idx).await
                    }
                    JourneyKind::FormErrorSubmit => {
                        let idx = form_idx;
                        form_idx += 1;
                        form_error::test(ctx.page, candidate, idx).await
                    }
                    JourneyKind::AddToCart => {
                        let idx = add_to_cart_idx;
                        add_to_cart_idx += 1;
                        add_to_cart::test(ctx.page, candidate, idx).await
                    }
                    JourneyKind::QuantityStepper => {
                        let idx = quantity_stepper_idx;
                        quantity_stepper_idx += 1;
                        quantity_stepper::test(ctx.page, candidate, idx).await
                    }
                }
            };

            match tokio::time::timeout(JOURNEY_TIMEOUT, journey).await {
                Ok(Ok((trace, findings))) => {
                    out.journey.execution.completed += 1;
                    out.journey
                        .execution
                        .runs
                        .push(crate::audit::normalized::JourneyRun {
                            journey: trace.journey.clone(),
                            status: crate::audit::ExecutionStatus::Completed,
                            reason_code: None,
                        });
                    out.journey.traces.push(trace);
                    out.findings.extend(findings);
                }
                Ok(Err(e)) => {
                    tracing::warn!("Journey {:?} failed: {}", candidate.required_journey, e);
                    out.journey.execution.failed += 1;
                    out.journey
                        .execution
                        .runs
                        .push(crate::audit::normalized::JourneyRun {
                            journey: format!("{:?}", candidate.required_journey).to_lowercase(),
                            status: crate::audit::ExecutionStatus::Failed,
                            reason_code: Some("journey_execution_failed".to_string()),
                        });
                }
                Err(_) => {
                    tracing::warn!(
                        "Journey {:?} timed out after {:?}",
                        candidate.required_journey,
                        JOURNEY_TIMEOUT
                    );
                    out.journey.execution.failed += 1;
                    out.journey
                        .execution
                        .runs
                        .push(crate::audit::normalized::JourneyRun {
                            journey: format!("{:?}", candidate.required_journey).to_lowercase(),
                            status: crate::audit::ExecutionStatus::Failed,
                            reason_code: Some("journey_timeout".to_string()),
                        });
                }
            }
        }
    }

    // ── SPA-Navigation detection (Phase 3) ───────────────────────────────────
    // Full mode only: emits findings when actual SPA navigation is observed.
    if matches!(ctx.mode, InteractiveMode::Full) && Instant::now() < deadline {
        out.journey.execution.candidates_detected += 1;
        out.journey.execution.attempted += 1;
        match tokio::time::timeout(
            JOURNEY_TIMEOUT,
            spa_navigation::run(ctx.page, ctx.initial_url),
        )
        .await
        {
            Ok(Ok(Some((trace, findings)))) => {
                out.journey.execution.completed += 1;
                out.journey
                    .execution
                    .runs
                    .push(crate::audit::normalized::JourneyRun {
                        journey: trace.journey.clone(),
                        status: crate::audit::ExecutionStatus::Completed,
                        reason_code: None,
                    });
                out.journey.traces.push(trace);
                out.findings.extend(findings);
            }
            Ok(Ok(None)) => {
                out.journey.execution.skipped += 1;
                out.journey
                    .execution
                    .runs
                    .push(crate::audit::normalized::JourneyRun {
                        journey: "spa_navigation".to_string(),
                        status: crate::audit::ExecutionStatus::NotApplicable,
                        reason_code: Some("no_spa_candidate".to_string()),
                    });
            }
            Ok(Err(e)) => {
                tracing::warn!("SPA-navigation journey failed: {}", e);
                out.journey.execution.failed += 1;
                out.journey
                    .execution
                    .runs
                    .push(crate::audit::normalized::JourneyRun {
                        journey: "spa_navigation".to_string(),
                        status: crate::audit::ExecutionStatus::Failed,
                        reason_code: Some("spa_navigation_failed".to_string()),
                    });
            }
            Err(_) => {
                tracing::warn!(
                    "SPA-navigation journey timed out after {:?}",
                    JOURNEY_TIMEOUT
                );
                out.journey.execution.failed += 1;
                out.journey
                    .execution
                    .runs
                    .push(crate::audit::normalized::JourneyRun {
                        journey: "spa_navigation".to_string(),
                        status: crate::audit::ExecutionStatus::Failed,
                        reason_code: Some("journey_timeout".to_string()),
                    });
            }
        }
    } else if matches!(ctx.mode, InteractiveMode::Full) {
        out.journey.execution.budget_exhausted = true;
        out.journey.execution.candidates_detected += 1;
        out.journey.execution.skipped += 1;
        out.journey
            .execution
            .runs
            .push(crate::audit::normalized::JourneyRun {
                journey: "spa_navigation".to_string(),
                status: crate::audit::ExecutionStatus::Skipped,
                reason_code: Some("budget_exhausted".to_string()),
            });
    }

    // ── Link/Heading/Landmark inventory (Phase 3, Stufe B — pure AXTree) ────
    // Full mode only. No browser interaction, so it can run even if budget is exhausted.
    if matches!(ctx.mode, InteractiveMode::Full) {
        // Generic-link-text detection follows the *page's* language, not the
        // report language (#406) — a German page keeps being scanned with
        // German stopwords even when the report is rendered in English.
        let page_locale = eval_string(
            ctx.page,
            "document.documentElement.getAttribute('lang') || \
             document.documentElement.getAttribute('xml:lang') || ''",
        )
        .await
        .unwrap_or_default();
        out.findings.extend(link_inventory::analyse(
            ctx.ax_tree,
            &page_locale,
            ctx.locale,
        ));
    }

    Ok(Some(out))
}

/// Evaluate `js` and read back a `bool` result. Shared by the journey
/// submodules that each need a tiny amount of page-state probing.
pub(super) async fn eval_bool(page: &Page, js: &str) -> Option<bool> {
    let params = EvaluateParams::builder()
        .expression(js.to_string())
        .return_by_value(true)
        .build()
        .ok()?;
    let result = page.execute(params).await.ok()?;
    result.result.result.value?.as_bool()
}

/// Evaluate `js` and read back a `String` result (`None` for `null`/absent).
pub(super) async fn eval_string(page: &Page, js: &str) -> Option<String> {
    let params = EvaluateParams::builder()
        .expression(js.to_string())
        .return_by_value(true)
        .build()
        .ok()?;
    let result = page.execute(params).await.ok()?;
    result.result.result.value?.as_str().map(|s| s.to_string())
}

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

    fn candidate(confidence: f32, backend: i64) -> JourneyCandidate {
        JourneyCandidate {
            pattern_kind: crate::patterns::PatternKind::Disclosure,
            trigger_backend_id: Some(backend),
            controlled_backend_id: None,
            confidence,
            required_journey: JourneyKind::DisclosureToggle,
        }
    }

    /// Schneidet das Budget, sollen die unsichersten Kandidaten fallen — nicht
    /// die zuletzt erkannten. Vorher standen die nativen `<details>` (0.9)
    /// hinter jedem ARIA-Auslöser (0.7) und fielen als Erste heraus.
    #[test]
    fn kandidaten_laufen_nach_konfidenz_absteigend() {
        let list = vec![
            candidate(0.7, 1),
            candidate(0.9, 2),
            candidate(0.8, 3),
            candidate(0.9, 4),
        ];
        let ordered: Vec<i64> = by_descending_confidence(&list)
            .iter()
            .filter_map(|c| c.trigger_backend_id)
            .collect();
        // 0.9 zuerst, in Erkennungsreihenfolge; dann 0.8, dann 0.7.
        assert_eq!(ordered, vec![2, 4, 3, 1]);
    }

    #[test]
    fn basic_mode_excludes_full_only_journeys() {
        assert!(journey_allowed(
            InteractiveMode::Basic,
            JourneyKind::SkipLinkActivate
        ));
        assert!(journey_allowed(
            InteractiveMode::Basic,
            JourneyKind::ModalOpen
        ));
        assert!(!journey_allowed(
            InteractiveMode::Basic,
            JourneyKind::FormErrorSubmit
        ));
    }

    #[test]
    fn full_mode_allows_full_scope_journeys() {
        assert!(journey_allowed(
            InteractiveMode::Full,
            JourneyKind::FormErrorSubmit
        ));
    }

    #[test]
    fn compact_focus_evidence_is_part_of_public_journey_json() {
        let journey = crate::audit::normalized::AccessibilityJourney {
            execution: crate::audit::normalized::JourneyExecution {
                mode: "basic".to_string(),
                budget_ms: 1_000,
                candidates_detected: 1,
                attempted: 1,
                completed: 1,
                ..Default::default()
            },
            traces: Vec::new(),
            focus_evidence: vec![crate::accessibility::FocusSnapshot {
                selector: Some("#submit".to_string()),
                visible: true,
                in_viewport: true,
                focus_indicator: Some(crate::accessibility::FocusIndicatorStatus::Detected),
                ..Default::default()
            }],
        };

        let value = serde_json::to_value(journey).unwrap();
        assert_eq!(value["execution"]["completed"], 1);
        assert_eq!(value["focus_evidence"][0]["selector"], "#submit");
        assert_eq!(value["focus_evidence"][0]["visible"], true);
    }
}