-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWCAG_Site_PDF_Scanner.py
More file actions
8524 lines (7552 loc) · 451 KB
/
Copy pathWCAG_Site_PDF_Scanner.py
File metadata and controls
8524 lines (7552 loc) · 451 KB
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""WCAG 2.2 Site and PDF Scanner.
One-file accessibility assurance toolkit for websites, local HTML, and PDF
documents. Automated results are evidence for an accessibility review. They
are not, by themselves, a WCAG or PDF/UA conformance determination.
"""
import asyncio
import csv
import difflib
import hashlib
import html as html_lib
import importlib.metadata
import inspect
import io
import ipaddress
import json
import socket
import stat
import logging
import os
import platform
import re
import secrets
import shutil
# Subprocess execution is limited to this script through the current interpreter.
import subprocess # nosec B404
import sys
import tempfile
import time
import warnings
from contextlib import asynccontextmanager
from collections import Counter, defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import asdict, dataclass, field, replace
from datetime import datetime, timezone
from enum import Enum
from pathlib import Path
from typing import Any, DefaultDict, Dict, Iterable, List, Optional, Set, Tuple, Union
from urllib.parse import unquote, urldefrag, urljoin, urlparse
from urllib.request import url2pathname
from urllib.robotparser import RobotFileParser
import aiohttp
from bs4 import BeautifulSoup, Tag
import click
import cssutils
from cssutils.css import CSSStyleRule, Property
from defusedxml import ElementTree as SafeET
try:
from playwright.async_api import Browser, Error as PlaywrightError, Page, Playwright, async_playwright
PLAYWRIGHT_READY = True
except ImportError:
Browser = Page = Playwright = Any
class PlaywrightError(Exception):
"""Fallback exception when Playwright is unavailable."""
async_playwright = None
PLAYWRIGHT_READY = False
import questionary
from rich.console import Console
from rich.panel import Panel
from rich.progress import (
BarColumn,
MofNCompleteColumn,
Progress,
SpinnerColumn,
TextColumn,
TimeElapsedColumn,
)
from rich.prompt import Confirm
from rich.syntax import Syntax
from rich.table import Table
warnings.filterwarnings("ignore", category=UserWarning, message="pkg_resources is deprecated as an API.")
# Ensure UTF-8 console output everywhere (rich emits ✓/✗ and box-drawing chars that crash on a
# Windows cp1252 console when output is redirected, piped, or run in CI/--ci-mode).
for _stream in (sys.stdout, sys.stderr):
try:
_stream.reconfigure(encoding="utf-8")
# Console encoding is optional, so a best-effort failure is safe to ignore.
except Exception: # noqa: S112 # nosec B112
continue
################################################################################
# BEGIN core.py
# ==============================================================================
# ENUMS AND CONSTANTS
# ==============================================================================
class WCAGLevel(Enum):
A = "A"
AA = "AA"
AAA = "AAA"
def __le__(self, other):
if self.__class__ is other.__class__:
order = list(WCAGLevel)
return order.index(self) <= order.index(other)
return NotImplemented
def __lt__(self, other):
if self.__class__ is other.__class__:
order = list(WCAGLevel)
return order.index(self) < order.index(other)
return NotImplemented
def __ge__(self, other):
if self.__class__ is other.__class__:
order = list(WCAGLevel)
return order.index(self) >= order.index(other)
return NotImplemented
def __gt__(self, other):
if self.__class__ is other.__class__:
order = list(WCAGLevel)
return order.index(self) > order.index(other)
return NotImplemented
class IssueSeverity(Enum):
CRITICAL = "Critical"
SERIOUS = "Serious"
MODERATE = "Moderate"
MINOR = "Minor"
INFO = "Informational"
class FixType(Enum):
AUTOMATIC = "Automatic"
SEMI_AUTOMATIC = "Semi-Automatic"
MANUAL = "Manual"
class AnalysisMode(Enum):
CRAWLER = "Crawler"
STATIC = "Static"
DYNAMIC = "Dynamic"
AXE = "Axe-core"
CONTENT = "Content-NLP"
CSS = "CSS"
CONSISTENCY = "Cross-Page"
VALIDATION = "Validation"
SPELLING = "Spelling"
# ARIA Constants (Expanded for more comprehensive checks)
VALID_ARIA_ROLES = {
"alert", "alertdialog", "application", "article", "banner", "button", "cell", "checkbox", "columnheader",
"combobox", "complementary", "contentinfo", "definition", "dialog", "directory", "document", "feed", "figure",
"form", "grid", "gridcell", "group", "heading", "img", "link", "list", "listbox", "listitem", "log", "main",
"marquee", "math", "menu", "menubar", "menuitem", "menuitemcheckbox", "menuitemradio", "navigation", "none",
"note", "option", "presentation", "progressbar", "radio", "radiogroup", "region", "row", "rowgroup",
"rowheader", "scrollbar", "search", "searchbox", "separator", "slider", "spinbutton", "status", "switch",
"tab", "table", "tablist", "tabpanel", "term", "textbox", "timer", "toolbar", "tooltip", "tree", "treegrid", "treeitem"
}
VALID_ARIA_PROPS = {
"aria-activedescendant", "aria-atomic", "aria-autocomplete", "aria-busy", "aria-checked", "aria-colcount",
"aria-colindex", "aria-colspan", "aria-controls", "aria-current", "aria-describedby", "aria-details",
"aria-disabled", "aria-dropeffect", "aria-errormessage", "aria-expanded", "aria-flowto", "aria-grabbed",
"aria-haspopup", "aria-hidden", "aria-invalid", "aria-keyshortcuts", "aria-label", "aria-labelledby",
"aria-level", "aria-live", "aria-modal", "aria-multiline", "aria-multiselectable", "aria-orientation",
"aria-owns", "aria-placeholder", "aria-posinset", "aria-pressed", "aria-readonly", "aria-relevant",
"aria-required", "aria-roledescription", "aria-rowcount", "aria-rowindex", "aria-rowspan", "aria-selected",
"aria-setsize", "aria-sort", "aria-valuemax", "aria-valuemin", "aria-valuenow", "aria-valuetext"
}
# Mapping of ARIA roles to required attributes
ARIA_REQUIRED_PROPS = {
"checkbox": ["aria-checked"],
"combobox": ["aria-controls", "aria-expanded"],
"grid": ["aria-readonly"],
"gridcell": [],
"listbox": [],
"menuitemcheckbox": ["aria-checked"],
"menuitemradio": ["aria-checked"],
"progressbar": ["aria-valuemin", "aria-valuemax", "aria-valuenow"],
"radio": ["aria-checked"],
"radiogroup": [],
"slider": ["aria-valuemin", "aria-valuemax", "aria-valuenow"],
"spinbutton": ["aria-valuemin", "aria-valuemax", "aria-valuenow"],
"switch": ["aria-checked"],
"tab": ["aria-selected"],
"tablist": [],
"tabpanel": ["aria-labelledby"],
"textbox": [],
"treeitem": ["aria-expanded"],
"alertdialog": ["aria-modal", "aria-label", "aria-labelledby"]
}
# ==============================================================================
# DATA STRUCTURES
# ==============================================================================
@dataclass
class AccessibilityIssue:
criterion: str
criterion_name: str
level: WCAGLevel
severity: IssueSeverity
mode: AnalysisMode
description: str
impact: str
element: Optional[str] = None
element_html: Optional[str] = None
context_html: Optional[str] = None
selector: Optional[str] = None
fix_type: FixType = FixType.MANUAL
suggested_fix: Optional[str] = None
file_path: Optional[str] = None
url: Optional[str] = None
line_number: Optional[int] = None
col_number: Optional[int] = None
screenshot_path: Optional[str] = None
additional_info: Dict[str, Any] = field(default_factory=dict)
fixed: bool = False
fix_applied: Optional[str] = None
issue_hash: str = field(init=False)
def __post_init__(self):
# Create a stable hash for duplicate detection and tracking fixes
import hashlib
unique_str = f"{self.criterion}{self.url or self.file_path}{self.selector or self.element_html}{self.description}"
self.issue_hash = hashlib.sha256(unique_str.encode('utf-8')).hexdigest()[:16]
@dataclass
class PassedCheck:
criterion: str
criterion_name: str
level: WCAGLevel
mode: AnalysisMode
description: str
elements_checked: int = 0
file_path: Optional[str] = None
url: Optional[str] = None
details: Optional[str] = None
@dataclass
class AccessibilityReport:
target: str
timestamp: str = field(default_factory=lambda: datetime.now().isoformat())
wcag_level_tested: WCAGLevel = WCAGLevel.AA
issues: List[AccessibilityIssue] = field(default_factory=list)
passed_checks: List[PassedCheck] = field(default_factory=list)
all_files_analyzed: Set[str] = field(default_factory=set)
all_urls_crawled: Set[str] = field(default_factory=set)
broken_links: DefaultDict[str, Set[str]] = field(default_factory=lambda: defaultdict(set))
fixes_applied: DefaultDict[str, List[Dict[str, Any]]] = field(default_factory=lambda: defaultdict(list))
analysis_duration: float = 0.0
summary: Dict[str, Any] = field(default_factory=dict)
screenshot_dir: Optional[Path] = None
def reconcile_results(self):
"""Remove criterion-level pass records contradicted by findings.
The legacy analyzers record successful narrow checks independently.
A page can therefore have both a failure and a pass for the same WCAG
criterion. Until every rule has its own atomic identifier, suppress the
contradictory pass so reports never imply criterion conformance.
"""
failed = {
(issue.criterion, issue.url or issue.file_path or "")
for issue in self.issues
if not issue.fixed
}
self.passed_checks = [
check for check in self.passed_checks
if (check.criterion, check.url or check.file_path or "") not in failed
]
def compile_summary(self):
self.reconcile_results()
# Ensures all sets are converted to lists for JSON serialization later down
self.summary = {
"target": self.target,
"timestamp": self.timestamp,
"wcag_level_tested": self.wcag_level_tested.value,
"analysis_duration_seconds": round(self.analysis_duration, 2),
"total_urls_crawled": len(self.all_urls_crawled),
"total_files_analyzed": len(self.all_files_analyzed),
"total_issues": len(self.issues),
"total_passed_checks": len(self.passed_checks),
"passed_check_scope": "Narrow automated checks with no detected failure; not criterion conformance",
"total_broken_links": sum(len(pages) for pages in self.broken_links.values()),
"issues_by_severity": {
sev.value: len([i for i in self.issues if i.severity == sev]) for sev in IssueSeverity
},
"issues_by_level": {
lvl.value: len([i for i in self.issues if i.level == lvl]) for lvl in WCAGLevel
},
"issues_fixed": len([i for i in self.issues if i.fixed]),
"issues_by_mode": {
mode.value: len([i for i in self.issues if i.mode == mode]) for mode in AnalysisMode
},
"broken_links_by_target": {k: list(v) for k, v in self.broken_links.items()} if self.broken_links else {},
}
# Clean up empty categories for cleaner summary
self.summary["issues_by_severity"] = {k: v for k, v in self.summary["issues_by_severity"].items() if v > 0}
self.summary["issues_by_level"] = {k: v for k, v in self.summary["issues_by_level"].items() if v > 0}
self.summary["issues_by_mode"] = {k: v for k, v in self.summary["issues_by_mode"].items() if v > 0}
# ==============================================================================
# WCAG 2.2 CRITERIA DATABASE
# ==============================================================================
WCAG_CRITERIA_DATABASE: Dict[str, Dict[str, Any]] = {
# Principle 1: Perceivable
"1.1.1": {"name": "Non-text Content", "level": WCAGLevel.A, "url": "https://www.w3.org/WAI/WCAG22/Understanding/non-text-content.html", "fix_type": FixType.SEMI_AUTOMATIC, "severity": IssueSeverity.CRITICAL},
"1.2.1": {"name": "Audio-only and Video-only (Prerecorded)", "level": WCAGLevel.A, "url": "https://www.w3.org/WAI/WCAG22/Understanding/audio-only-and-video-only-prerecorded.html"},
"1.2.2": {"name": "Captions (Prerecorded)", "level": WCAGLevel.A, "url": "https://www.w3.org/WAI/WCAG22/Understanding/captions-prerecorded.html"},
"1.2.3": {"name": "Audio Description or Media Alternative (Prerecorded)", "level": WCAGLevel.A, "url": "https://www.w3.org/WAI/WCAG22/Understanding/audio-description-or-media-alternative-prerecorded.html"},
"1.2.4": {"name": "Captions (Live)", "level": WCAGLevel.AA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/captions-live.html"},
"1.2.5": {"name": "Audio Description (Prerecorded)", "level": WCAGLevel.AA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/audio-description-prerecorded.html"},
"1.3.1": {"name": "Info and Relationships", "level": WCAGLevel.A, "url": "https://www.w3.org/WAI/WCAG22/Understanding/info-and-relationships.html", "fix_type": FixType.MANUAL, "severity": IssueSeverity.SERIOUS},
"1.3.2": {"name": "Meaningful Sequence", "level": WCAGLevel.A, "url": "https://www.w3.org/WAI/WCAG22/Understanding/meaningful-sequence.html"},
"1.3.3": {"name": "Sensory Characteristics", "level": WCAGLevel.A, "url": "https://www.w3.org/WAI/WCAG22/Understanding/sensory-characteristics.html"},
"1.3.4": {"name": "Orientation", "level": WCAGLevel.AA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/orientation.html"},
"1.3.5": {"name": "Identify Input Purpose", "level": WCAGLevel.AA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/identify-input-purpose.html", "fix_type": FixType.SEMI_AUTOMATIC, "severity": IssueSeverity.MODERATE},
"1.4.1": {"name": "Use of Color", "level": WCAGLevel.A, "url": "https://www.w3.org/WAI/WCAG22/Understanding/use-of-color.html"},
"1.4.2": {"name": "Audio Control", "level": WCAGLevel.A, "url": "https://www.w3.org/WAI/WCAG22/Understanding/audio-control.html"},
"1.4.3": {"name": "Contrast (Minimum)", "level": WCAGLevel.AA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/contrast-minimum.html", "fix_type": FixType.MANUAL, "severity": IssueSeverity.CRITICAL},
"1.4.4": {"name": "Resize text", "level": WCAGLevel.AA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/resize-text.html"},
"1.4.5": {"name": "Images of Text", "level": WCAGLevel.AA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/images-of-text.html"},
"1.4.10": {"name": "Reflow", "level": WCAGLevel.AA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/reflow.html", "fix_type": FixType.MANUAL, "severity": IssueSeverity.SERIOUS},
"1.4.11": {"name": "Non-text Contrast", "level": WCAGLevel.AA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/non-text-contrast.html", "fix_type": FixType.MANUAL, "severity": IssueSeverity.CRITICAL},
"1.4.12": {"name": "Text Spacing", "level": WCAGLevel.AA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/text-spacing.html", "fix_type": FixType.MANUAL, "severity": IssueSeverity.MODERATE},
"1.4.13": {"name": "Content on Hover or Focus", "level": WCAGLevel.AA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/content-on-hover-or-focus.html", "fix_type": FixType.MANUAL, "severity": IssueSeverity.SERIOUS},
# Principle 2: Operable
"2.1.1": {"name": "Keyboard", "level": WCAGLevel.A, "url": "https://www.w3.org/WAI/WCAG22/Understanding/keyboard.html", "fix_type": FixType.MANUAL, "severity": IssueSeverity.CRITICAL},
"2.1.2": {"name": "No Keyboard Trap", "level": WCAGLevel.A, "url": "https://www.w3.org/WAI/WCAG22/Understanding/no-keyboard-trap.html", "fix_type": FixType.MANUAL, "severity": IssueSeverity.CRITICAL},
"2.1.4": {"name": "Character Key Shortcuts", "level": WCAGLevel.A, "url": "https://www.w3.org/WAI/WCAG22/Understanding/character-key-shortcuts.html"},
"2.2.1": {"name": "Timing Adjustable", "level": WCAGLevel.A, "url": "https://www.w3.org/WAI/WCAG22/Understanding/timing-adjustable.html"},
"2.2.2": {"name": "Pause, Stop, Hide", "level": WCAGLevel.A, "url": "https://www.w3.org/WAI/WCAG22/Understanding/pause-stop-hide.html"},
"2.3.1": {"name": "Three Flashes or Below Threshold", "level": WCAGLevel.A, "url": "https://www.w3.org/WAI/WCAG22/Understanding/three-flashes-or-below-threshold.html"},
"2.4.1": {"name": "Bypass Blocks", "level": WCAGLevel.A, "url": "https://www.w3.org/WAI/WCAG22/Understanding/bypass-blocks.html", "fix_type": FixType.SEMI_AUTOMATIC, "severity": IssueSeverity.SERIOUS},
"2.4.2": {"name": "Page Titled", "level": WCAGLevel.A, "url": "https://www.w3.org/WAI/WCAG22/Understanding/page-titled.html", "fix_type": FixType.SEMI_AUTOMATIC, "severity": IssueSeverity.CRITICAL},
"2.4.3": {"name": "Focus Order", "level": WCAGLevel.A, "url": "https://www.w3.org/WAI/WCAG22/Understanding/focus-order.html"},
"2.4.4": {"name": "Link Purpose (In Context)", "level": WCAGLevel.A, "url": "https://www.w3.org/WAI/WCAG22/Understanding/link-purpose-in-context.html", "fix_type": FixType.MANUAL, "severity": IssueSeverity.SERIOUS},
"2.4.5": {"name": "Multiple Ways", "level": WCAGLevel.AA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/multiple-ways.html"},
"2.4.6": {"name": "Headings and Labels", "level": WCAGLevel.AA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/headings-and-labels.html", "fix_type": FixType.SEMI_AUTOMATIC, "severity": IssueSeverity.SERIOUS},
"2.4.7": {"name": "Focus Visible", "level": WCAGLevel.AA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/focus-visible.html", "fix_type": FixType.MANUAL, "severity": IssueSeverity.SERIOUS},
"2.4.11": {"name": "Focus Not Obscured (Minimum)", "level": WCAGLevel.AA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/focus-not-obscured-minimum.html", "fix_type": FixType.MANUAL, "severity": IssueSeverity.SERIOUS},
"2.4.12": {"name": "Focus Not Obscured (Enhanced)", "level": WCAGLevel.AAA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/focus-not-obscured-enhanced.html", "fix_type": FixType.MANUAL, "severity": IssueSeverity.SERIOUS},
"2.5.1": {"name": "Pointer Gestures", "level": WCAGLevel.A, "url": "https://www.w3.org/WAI/WCAG22/Understanding/pointer-gestures.html"},
"2.5.2": {"name": "Pointer Cancellation", "level": WCAGLevel.A, "url": "https://www.w3.org/WAI/WCAG22/Understanding/pointer-cancellation.html"},
"2.5.3": {"name": "Label in Name", "level": WCAGLevel.A, "url": "https://www.w3.org/WAI/WCAG22/Understanding/label-in-name.html"},
"2.5.4": {"name": "Motion Actuation", "level": WCAGLevel.A, "url": "https://www.w3.org/WAI/WCAG22/Understanding/motion-actuation.html"},
"2.5.7": {"name": "Dragging Movements", "level": WCAGLevel.AA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/dragging-movements.html"},
"2.5.8": {"name": "Target Size (Minimum)", "level": WCAGLevel.AA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/target-size-minimum.html", "fix_type": FixType.MANUAL, "severity": IssueSeverity.MODERATE},
# Principle 3: Understandable
"3.1.1": {"name": "Language of Page", "level": WCAGLevel.A, "url": "https://www.w3.org/WAI/WCAG22/Understanding/language-of-page.html", "fix_type": FixType.SEMI_AUTOMATIC, "severity": IssueSeverity.CRITICAL},
"3.1.2": {"name": "Language of Parts", "level": WCAGLevel.AA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/language-of-parts.html", "fix_type": FixType.MANUAL, "severity": IssueSeverity.MODERATE},
"3.1.3": {"name": "Unusual Words", "level": WCAGLevel.AAA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/unusual-words.html", "fix_type": FixType.MANUAL, "severity": IssueSeverity.MINOR},
"3.1.4": {"name": "Abbreviations", "level": WCAGLevel.AAA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/abbreviations.html", "fix_type": FixType.MANUAL, "severity": IssueSeverity.MINOR},
"3.1.5": {"name": "Reading Level", "level": WCAGLevel.AAA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/reading-level.html", "fix_type": FixType.MANUAL, "severity": IssueSeverity.MODERATE},
"3.2.1": {"name": "On Focus", "level": WCAGLevel.A, "url": "https://www.w3.org/WAI/WCAG22/Understanding/on-focus.html"},
"3.2.2": {"name": "On Input", "level": WCAGLevel.A, "url": "https://www.w3.org/WAI/WCAG22/Understanding/on-input.html"},
"3.2.3": {"name": "Consistent Navigation", "level": WCAGLevel.AA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/consistent-navigation.html"},
"3.2.4": {"name": "Consistent Identification", "level": WCAGLevel.AA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/consistent-identification.html"},
"3.3.1": {"name": "Error Identification", "level": WCAGLevel.A, "url": "https://www.w3.org/WAI/WCAG22/Understanding/error-identification.html", "fix_type": FixType.MANUAL, "severity": IssueSeverity.MODERATE},
"3.3.2": {"name": "Labels or Instructions", "level": WCAGLevel.A, "url": "https://www.w3.org/WAI/WCAG22/Understanding/labels-or-instructions.html", "fix_type": FixType.SEMI_AUTOMATIC, "severity": IssueSeverity.CRITICAL},
"3.3.3": {"name": "Error Suggestion", "level": WCAGLevel.AA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/error-suggestion.html"},
"3.3.4": {"name": "Error Prevention (Legal, Financial, Data)", "level": WCAGLevel.AA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/error-prevention-legal-financial-data.html"},
"3.3.7": {"name": "Redundant Entry", "level": WCAGLevel.A, "url": "https://www.w3.org/WAI/WCAG22/Understanding/redundant-entry.html"},
"3.3.8": {"name": "Accessible Authentication (Minimum)", "level": WCAGLevel.AA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/accessible-authentication-minimum.html"},
# Principle 4: Robust
"4.1.2": {"name": "Name, Role, Value", "level": WCAGLevel.A, "url": "https://www.w3.org/WAI/WCAG22/Understanding/name-role-value.html", "fix_type": FixType.MANUAL, "severity": IssueSeverity.SERIOUS},
"4.1.3": {"name": "Status Messages", "level": WCAGLevel.AA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/status-messages.html", "fix_type": FixType.MANUAL, "severity": IssueSeverity.SERIOUS},
# WCAG 2.2 New Criteria
"2.4.13": {"name": "Focus Appearance", "level": WCAGLevel.AAA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/focus-appearance.html", "fix_type": FixType.MANUAL, "severity": IssueSeverity.MODERATE},
"2.5.5": {"name": "Target Size (Enhanced)", "level": WCAGLevel.AAA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/target-size-enhanced.html", "fix_type": FixType.MANUAL, "severity": IssueSeverity.MODERATE},
"2.5.6": {"name": "Concurrent Input Mechanisms", "level": WCAGLevel.AAA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/concurrent-input-mechanisms.html", "fix_type": FixType.MANUAL, "severity": IssueSeverity.MODERATE},
"3.2.6": {"name": "Consistent Help", "level": WCAGLevel.A, "url": "https://www.w3.org/WAI/WCAG22/Understanding/consistent-help.html", "fix_type": FixType.MANUAL, "severity": IssueSeverity.MODERATE},
"3.3.9": {"name": "Accessible Authentication (Enhanced)", "level": WCAGLevel.AAA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/accessible-authentication-enhanced.html", "fix_type": FixType.MANUAL, "severity": IssueSeverity.SERIOUS},
# Previously missing AAA criteria
"1.2.6": {"name": "Sign Language (Prerecorded)", "level": WCAGLevel.AAA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/sign-language-prerecorded.html"},
"1.2.7": {"name": "Extended Audio Description (Prerecorded)", "level": WCAGLevel.AAA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/extended-audio-description-prerecorded.html"},
"1.2.8": {"name": "Media Alternative (Prerecorded)", "level": WCAGLevel.AAA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/media-alternative-prerecorded.html"},
"1.2.9": {"name": "Audio-only (Live)", "level": WCAGLevel.AAA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/audio-only-live.html"},
"1.3.6": {"name": "Identify Purpose", "level": WCAGLevel.AAA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/identify-purpose.html"},
"1.4.6": {"name": "Contrast (Enhanced)", "level": WCAGLevel.AAA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/contrast-enhanced.html", "fix_type": FixType.MANUAL, "severity": IssueSeverity.SERIOUS},
"1.4.7": {"name": "Low or No Background Audio", "level": WCAGLevel.AAA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/low-or-no-background-audio.html"},
"1.4.8": {"name": "Visual Presentation", "level": WCAGLevel.AAA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/visual-presentation.html"},
"1.4.9": {"name": "Images of Text (No Exception)", "level": WCAGLevel.AAA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/images-of-text-no-exception.html"},
"2.1.3": {"name": "Keyboard (No Exception)", "level": WCAGLevel.AAA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/keyboard-no-exception.html"},
"2.2.3": {"name": "No Timing", "level": WCAGLevel.AAA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/no-timing.html"},
"2.2.4": {"name": "Interruptions", "level": WCAGLevel.AAA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/interruptions.html"},
"2.2.5": {"name": "Re-authenticating", "level": WCAGLevel.AAA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/re-authenticating.html"},
"2.2.6": {"name": "Timeouts", "level": WCAGLevel.AAA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/timeouts.html"},
"2.3.2": {"name": "Three Flashes", "level": WCAGLevel.AAA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/three-flashes.html"},
"2.3.3": {"name": "Animation from Interactions", "level": WCAGLevel.AAA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/animation-from-interactions.html"},
"2.4.8": {"name": "Location", "level": WCAGLevel.AAA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/location.html"},
"2.4.9": {"name": "Link Purpose (Link Only)", "level": WCAGLevel.AAA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/link-purpose-link-only.html"},
"2.4.10": {"name": "Section Headings", "level": WCAGLevel.AAA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/section-headings.html"},
"3.1.6": {"name": "Pronunciation", "level": WCAGLevel.AAA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/pronunciation.html"},
"3.2.5": {"name": "Change on Request", "level": WCAGLevel.AAA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/change-on-request.html"},
"3.3.5": {"name": "Help", "level": WCAGLevel.AAA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/help.html"},
"3.3.6": {"name": "Error Prevention (All)", "level": WCAGLevel.AAA, "url": "https://www.w3.org/WAI/WCAG22/Understanding/error-prevention-all.html"},
# Custom/Informational Criteria
"HTML5_SEMANTICS": {"name": "HTML5 Semantic Elements", "level": WCAGLevel.A, "url": "#", "fix_type": FixType.MANUAL, "severity": IssueSeverity.INFO},
"CSS_ANALYSIS": {"name": "CSS Rule Analysis", "level": WCAGLevel.AA, "url": "#", "fix_type": FixType.MANUAL, "severity": IssueSeverity.INFO},
"HTML_VALIDATION": {"name": "HTML Validation (Standards)", "level": WCAGLevel.A, "url": "https://validator.w3.org/", "fix_type": FixType.MANUAL, "severity": IssueSeverity.MINOR},
"CSS_VALIDATION": {"name": "CSS Validation (Standards)", "level": WCAGLevel.A, "url": "https://jigsaw.w3.org/css-validator/", "fix_type": FixType.MANUAL, "severity": IssueSeverity.MINOR},
"SPELLING": {"name": "Spelling", "level": WCAGLevel.A, "url": "#", "fix_type": FixType.MANUAL, "severity": IssueSeverity.MINOR},
"AXE_PASSED_GENERIC": {"name": "Axe-core Passed Rule", "level": WCAGLevel.AA, "url": "#", "fix_type": FixType.MANUAL, "severity": IssueSeverity.INFO},
"INFO_CONTENT": {"name": "Content Analysis Info", "level": WCAGLevel.AAA, "url": "#", "fix_type": FixType.MANUAL, "severity": IssueSeverity.INFO},
"UNKNOWN": {"name": "Unknown or General Accessibility Issue", "level": WCAGLevel.A, "url": "#", "fix_type": FixType.MANUAL, "severity": IssueSeverity.INFO},
}
# ==============================================================================
# UTILITY FUNCTIONS
# ==============================================================================
def get_criterion_details(criterion_id: str) -> Dict[str, Any]:
"""Get details for a WCAG criterion ID."""
return WCAG_CRITERIA_DATABASE.get(criterion_id, WCAG_CRITERIA_DATABASE["UNKNOWN"])
# Section 508 (2017 Refresh) incorporates WCAG 2.0 Level A & AA by reference.
# These are the WCAG 2.0 A/AA success criteria; 2.1/2.2-only criteria are not formally part of 508.
SECTION_508_WCAG20 = {
"1.1.1", "1.2.1", "1.2.2", "1.2.3", "1.3.1", "1.3.2", "1.3.3", "1.4.1", "1.4.2",
"2.1.1", "2.1.2", "2.2.1", "2.2.2", "2.3.1", "2.4.1", "2.4.2", "2.4.3", "2.4.4",
"3.1.1", "3.2.1", "3.2.2", "3.3.1", "3.3.2", "4.1.2",
"1.2.4", "1.2.5", "1.4.3", "1.4.4", "1.4.5", "2.4.5", "2.4.6", "2.4.7",
"3.1.2", "3.2.3", "3.2.4", "3.3.3", "3.3.4",
}
def is_section_508(criterion: str) -> bool:
"""True if the criterion is part of WCAG 2.0 A/AA (referenced by the Section 508 2017 Refresh)."""
return criterion in SECTION_508_WCAG20
# ==============================================================================
# SECURITY HELPERS (output encoding, SSRF guard, resource limits)
# ==============================================================================
MAX_RESPONSE_BYTES = 10 * 1024 * 1024
MAX_SITEMAP_BYTES = 5 * 1024 * 1024
MAX_BROWSER_DOM_BYTES = 20 * 1024 * 1024
MAX_URL_LENGTH = 8192
DEFAULT_MAX_PDF_PAGES = 10000
DEFAULT_MAX_PDF_DOCUMENTS = 10000
def _safe_url(url, allow_relative: bool = True) -> str:
"""Return url only if it uses a safe scheme for a report link; else '#'.
Blocks javascript:/data:/vbscript:/file: (XSS / local-file vectors), finding F1.
"""
if not url:
return "#"
u = str(url).strip()
if len(u) > MAX_URL_LENGTH or re.search(r'[\x00-\x1f\x7f]', u):
return "#"
low = re.sub(r'[\s\x00-\x1f]', '', u.lower()) # defeat whitespace/control-char smuggling
if low.startswith(('javascript:', 'data:', 'vbscript:', 'file:')):
return "#"
if low.startswith(('http://', 'https://', 'mailto:', 'tel:')):
return u
if allow_relative and (u[:1] in ('/', '#', '?', '.') or ':' not in u.split('/', 1)[0]):
return u # relative path / fragment
return "#"
def _csv_safe(value):
"""Neutralize CSV formula/macro injection (CWE-1236), finding F2."""
if isinstance(value, str) and value[:1] in ('=', '+', '-', '@', '\t', '\r'):
return "'" + value
return value
def _safe_filename(name, maxlen: int = 80) -> str:
"""Reduce an arbitrary string to a filesystem-safe token (no path traversal), finding F7."""
cleaned = re.sub(r'[^A-Za-z0-9._-]', '-', str(name)).lstrip('.')
return (cleaned or 'x')[:maxlen]
def _md_cell(text) -> str:
"""Escape a value for safe inclusion in a Markdown table cell, finding F8."""
s = str(text if text is not None else '').replace('\n', ' ').replace('\r', ' ')
s = s.replace('|', '\\|').replace('`', '\\`').replace('<', '<').replace('>', '>')
return ('\\' + s) if s[:1] in ('=', '+', '@') else s
def _ip_is_blocked(ip_str: str, allow_private: bool) -> bool:
"""True if an IP should not be connected to (SSRF guard), finding F5."""
try:
ip = ipaddress.ip_address(ip_str)
except ValueError:
return False
metadata_addresses = {
ipaddress.ip_address('169.254.169.254'),
ipaddress.ip_address('100.100.100.200'),
ipaddress.ip_address('fd00:ec2::254'),
}
if ip in metadata_addresses:
return True
if ip.is_link_local or ip.is_multicast or ip.is_reserved or ip.is_unspecified:
return True
if not allow_private and (ip.is_private or ip.is_loopback):
return True
return False
try:
from aiohttp.abc import AbstractResolver as _AbstractResolver
from aiohttp.resolver import ThreadedResolver as _ThreadedResolver
_RESOLVER_OK = True
except Exception:
_AbstractResolver, _ThreadedResolver, _RESOLVER_OK = object, None, False
class _SafeResolver(_AbstractResolver):
"""aiohttp resolver that refuses non-public IPs and also catches redirect hops."""
def __init__(self, allow_private: bool = False):
self._base = _ThreadedResolver()
self.allow_private = allow_private
async def resolve(self, host, port=0, family=socket.AF_INET):
infos = await self._base.resolve(host, port, family)
for info in infos:
if _ip_is_blocked(info['host'], self.allow_private):
raise OSError(f"Blocked connection to non-public address {info['host']} (host '{host}')")
return infos
async def close(self):
await self._base.close()
def _safe_connector(allow_private: bool = False, **kwargs) -> "aiohttp.TCPConnector":
"""Build a TLS-verifying connector with the SSRF resolver attached (when available)."""
if _RESOLVER_OK:
return aiohttp.TCPConnector(resolver=_SafeResolver(allow_private), ssl=True, **kwargs)
return aiohttp.TCPConnector(ssl=True, **kwargs)
async def _assert_safe_destination(url: str, allow_private: bool = False) -> None:
"""Reject unsafe schemes, credentials, IP literals, and resolved addresses."""
if not url or len(str(url)) > MAX_URL_LENGTH or re.search(r'[\x00-\x20]', str(url)):
raise ValueError("URL is empty, too long, or contains control characters")
parsed = urlparse(str(url))
if parsed.scheme not in {'http', 'https'} or not parsed.hostname:
raise ValueError("Only HTTP and HTTPS URLs with a hostname are accepted")
if parsed.username or parsed.password:
raise ValueError("Credentials are not allowed in URLs")
try:
port = parsed.port or (443 if parsed.scheme == 'https' else 80)
except ValueError as exc:
raise ValueError("URL contains an invalid port") from exc
if not 1 <= port <= 65535:
raise ValueError("URL contains an invalid port")
hostname = parsed.hostname
try:
addresses = [str(ipaddress.ip_address(hostname))]
except ValueError:
try:
infos = await asyncio.wait_for(
asyncio.to_thread(socket.getaddrinfo, hostname, port, type=socket.SOCK_STREAM),
timeout=5,
)
except Exception as exc:
raise OSError(f"Could not safely resolve host '{hostname}': {exc}") from exc
addresses = sorted({info[4][0] for info in infos})
if not addresses:
raise OSError(f"Host '{hostname}' resolved to no addresses")
blocked = [address for address in addresses if _ip_is_blocked(address, allow_private)]
if blocked:
raise OSError(f"Blocked connection to non-public or protected address for host '{hostname}'")
@asynccontextmanager
async def _safe_get(
session: aiohttp.ClientSession,
url: str,
*,
allow_private: bool = False,
max_redirects: int = 5,
**kwargs,
):
"""Issue a GET with explicit validation before every redirect hop."""
current = str(url)
response = None
try:
for hop in range(max_redirects + 1):
await _assert_safe_destination(current, allow_private)
response = await session.get(current, allow_redirects=False, **kwargs)
if response.status not in {301, 302, 303, 307, 308}:
yield response
return
if hop >= max_redirects:
raise ValueError("Request exceeded the redirect limit")
location = response.headers.get('Location')
response.release()
response = None
if not location:
raise ValueError("Redirect has no Location header")
current = urljoin(current, location)
raise ValueError("Request could not be completed")
finally:
if response is not None:
response.release()
async def _read_capped_bytes(resp, max_bytes: int = MAX_RESPONSE_BYTES) -> bytes:
"""Read a response body and reject content over the limit."""
if resp.content_length and resp.content_length > max_bytes:
raise ValueError(f"Response exceeds the {max_bytes}-byte safety limit")
chunks: List[bytes] = []
total = 0
async for chunk in resp.content.iter_chunked(64 * 1024):
total += len(chunk)
if total > max_bytes:
raise ValueError(f"Response exceeds the {max_bytes}-byte safety limit")
chunks.append(chunk)
return b''.join(chunks)
async def _read_capped_text(resp, max_bytes: int = MAX_RESPONSE_BYTES) -> str:
"""Read and decode a response body, rejecting content over the limit."""
raw = await _read_capped_bytes(resp, max_bytes)
enc = resp.charset or 'utf-8'
try:
return raw.decode(enc, errors='ignore')
except (LookupError, TypeError):
return raw.decode('utf-8', errors='ignore')
def _enum_value_safe(v):
"""Safely get enum value for serialization."""
try:
return v.value
except Exception:
return v
def generate_css_selector(element: Tag) -> str:
"""Generates a robust CSS selector for a BeautifulSoup Tag object."""
if not isinstance(element, Tag):
return ""
path = []
current = element
while current and current.name and current.parent and current.name != '[document]':
selector = current.name
if current.has_attr('id') and current['id']:
element_id = current['id'] if isinstance(current['id'], str) else ' '.join(current['id'])
# Ensure ID is valid for CSS selector and doesn't contain spaces or special chars
if re.match(r"^[a-zA-Z_][\w-]*$", element_id):
selector = f"#{element_id}"
path.append(selector)
break # ID is unique enough
classes = sorted([
c for c in current.get('class', [])
if c and isinstance(c, str) and re.match(r"^[a-zA-Z_][\w-]*$", c)
])
if classes:
selector += "." + ".".join(classes)
# Add index if multiple siblings of the same tag name exist
if current.parent:
siblings = [sib for sib in current.parent.children if isinstance(sib, Tag) and sib.name == current.name]
if len(siblings) > 1:
try:
index = siblings.index(current) + 1
selector += f":nth-of-type({index})"
except ValueError:
pass
path.append(selector)
current = current.parent
return " > ".join(reversed(path))
def get_element_description(element: Union[Tag, str]) -> str:
"""Provides a concise string description of a BeautifulSoup Tag or string."""
if not isinstance(element, Tag):
return str(element)
desc = f"<{element.name}"
attrs = {k: v for k, v in element.attrs.items() if k in ['id', "class", 'name', 'type', 'href', 'alt', 'title']}
for attr, val in attrs.items():
val_str = ' '.join(val) if isinstance(val, list) else str(val)
desc += f" {attr}='{val_str[:30]}...'" if len(val_str) > 30 else f" {attr}='{val_str}'"
return desc + ">"
def get_element_context(soup: BeautifulSoup, element: Tag, lines: int = 5) -> str:
"""Gets a few lines of HTML context around the element for reporting."""
if not element:
return ""
try:
# Check if the element is actually part of this soup's parse tree
element_in_soup = soup.find(lambda tag: tag is element)
if not element_in_soup:
return element.prettify() if isinstance(element, Tag) else str(element)
# Generate a prettified version of the element and the whole soup
elem_prettified = element_in_soup.prettify(formatter="html").strip()
full_prettified = soup.prettify(formatter="html").strip()
# Find the start of the element in the full prettified HTML
element_start_idx = full_prettified.find(elem_prettified)
if element_start_idx == -1:
return elem_prettified
# Calculate start and end line numbers for context
all_lines = full_prettified.splitlines()
element_start_line_num = full_prettified[:element_start_idx].count('\n')
# Determine approx number of lines the element itself takes after prettify
element_line_count = elem_prettified.count('\n') + 1
context_start_line = max(0, element_start_line_num - (lines - 1) // 2)
context_end_line = min(len(all_lines), element_start_line_num + element_line_count + lines // 2)
return "\n".join(all_lines[context_start_line:context_end_line])
except Exception as e:
import logging
logging.getLogger(__name__).debug(f"Error getting element context: {e}. Falling back to element html.")
return element.prettify() if isinstance(element, Tag) else str(element)
# Interactive ARIA roles whose elements are expected to expose an accessible name.
INTERACTIVE_ROLES = {
"button", "link", "checkbox", "radio", "menuitem", "menuitemcheckbox", "menuitemradio",
"tab", "switch", "textbox", "combobox", "searchbox", "slider", "spinbutton", "option", "treeitem",
}
def _accname_text_from_ids(soup: BeautifulSoup, idref: str) -> str:
"""Concatenate the text of elements referenced by a space-separated id list."""
parts = []
for _id in (idref or "").split():
ref = soup.find(id=_id)
if ref:
parts.append(ref.get_text(" ", strip=True))
return " ".join(p for p in parts if p).strip()
def compute_accessible_name(el: Tag, soup: BeautifulSoup) -> str:
"""A practical subset of the W3C accessible name computation (this is ANDI's signature feature).
Order: aria-labelledby -> aria-label -> native (label/legend/alt/value/text) -> title -> placeholder.
"""
if not isinstance(el, Tag):
return ""
if el.has_attr('aria-labelledby'):
name = _accname_text_from_ids(soup, el['aria-labelledby'])
if name:
return name
if el.has_attr('aria-label') and str(el['aria-label']).strip():
return str(el['aria-label']).strip()
tag = el.name
typ = (el.get('type') or '').lower()
if tag in ('input', 'textarea', 'select'):
if el.has_attr('id'):
lbl = soup.find('label', attrs={'for': el['id']})
if lbl and lbl.get_text(strip=True):
return lbl.get_text(" ", strip=True)
wrap = el.find_parent('label')
if wrap and wrap.get_text(strip=True):
return wrap.get_text(" ", strip=True)
if tag == 'input' and typ in ('button', 'submit', 'reset') and (el.get('value') or '').strip():
return el['value'].strip()
if tag == 'input' and typ == 'image' and (el.get('alt') or '').strip():
return el['alt'].strip()
elif tag in ('img', 'area'):
if el.has_attr('alt'):
return el['alt'].strip()
elif tag in ('button', 'a', 'summary') or el.has_attr('role'):
txt = el.get_text(" ", strip=True)
if not txt:
txt = " ".join(i.get('alt', '').strip() for i in el.find_all('img') if i.get('alt', '').strip())
if txt:
return txt
elif tag == 'fieldset':
leg = el.find('legend')
if leg and leg.get_text(strip=True):
return leg.get_text(" ", strip=True)
if el.has_attr('title') and str(el['title']).strip():
return str(el['title']).strip()
if el.has_attr('placeholder') and str(el['placeholder']).strip():
return str(el['placeholder']).strip()
return ""
class ColorUtils:
"""Utility class for color parsing and contrast ratio calculations."""
@staticmethod
def parse_color(color_str: str) -> Optional[Tuple[int, int, int]]:
"""Parse color string and return RGB tuple. Supports hex (3/4/6/8), rgb/rgba, hsl/hsla, modern space syntax, named colors."""
if not color_str:
return None
color_str = color_str.lower().strip()
if color_str in ('transparent', 'currentcolor', 'inherit', 'initial', 'unset'):
return None
if color_str.startswith('#'):
hex_val = color_str.lstrip('#')
# Handle 4-digit and 8-digit hex (with alpha)
if len(hex_val) == 4:
# #RGBA -> check alpha
alpha = int(hex_val[3] * 2, 16) / 255.0
if alpha < 0.05:
return None
hex_val = hex_val[0] * 2 + hex_val[1] * 2 + hex_val[2] * 2
return ColorUtils.hex_to_rgb('#' + hex_val)
elif len(hex_val) == 8:
# #RRGGBBAA -> check alpha
alpha = int(hex_val[6:8], 16) / 255.0
if alpha < 0.05:
return None
return ColorUtils.hex_to_rgb('#' + hex_val[:6])
return ColorUtils.hex_to_rgb(color_str)
# Modern CSS rgb/rgba: supports both comma and space syntax
rgb_match = re.match(r'rgba?\(\s*([\d.]+%?)\s*[,/\s]\s*([\d.]+%?)\s*[,/\s]\s*([\d.]+%?)(?:\s*[,/]\s*([\d.]+%?))?\s*\)', color_str)
if rgb_match:
def _parse_channel(val):
if val.endswith('%'):
return int(float(val[:-1]) * 255 / 100)
return min(255, max(0, int(float(val))))
r, g, b = _parse_channel(rgb_match.group(1)), _parse_channel(rgb_match.group(2)), _parse_channel(rgb_match.group(3))
if rgb_match.group(4):
alpha_str = rgb_match.group(4)
alpha = float(alpha_str[:-1]) / 100.0 if alpha_str.endswith('%') else float(alpha_str)
if alpha < 0.05:
return None
return (r, g, b)
# Modern CSS hsl/hsla: supports both comma and space syntax
hsl_match = re.match(r'hsla?\(\s*([\d.]+)\s*[,\s]\s*([\d.]+)%\s*[,\s]\s*([\d.]+)%(?:\s*[,/]\s*([\d.]+%?))?\s*\)', color_str)
if hsl_match:
h, s, l = float(hsl_match.group(1)), float(hsl_match.group(2)), float(hsl_match.group(3))
if hsl_match.group(4):
alpha_str = hsl_match.group(4)
alpha = float(alpha_str[:-1]) / 100.0 if alpha_str.endswith('%') else float(alpha_str)
if alpha < 0.05:
return None
return ColorUtils.hsl_to_rgb(int(h), int(s), int(l))
# Extended named colors (CSS Level 4)
named_colors = {
"black": "#000000", "white": "#ffffff", "red": "#ff0000", "green": "#008000",
"blue": "#0000ff", "yellow": "#ffff00", "orange": "#ffa500", "purple": "#800080",
"gray": "#808080", "grey": "#808080", "silver": "#c0c0c0", "maroon": "#800000",
"olive": "#808000", "lime": "#00ff00", "aqua": "#00ffff", "teal": "#008080",
"navy": "#000080", "fuchsia": "#ff00ff", "cyan": "#00ffff", "magenta": "#ff00ff",
"coral": "#ff7f50", "crimson": "#dc143c", "darkblue": "#00008b", "darkgreen": "#006400",
"darkgray": "#a9a9a9", "darkgrey": "#a9a9a9", "darkred": "#8b0000",
"gold": "#ffd700", "indigo": "#4b0082", "ivory": "#fffff0",
"khaki": "#f0e68c", "lavender": "#e6e6fa", "lightblue": "#add8e6",
"lightgray": "#d3d3d3", "lightgrey": "#d3d3d3", "lightgreen": "#90ee90",
"lightyellow": "#ffffe0", "linen": "#faf0e6", "mintcream": "#f5fffa",
"pink": "#ffc0cb", "plum": "#dda0dd", "salmon": "#fa8072",
"skyblue": "#87ceeb", "slategray": "#708090", "slategrey": "#708090",
"snow": "#fffafa", "tan": "#d2b48c", "tomato": "#ff6347",
"turquoise": "#40e0d0", "violet": "#ee82ee", "wheat": "#f5deb3",
"whitesmoke": "#f5f5f5", "yellowgreen": "#9acd32",
"rebeccapurple": "#663399", "aliceblue": "#f0f8ff", "antiquewhite": "#faebd7",
"beige": "#f5f5dc", "bisque": "#ffe4c4", "brown": "#a52a2a",
"burlywood": "#deb887", "cadetblue": "#5f9ea0", "chartreuse": "#7fff00",
"chocolate": "#d2691e", "cornflowerblue": "#6495ed", "cornsilk": "#fff8dc",
"darkkhaki": "#bdb76b", "darkorange": "#ff8c00", "darkorchid": "#9932cc",
"darkviolet": "#9400d3", "deeppink": "#ff1493", "deepskyblue": "#00bfff",
"dodgerblue": "#1e90ff", "firebrick": "#b22222", "forestgreen": "#228b22",
"gainsboro": "#dcdcdc", "ghostwhite": "#f8f8ff", "goldenrod": "#daa520",
"greenyellow": "#adff2f", "honeydew": "#f0fff0", "hotpink": "#ff69b4",
"lawngreen": "#7cfc00", "lemonchiffon": "#fffacd", "lightcoral": "#f08080",
"lightcyan": "#e0ffff", "lightpink": "#ffb6c1", "lightsalmon": "#ffa07a",
"lightseagreen": "#20b2aa", "lightskyblue": "#87cefa", "lightsteelblue": "#b0c4de",
"mediumaquamarine": "#66cdaa", "mediumblue": "#0000cd", "mediumorchid": "#ba55d3",
"mediumpurple": "#9370db", "mediumseagreen": "#3cb371", "mediumslateblue": "#7b68ee",
"mediumspringgreen": "#00fa9a", "mediumturquoise": "#48d1cc", "mediumvioletred": "#c71585",
"midnightblue": "#191970", "mistyrose": "#ffe4e1", "moccasin": "#ffe4b5",
"navajowhite": "#ffdead", "oldlace": "#fdf5e6", "olivedrab": "#6b8e23",
"orangered": "#ff4500", "orchid": "#da70d6", "palegoldenrod": "#eee8aa",
"palegreen": "#98fb98", "paleturquoise": "#afeeee", "palevioletred": "#db7093",
"papayawhip": "#ffefd5", "peachpuff": "#ffdab9", "peru": "#cd853f",
"powderblue": "#b0e0e6", "rosybrown": "#bc8f8f", "royalblue": "#4169e1",
"saddlebrown": "#8b4513", "sandybrown": "#f4a460", "seagreen": "#2e8b57",
"seashell": "#fff5ee", "sienna": "#a0522d", "springgreen": "#00ff7f",
"steelblue": "#4682b4", "thistle": "#d8bfd8",
}
hex_color = named_colors.get(color_str)
if hex_color:
return ColorUtils.hex_to_rgb(hex_color)
return None
@staticmethod
def hex_to_rgb(hex_color: str) -> Optional[Tuple[int, int, int]]:
"""Convert hex color to RGB tuple."""
hex_color = hex_color.lstrip('#').lower()
if len(hex_color) == 3:
hex_color = "".join([c*2 for c in hex_color])
if re.match(r"^[0-9a-f]{6}$", hex_color):
try:
r, g, b = int(hex_color[0:2], 16), int(hex_color[2:4], 16), int(hex_color[4:6], 16)
return (r, g, b)
except ValueError:
return None
return None
@staticmethod
def hsl_to_rgb(h: int, s: int, l: int) -> Tuple[int, int, int]:
"""Convert HSL to RGB."""
s /= 100.0
l /= 100.0
c = (1 - abs(2 * l - 1)) * s
x = c * (1 - abs((h / 60) % 2 - 1))
m = l - c / 2
r, g, b = 0, 0, 0
if 0 <= h < 60:
r, g, b = c, x, 0
elif 60 <= h < 120:
r, g, b = x, c, 0
elif 120 <= h < 180:
r, g, b = 0, c, x
elif 180 <= h < 240:
r, g, b = 0, x, c
elif 240 <= h < 300:
r, g, b = x, 0, c
elif 300 <= h < 360:
r, g, b = c, 0, x
return (int((r + m) * 255), int((g + m) * 255), int((b + m) * 255))
@staticmethod
def get_luminance(rgb_tuple: Tuple[int, int, int]) -> float:
"""Calculate relative luminance of RGB color."""
if not rgb_tuple:
return 0.0
srgb = [val / 255.0 for val in rgb_tuple]
r, g, b = [
(val / 12.92) if val <= 0.03928 else ((val + 0.055) / 1.055) ** 2.4 for val in srgb
]
return 0.2126 * r + 0.7152 * g + 0.0722 * b
@staticmethod
def get_contrast_ratio(color1_str: str, color2_str: str) -> float:
"""Calculate contrast ratio between two colors per WCAG 2.x formula."""
rgb1 = ColorUtils.parse_color(color1_str)
rgb2 = ColorUtils.parse_color(color2_str)
if not rgb1 or not rgb2:
return 1.0
lum1 = ColorUtils.get_luminance(rgb1)
lum2 = ColorUtils.get_luminance(rgb2)
lighter = max(lum1, lum2)
darker = min(lum1, lum2)
return (lighter + 0.05) / (darker + 0.05)
# ==============================================================================
# CONSTANTS
# ==============================================================================
APP_VERSION = "5.0.1"
APP_NAME = "WCAG 2.2 Site and PDF Scanner"
DEFAULT_USER_AGENT = f"WCAG-Site-PDF-Scanner/{APP_VERSION} (+accessibility testing)"
################################################################################
# BEGIN analyzers.py