@kinti/a11y-toolkit 5.26.0 → 5.28.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/a11y_toolkit/a11y.py +30 -4
- package/a11y_toolkit/a11yact.py +9 -1
- package/a11y_toolkit/a11yannotate.py +185 -0
- package/a11y_toolkit/a11yaudit.py +924 -196
- package/a11y_toolkit/a11ybadge.py +24 -17
- package/a11y_toolkit/a11ybudget.py +145 -1
- package/a11y_toolkit/a11ycorpus.py +58 -24
- package/a11y_toolkit/a11ycrit.py +114 -53
- package/a11y_toolkit/a11ydiff.py +104 -34
- package/a11y_toolkit/a11ydisprove.py +15 -8
- package/a11y_toolkit/a11ydocx.py +8 -6
- package/a11y_toolkit/a11ydom.py +567 -97
- package/a11y_toolkit/a11yen301549.py +53 -1
- package/a11y_toolkit/a11yengines.py +157 -0
- package/a11y_toolkit/a11yevidence.py +81 -33
- package/a11y_toolkit/a11yfix.py +131 -52
- package/a11y_toolkit/a11ygate.py +225 -0
- package/a11y_toolkit/a11yinit.py +73 -7
- package/a11y_toolkit/a11yjourney.py +110 -4
- package/a11y_toolkit/a11yledger.py +119 -12
- package/a11y_toolkit/a11ylocate.py +247 -0
- package/a11y_toolkit/a11yopenacr.py +10 -3
- package/a11y_toolkit/a11ypatches.py +154 -0
- package/a11y_toolkit/a11ypatterns.py +344 -0
- package/a11y_toolkit/a11ypdf.py +109 -53
- package/a11y_toolkit/a11yrgaa.py +60 -0
- package/a11y_toolkit/a11yroute.py +34 -12
- package/a11y_toolkit/a11ysarif.py +45 -18
- package/a11y_toolkit/a11yscope.py +67 -15
- package/a11y_toolkit/a11yscroll.py +7 -5
- package/a11y_toolkit/a11ystatement.py +30 -6
- package/a11y_toolkit/a11ytrace.py +293 -0
- package/a11y_toolkit/a11yvalidate.py +21 -15
- package/a11y_toolkit/a11yvpat.py +34 -7
- package/a11y_toolkit/a11yvtt.py +22 -6
- package/a11y_toolkit/a11ywiz.py +121 -0
- package/a11y_toolkit/contrast.py +62 -24
- package/a11y_toolkit/locales/en.json +185 -20
- package/a11y_toolkit/locales/es.json +186 -21
- package/a11y_toolkit/rgaa.json +2661 -0
- package/a11y_toolkit/server.py +157 -54
- package/package.json +2 -2
- package/a11y_toolkit/a11yplan.py +0 -214
- package/a11y_toolkit/a11ywcagem.py +0 -237
|
@@ -27,6 +27,20 @@ from . import a11yi18n
|
|
|
27
27
|
|
|
28
28
|
MAX_HTML = 3_000_000
|
|
29
29
|
|
|
30
|
+
# alt_quality (1.1.1): alt que "existe" pero no comunica. La mina de
|
|
31
|
+
# patentes lo confirma (el plugin alt-text de GitHub): filenames, palabras
|
|
32
|
+
# genéricas y marcadores PASAN el chequeo de presencia y aun así fallan.
|
|
33
|
+
_ALT_EXT_RX = re.compile(r'\.(jpe?g|png|gif|webp|svg|avif|bmp)$', re.I)
|
|
34
|
+
_ALT_DUMP_RX = re.compile(
|
|
35
|
+
r'^(dsc[f]?[-_ ]?\d+|img[-_ ]?\d+|imagen\d*|foto\d*|screenshot[\w-]*)$', re.I)
|
|
36
|
+
_ALT_GENERIC = {
|
|
37
|
+
'image', 'imagen', 'photo', 'foto', 'picture', 'pic', 'img',
|
|
38
|
+
'grafico', 'gráfico', 'grafica', 'gráfica', 'graphic', 'chart',
|
|
39
|
+
'icon', 'icono', 'logo', 'logotipo', 'spacer', 'banner', 'avatar',
|
|
40
|
+
'drawing', 'dibujo', 'figure', 'figura', 'media', 'button', 'botón',
|
|
41
|
+
'boton', 'link', 'enlace', 'svg', 'png', 'jpg', 'jpeg',
|
|
42
|
+
}
|
|
43
|
+
|
|
30
44
|
# Campos de formulario que necesitan etiqueta visible o nombre accesible
|
|
31
45
|
_FIELDS = {'text', 'email', 'tel', 'url', 'search', 'password', 'number',
|
|
32
46
|
'date', 'time', 'datetime-local', 'month', 'week', 'checkbox',
|
|
@@ -37,14 +51,38 @@ _CONTROLS = ('a', 'button', 'summary')
|
|
|
37
51
|
_VOID = {'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link',
|
|
38
52
|
'meta', 'param', 'source', 'track', 'wbr'}
|
|
39
53
|
|
|
40
|
-
#
|
|
54
|
+
# ── kernel de anotación por elemento (a11yannotate) ────────────────────────
|
|
55
|
+
# Fuente única de la identidad de elemento: la comparten el auditor (que
|
|
56
|
+
# graba rutas mientras parsea) y el localizador de a11yannotate (que vuelve a
|
|
57
|
+
# parsear el MISMO html para inyectar marcas). Mismo algoritmo, mismo orden.
|
|
58
|
+
VOID_TAGS = _VOID
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def path_segment(tag, nth):
|
|
62
|
+
"""Segmento de ruta CSS determinista (nth SIEMPRE: los id duplicados no
|
|
63
|
+
pueden romper la identidad)."""
|
|
64
|
+
return f'{tag}:nth-of-type({nth})'
|
|
65
|
+
|
|
66
|
+
# roles que convierten cualquier elemento en campo etiquetable (e086e5).
|
|
67
|
+
# OJO: 'search' NO está — es un LANDMARK (WAI-ARIA 1.2), no un widget: un
|
|
68
|
+
# <form role="search"> sin aria-label es un landmark sin etiqueta, no un
|
|
69
|
+
# campo sin label (el patrón del tutorial W3C no puede dar HIGH 3.3.2)
|
|
41
70
|
_ROLE_FIELDS = {'textbox', 'searchbox', 'spinbutton', 'combobox', 'listbox',
|
|
42
|
-
'checkbox', 'radio', 'switch'
|
|
71
|
+
'checkbox', 'radio', 'switch'}
|
|
43
72
|
|
|
44
73
|
# Subetiquetas BCP-47 principales habituales (validación blanda)
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
74
|
+
# ISO 639-1 COMPLETO: los 190 subtags de idioma de 2 letras del registro IANA
|
|
75
|
+
# language-subtag-registry (File-Date 2026-09-17, la fuente canónica de BCP-47),
|
|
76
|
+
# deprecados incluidos — in/iw/ji/jw/mo/sh siguen vivos en páginas reales. La
|
|
77
|
+
# lista corta de la era v3 (77 códigos) rechazaba válidos como gd/eo/yi — FP de
|
|
78
|
+
# la revisión externa de 2026-11.
|
|
79
|
+
_LANG_CODES = set('''aa ab ae af ak am an ar as av ay az ba be bg bh bi bm bn bo br bs ca ce ch co cr cs cu cv cy
|
|
80
|
+
da de dv dz ee el en eo es et eu fa ff fi fj fo fr fy ga gd gl gn gu gv ha he hi ho hr ht hu
|
|
81
|
+
hy hz ia id ie ig ii ik in io is it iu iw ja ji jv jw ka kg ki kj kk kl km kn ko kr ks ku kv
|
|
82
|
+
kw ky la lb lg li ln lo lt lu lv mg mh mi mk ml mn mo mr ms mt my na nb nd ne ng nl nn no nr
|
|
83
|
+
nv ny oc oj om or os pa pi pl ps pt qu rm rn ro ru rw sa sc sd se sg sh si sk sl sm sn so sq
|
|
84
|
+
sr ss st su sv sw ta te tg th ti tk tl tn to tr ts tt tw ty ug uk ur uz ve vi vo wa wo xh yi
|
|
85
|
+
yo za zh zu'''.split())
|
|
48
86
|
|
|
49
87
|
_REGIONS = set('''af ax al dz as ad ao ai aq ag ar am aw au at az bs bh bd bb by be bz
|
|
50
88
|
bm bt bo bq ba bw bv io br io bn bg bf bi cv kh cm ca ky cf td cl cn cx cc co km cg cd
|
|
@@ -86,8 +124,9 @@ _SENSORIAL = re.compile(
|
|
|
86
124
|
|
|
87
125
|
# Campos que con frecuencia recogen datos personales (1.3.5)
|
|
88
126
|
_PERSONAL_DATA = re.compile(
|
|
89
|
-
r'(^|[\W_])(name|nombre|email|correo|
|
|
90
|
-
r'
|
|
127
|
+
r'(^|[\W_])(full[_-]?name|first[_-]?name|last[_-]?name|name|nombre|email|correo|'
|
|
128
|
+
r'phone|telefono|tel|address|direccion|postal|zip|city|ciudad|country|pais|'
|
|
129
|
+
r'organi[sz]ation|company|empresa|street|user(name)?|usuario)([\W_]|$)', re.I)
|
|
91
130
|
|
|
92
131
|
# Tokens autofill válidos (HTML §7.5 — subconjunto práctico del estándar;
|
|
93
132
|
# one-time-code incluido: los campos OTP lo exigen y los lectores lo usan)
|
|
@@ -108,6 +147,31 @@ _AUTOFILL_TOKENS = {
|
|
|
108
147
|
# nombres de campo que faltaban
|
|
109
148
|
'cc-additional-name', 'tel-extension', 'webauthn',
|
|
110
149
|
}
|
|
150
|
+
# 1.3.5 contradicción de propósito: el type y el token de autocomplete que
|
|
151
|
+
# dicen cosas incompatibles (type=email con autocomplete="postal-code").
|
|
152
|
+
# Solo contradicciones DURAS por familia de dato del estándar; lo raro pero
|
|
153
|
+
# legal queda fuera (type=email + username es EL patrón de login por correo y
|
|
154
|
+
# es legítimo: username queda exento en todas las familias).
|
|
155
|
+
_AC_FAMILIA_TEL = {'tel', 'tel-country-code', 'tel-national', 'tel-area-code',
|
|
156
|
+
'tel-local', 'tel-extension'}
|
|
157
|
+
_AC_FAMILIA_ADDR = {'street-address', 'address-line1', 'address-line2',
|
|
158
|
+
'address-line3', 'address-level1', 'address-level2',
|
|
159
|
+
'address-level3', 'address-level4', 'country',
|
|
160
|
+
'country-name', 'postal-code'}
|
|
161
|
+
_AC_FAMILY_TEXT = {'name', 'given-name', 'additional-name', 'family-name',
|
|
162
|
+
'nickname', 'honorific-prefix', 'honorific-suffix',
|
|
163
|
+
'organization', 'cc-name', 'cc-given-name',
|
|
164
|
+
'cc-additional-name', 'cc-family-name'}
|
|
165
|
+
_AC_MISC = {'bday', 'bday-day', 'bday-month', 'bday-year', 'sex', 'language',
|
|
166
|
+
'photo', 'impp', 'cc-number', 'cc-exp', 'cc-exp-month',
|
|
167
|
+
'cc-exp-year', 'cc-csc', 'cc-type', 'transaction-currency',
|
|
168
|
+
'transaction-amount'}
|
|
169
|
+
_AUTOCOMPLETE_CONTRA = {
|
|
170
|
+
'email': _AC_FAMILIA_TEL | _AC_FAMILIA_ADDR | _AC_FAMILY_TEXT | _AC_MISC,
|
|
171
|
+
'tel': {'email', 'url'} | _AC_FAMILIA_ADDR | _AC_FAMILY_TEXT | _AC_MISC,
|
|
172
|
+
'url': {'email'} | _AC_FAMILIA_TEL | _AC_FAMILIA_ADDR | _AC_FAMILY_TEXT | _AC_MISC,
|
|
173
|
+
}
|
|
174
|
+
|
|
111
175
|
# sección-*: comodín del estándar (section-main, section-top…)
|
|
112
176
|
_SECTION = __import__('re').compile(r'^section-[a-z0-9-]+$')
|
|
113
177
|
|
|
@@ -118,10 +182,6 @@ _MOD_ADDRESS = {'shipping', 'billing'}
|
|
|
118
182
|
# el modificador de contacto solo vale pegado a estos campos (ABNF 73f2c2)
|
|
119
183
|
_FIELDS_AFTER_CONTACT = {'email', 'impp', 'tel', 'tel-country-code', 'tel-national',
|
|
120
184
|
'tel-area-code', 'tel-local', 'tel-extension'}
|
|
121
|
-
_FIELDS_AFTER_CONTACTMOD = {'username', 'email', 'impp', 'tel', 'tel-country-code',
|
|
122
|
-
'tel-national', 'tel-area-code', 'tel-local', 'tel-extension',
|
|
123
|
-
'nickname', 'honorific-prefix', 'given-name', 'additional-name',
|
|
124
|
-
'family-name', 'new-password', 'current-password', 'one-time-code'}
|
|
125
185
|
_FIELDS_AFTER_ADDRMOD = {'street-address', 'address-line1', 'address-line2', 'address-line3',
|
|
126
186
|
'address-level1', 'address-level2', 'address-level3', 'address-level4',
|
|
127
187
|
'country', 'country-name', 'postal-code'}
|
|
@@ -276,8 +336,25 @@ _OVERLAY_WIDGETS = (
|
|
|
276
336
|
('AudioEye', ('audioeye.com',)),
|
|
277
337
|
('EqualWeb', ('equalweb.com',)),
|
|
278
338
|
("FACIL'ITI", ('facil-iti.com', 'facil-iti.org')),
|
|
339
|
+
# los históricos del sector público (la investigación 17-nov: Birmingham
|
|
340
|
+
# 2010 recomendaba Browsealoud; el linaje overlay va de Browsealoud a las
|
|
341
|
+
# barras modernas) y el resto del overlayfactsheet común
|
|
342
|
+
('Texthelp (Browsealoud/ReachDeck)', ('texthelp.com', 'browsealoud.com', 'reachdeck.com')),
|
|
343
|
+
('Recite Me', ('recite.me',)),
|
|
344
|
+
('User1st', ('user1st.com',)),
|
|
345
|
+
('UsableNet', ('usablenet.com',)),
|
|
279
346
|
)
|
|
280
347
|
|
|
348
|
+
# texto de un skip link (es/en/pt/fr — el vocabulario del patrón 3e12e1)
|
|
349
|
+
_SKIP_TEXT = re.compile(
|
|
350
|
+
r'skip|jump to|saltar|ir al contenido|ir para o conte[uú]do|passer au contenu', re.I)
|
|
351
|
+
|
|
352
|
+
# encabezados cortos legítimos (acrónimos y términos técnicos): «FAQ», «API»…
|
|
353
|
+
_SHORT_HEADINGS = {'FAQ', 'API', 'CSS', 'APP', 'MAP', 'EN', 'DE', 'ES', 'PT', 'FR',
|
|
354
|
+
'IT', 'UI', 'UX', 'ID', 'TV', 'HR', 'PR', 'AI', 'PC', 'OK', '3D',
|
|
355
|
+
'IOS', 'OS', 'GB', 'MB', 'KB', 'PDF', 'RSS', 'URL', 'WWW', 'XML',
|
|
356
|
+
'HTTP', 'FAQS', 'BLOG', 'HOME', 'INICIO', 'NOTAS', 'AGENDA'}
|
|
357
|
+
|
|
281
358
|
|
|
282
359
|
def _t(lang, key, n=None):
|
|
283
360
|
"""Message by key; `{"one","other"}` entries resolve via the locale's
|
|
@@ -296,10 +373,26 @@ class _Auditor(HTMLParser):
|
|
|
296
373
|
'form', 'input', 'select', 'textarea', 'table')
|
|
297
374
|
|
|
298
375
|
def __init__(self):
|
|
376
|
+
# ── anotación por elemento (kernel a11yannotate) ──────────────────
|
|
377
|
+
# identidad determinista: cada elemento del parseo recibe su ruta
|
|
378
|
+
# CSS (tag:nth-of-type(n) desde la raíz). id(attrs) es estable dentro
|
|
379
|
+
# del parseo (cada attrs es un dict nuevo) → los recolectores pueden
|
|
380
|
+
# resolver la ruta de LO QUE COGIERON sin cambiar sus tuplas.
|
|
381
|
+
self._path_stack = [] # [(tag, path, {tag: nth})] del elemento abierto
|
|
382
|
+
self._elem_paths = {} # id(attrs) → ruta del elemento
|
|
299
383
|
super().__init__(convert_charrefs=True)
|
|
300
384
|
self.imgs_no_alt = []
|
|
385
|
+
self.alt_quality_bad = [] # (razón, alt, attrs) — emitida en findings
|
|
386
|
+
# elementos (attrs) detrás de cada ejemplo, para el kernel de anotación
|
|
387
|
+
self.imgs_no_alt_elems = []
|
|
388
|
+
self.canvas_no_layer = [] # canvas sin capa accesible (1.1.1)
|
|
389
|
+
self.canvas_no_layer_elems = []
|
|
390
|
+
self.iframes_no_title_elems = []
|
|
391
|
+
self.placeholder_only_elems = []
|
|
392
|
+
self.autocomplete_elems = []
|
|
301
393
|
self.controls_by_kind = {} # tag → lista de atributos de controles sin nombre
|
|
302
394
|
self.fields_no_label = []
|
|
395
|
+
self.fields_no_label_elems = []
|
|
303
396
|
self.iframes_no_title = []
|
|
304
397
|
self.lang = None
|
|
305
398
|
self.lang_region_invalid = None
|
|
@@ -312,9 +405,12 @@ class _Auditor(HTMLParser):
|
|
|
312
405
|
self._heading_level = None
|
|
313
406
|
self._heading_text = []
|
|
314
407
|
self._visible_text = []
|
|
315
|
-
self._heading_text = []
|
|
316
408
|
self.positive_tabindices = []
|
|
409
|
+
self.positive_tabindex_elems = []
|
|
410
|
+
self.blank_no_warning_elems = [] # anchors _blank sin aviso (paths)
|
|
317
411
|
self.viewport = None
|
|
412
|
+
self._viewport_elem = None # attrs del meta viewport (path)
|
|
413
|
+
self._meta_refresh_elems = [] # attrs de cada meta refresh (path)
|
|
318
414
|
self.elements = 0
|
|
319
415
|
# Pila de controles interactivos (a/button/summary) para recoger su
|
|
320
416
|
# texto interno, que es la fuente más habitual de nombre accesible.
|
|
@@ -325,16 +421,27 @@ class _Auditor(HTMLParser):
|
|
|
325
421
|
self.orphan_labels = 0
|
|
326
422
|
# Nuevas señales
|
|
327
423
|
self.aria_hidden_focusable = [] # tag de interactivos con aria-hidden
|
|
424
|
+
self.aria_hidden_focusable_elems = []
|
|
328
425
|
self.stray_clicks = [] # tags no interactivos con onclick
|
|
426
|
+
self.stray_click_elems = [] # attrs de cada uno (paths del kernel)
|
|
427
|
+
self._stray_pend = [] # (tag, attrs, frame) hasta cerrar: se
|
|
428
|
+
# confirma salvo que el subárbol contenga un control nativo (delegación)
|
|
429
|
+
self.role_no_tabindex = [] # [role=button/link] sin tabindex (2.1.1)
|
|
430
|
+
self.role_no_tabindex_elems = []
|
|
329
431
|
self.meta_refresh = None
|
|
330
432
|
self.meta_refreshes = [] # todos los meta refresh: gana el 1º parseable (spec HTML)
|
|
331
433
|
self.saw_html = False
|
|
332
434
|
self.saw_body = False
|
|
333
435
|
self.root_tag = None
|
|
334
|
-
self._in_head = False
|
|
335
436
|
self._in_template = 0
|
|
336
437
|
self._title_buf = []
|
|
337
438
|
self._titles_in_order = []
|
|
439
|
+
# svg: <title> DENTRO de <svg> es el nombre del svg (accname), no el
|
|
440
|
+
# título del documento — se rastrea por profundidad de svg abiertos
|
|
441
|
+
self._svg_depth = 0
|
|
442
|
+
self._in_svg_title = False
|
|
443
|
+
self._svg_title_buf = []
|
|
444
|
+
self._svg_titles = {} # id(attrs del svg) → texto de su <title>
|
|
338
445
|
# accname (ola de precisión ACT): visibilidad HEREDADA (aria-hidden con
|
|
339
446
|
# re-activación por false, attr hidden, display:none/visibility:hidden)
|
|
340
447
|
# y registro id→texto para resolver aria-labelledby a un salto — los ids
|
|
@@ -352,6 +459,8 @@ class _Auditor(HTMLParser):
|
|
|
352
459
|
self._styles_text = '' # contenido de <style>: clases ocultas y fuentes-icono
|
|
353
460
|
self._styles_cached_src = None
|
|
354
461
|
self._style_rules = []
|
|
462
|
+
self._hidden_cls_set = set() # clases que el <style> oculta (caché)
|
|
463
|
+
self._nohiding_cls_set = set() # subconjunto display:none/visibility (foco)
|
|
355
464
|
self._icon_links = []
|
|
356
465
|
self._ahf_deferred = [] # (tag, id) off-screen: decidir post-parse con los scripts completos
|
|
357
466
|
self._el_stack = [] # (tag, attrs, [texto directo]) — texto propio del elemento
|
|
@@ -371,10 +480,16 @@ class _Auditor(HTMLParser):
|
|
|
371
480
|
self.videos = 0
|
|
372
481
|
self.videos_with_captions = 0
|
|
373
482
|
self._in_video = False
|
|
483
|
+
self._video_caps_stack = [] # [attrs, captions, descriptions] por <video>
|
|
484
|
+
self.videos_no_caps_elems = []
|
|
485
|
+
self.videos_no_desc_elems = []
|
|
486
|
+
self.media_autoplay_elems = []
|
|
374
487
|
self.tables = 0
|
|
375
488
|
self.tables_with_th = 0
|
|
376
489
|
self._in_table = False
|
|
377
490
|
self._th_in_table = False
|
|
491
|
+
self._table_stack = [] # (th_había, attrs) por <table> abierta
|
|
492
|
+
self.tables_no_th_elems = []
|
|
378
493
|
self.blank_no_warning = 0
|
|
379
494
|
self.blank_total = 0
|
|
380
495
|
self.hay_main = False
|
|
@@ -383,6 +498,8 @@ class _Auditor(HTMLParser):
|
|
|
383
498
|
self.empty_h = 0
|
|
384
499
|
self.ids = {}
|
|
385
500
|
self.input_img_no_alt = 0
|
|
501
|
+
self.canvases = [] # [(attrs, texto_interno, hidden)] — capa accesible del canvas
|
|
502
|
+
self.canvas_hidden = {} # id(attrs) → hidden, del starttag al endtag
|
|
386
503
|
# v3.1: validez ARIA, autocomplete, enlaces, landmarks, accesskey, autoplay
|
|
387
504
|
self.aria_refs = [] # (attr, id) referenciados por aria-labelledby/describedby
|
|
388
505
|
self.aria_values = [] # valores aria-* inválidos
|
|
@@ -392,9 +509,12 @@ class _Auditor(HTMLParser):
|
|
|
392
509
|
self.accesskeys = {} # accesskey → tag
|
|
393
510
|
self.missing_autocomplete = []
|
|
394
511
|
self.autocomplete_invalid = []
|
|
512
|
+
self.autocomplete_mismatch = []
|
|
395
513
|
self.links = {} # nombre normalizado → set de hrefs
|
|
396
514
|
self.generics = 0
|
|
397
515
|
self.labels_for_dups = {} # id → n labels (los >1, varios)
|
|
516
|
+
self._label_for_stack = [] # valor `for` de cada <label> abierto (None = envolvente)
|
|
517
|
+
self._label_text_for = {} # id del for → texto del label (decisión post-parse)
|
|
398
518
|
self.media_autoplay = 0
|
|
399
519
|
self._list_depth = 0
|
|
400
520
|
self._li_depth = 0
|
|
@@ -402,8 +522,12 @@ class _Auditor(HTMLParser):
|
|
|
402
522
|
self.label_no_name = [] # (texto visible, aria-label) 2.5.3
|
|
403
523
|
self.lang_parts_invalid = [] # lang inválidos en elementos no-html
|
|
404
524
|
self.down_events = [] # onmousedown/ontouchstart/onpointerdown
|
|
405
|
-
self.captchas = [] # detección 3.3.8
|
|
525
|
+
self.captchas = [] # detección 3.3.8 — SOLO en contexto de autenticación
|
|
526
|
+
self._form_captchas = [] # candidatos del <form> abierto (3.3.8 aplica a auth)
|
|
527
|
+
self._form_auth = False # form actual: acción de login o input password
|
|
528
|
+
self._required_pend = [] # (tag, attrs) required: decide post-parse con el label
|
|
406
529
|
self.mobiles = [] # marquee/blink/inline infinite animation (2.2.2)
|
|
530
|
+
self._landmark_ids = set() # ids de landmarks: objetivos válidos de skip link
|
|
407
531
|
self.nav_hrefs = set() # hrefs inside <nav> (site-level 3.2.3 signature)
|
|
408
532
|
self.help_hrefs = set() # help/contact links (site-level 3.2.6 signature)
|
|
409
533
|
self.images_of_text = []
|
|
@@ -417,21 +541,24 @@ class _Auditor(HTMLParser):
|
|
|
417
541
|
self.missing_fieldsets = 0 # 1.3.1: radio/check groups sin fieldset
|
|
418
542
|
self._radio_group = {}
|
|
419
543
|
self._radio_in_fieldset = {} # name → count (para detectar grupos)
|
|
544
|
+
self._radio_in_group = {} # name → dentro de role=group con nombre
|
|
420
545
|
self.vague_labels = [] # 2.4.6: label quality
|
|
421
546
|
self.financial_no_confirm = 0 # 3.3.4: financial form no confirm
|
|
422
547
|
self._financial_form = False
|
|
423
|
-
self._confirm_form = False #
|
|
548
|
+
self._confirm_form = False # 3.3.4: pista de confirmación en form financiero
|
|
424
549
|
self._in_nav = 0
|
|
425
550
|
self._in_fieldset = False
|
|
551
|
+
self._group_role_depth = 0 # <div role=group/radiogroup> abierto (con nombre)
|
|
426
552
|
self.has_search = False
|
|
427
553
|
self.has_sitemap = False
|
|
428
554
|
self.gestures = [] # touchmove/drag handlers (2.5.1)
|
|
555
|
+
self.focus_blur = [] # onfocus="blur()": foco robado (2.1.1)
|
|
556
|
+
self.focus_blur_elems = []
|
|
429
557
|
self.features = {} # tag → n (rasgos de aplicabilidad)
|
|
430
558
|
self.motions = [] # deviceorientation/devicemotion (2.5.4)
|
|
431
559
|
self.orientation_locks = [] # screen.orientation.lock / orientation MQ (1.3.4)
|
|
432
560
|
self.videos_descriptions = 0 # videos WITH descriptions track
|
|
433
561
|
self.sensory = [] # sensory-only instruction patterns (1.3.3)
|
|
434
|
-
self._skip_labels_pend = [] # labels declarados antes que su campo
|
|
435
562
|
|
|
436
563
|
def _close_control(self, tag):
|
|
437
564
|
if not self._ctrl:
|
|
@@ -464,7 +591,10 @@ class _Auditor(HTMLParser):
|
|
|
464
591
|
self._styles_text, re.I)) or bool(re.search(
|
|
465
592
|
r'fonts\.googleapis\.com/icon|/material-icons|font-?awesome|/icomoon',
|
|
466
593
|
' '.join(getattr(self, '_icon_links', [])), re.I))
|
|
467
|
-
|
|
594
|
+
# página con fuente-icono: el «texto» del control puede ser un glifo
|
|
595
|
+
# no verbal (ligadura Material «shopping_cart») — exento en CUALQUIER
|
|
596
|
+
# control (enlaces-icono incluidos), no solo <button>
|
|
597
|
+
if not _icon_font and _vis and _al:
|
|
468
598
|
def _lin_words(txt):
|
|
469
599
|
txt = re.sub(r'\([^)]*\)', ' ', txt)
|
|
470
600
|
# la puntuación se ELIMINA sin partir palabras («11×3=33» →
|
|
@@ -484,14 +614,23 @@ class _Auditor(HTMLParser):
|
|
|
484
614
|
for i in range(len(_ap2) - len(_vp) + 1))
|
|
485
615
|
if _mismatch:
|
|
486
616
|
self.label_no_name.append((_vis[:40], _al[:60]))
|
|
487
|
-
if tag == 'a':
|
|
617
|
+
if tag == 'a' and not c.get('hidden'):
|
|
488
618
|
if (a.get('target') or '').lower() == '_blank':
|
|
489
619
|
self.blank_total += 1
|
|
620
|
+
_img_alts = ' '.join((ia.get('alt') or '')
|
|
621
|
+
for ia in c.get('img_attrs', []))
|
|
490
622
|
if not _BLANK_HINT.search(text) and not _BLANK_HINT.search(a.get('aria-label') or '') \
|
|
491
|
-
and not _BLANK_HINT.search(a.get('title') or '')
|
|
623
|
+
and not _BLANK_HINT.search(a.get('title') or '') \
|
|
624
|
+
and not _BLANK_HINT.search(_img_alts):
|
|
492
625
|
self.blank_no_warning += 1
|
|
493
|
-
|
|
494
|
-
|
|
626
|
+
self.blank_no_warning_elems.append(a)
|
|
627
|
+
elif (a.get('href') or '').strip().startswith('#') \
|
|
628
|
+
and len((a.get('href') or '').strip()) > 1 and text:
|
|
629
|
+
# skip link REAL: ancla interna cuyo objetivo es un landmark o
|
|
630
|
+
# cuyo texto lo dice — un TOC/footnote no abate bloques (3e12e1)
|
|
631
|
+
if (a.get('href') or '').strip()[1:] in self._landmark_ids \
|
|
632
|
+
or _SKIP_TEXT.search(text):
|
|
633
|
+
self.hay_skip = True
|
|
495
634
|
name = (text or a.get('aria-label') or a.get('title') or '').strip()
|
|
496
635
|
href = (a.get('href') or '').strip()
|
|
497
636
|
if name and href:
|
|
@@ -505,9 +644,55 @@ class _Auditor(HTMLParser):
|
|
|
505
644
|
if self._labels_stack:
|
|
506
645
|
self._labels_stack[-1] = True
|
|
507
646
|
|
|
647
|
+
def _wrap_labels(self, a):
|
|
648
|
+
"""¿Un <label> ABIERTO etiqueta ESTE campo? El label envolvente solo
|
|
649
|
+
asocia cuando NO tiene `for` (o su `for` apunta al propio campo):
|
|
650
|
+
<label for=email>…<input id=pw>> NO etiqueta a pw (el for manda)."""
|
|
651
|
+
if not self._label_for_stack:
|
|
652
|
+
return False
|
|
653
|
+
_fid = a.get('id')
|
|
654
|
+
return any(_f is None or (_fid and _f == _fid)
|
|
655
|
+
for _f in self._label_for_stack)
|
|
656
|
+
|
|
508
657
|
def handle_starttag(self, tag, attrs):
|
|
509
|
-
|
|
658
|
+
# atributos DUPLICADOS: gana el PRIMERO (spec HTML: los repetidos se
|
|
659
|
+
# descartan) — dict(attrs) dejaría ganar al último y <img alt="x" alt="">
|
|
660
|
+
# pasaría por decorativa
|
|
661
|
+
a = {}
|
|
662
|
+
for _k, _v in attrs:
|
|
663
|
+
if _k not in a:
|
|
664
|
+
a[_k] = _v
|
|
510
665
|
self.elements += 1
|
|
666
|
+
# delegación de eventos: un control interactivo REAL dentro de un
|
|
667
|
+
# candidato a «click no enfocable» lo exime (wrapper de analytics
|
|
668
|
+
# sobre un <button> real). «Interactivo» exige OPERABILIDAD: un <a>
|
|
669
|
+
# SIN href no recibe foco, un input hidden/disabled tampoco, y el
|
|
670
|
+
# contenido de <template> es inerte — ninguno salva al wrapper
|
|
671
|
+
if self._stray_pend and not self._in_template:
|
|
672
|
+
_ti_mark = (a.get('tabindex') or '').strip()
|
|
673
|
+
_rolemark = (a.get('role') or '').strip().lower() in ('button', 'link')
|
|
674
|
+
_nav = (tag == 'a' and bool((a.get('href') or '').strip()))
|
|
675
|
+
_native = (tag in ('button', 'summary', 'select', 'textarea')
|
|
676
|
+
or _nav
|
|
677
|
+
or (tag == 'input' and (a.get('type') or 'text').lower() != 'hidden'
|
|
678
|
+
and 'disabled' not in a))
|
|
679
|
+
if _native or _rolemark \
|
|
680
|
+
or (_ti_mark.isdecimal() and int(_ti_mark) >= 0):
|
|
681
|
+
for _sp in self._stray_pend:
|
|
682
|
+
_sp[3] = True
|
|
683
|
+
# ruta determinista del elemento (kernel de anotación): nth-of-type
|
|
684
|
+
# SIEMPRE (los id duplicados no pueden romper la ruta) y los void no
|
|
685
|
+
# abren pila (no tienen handle_endtag)
|
|
686
|
+
if self._path_stack:
|
|
687
|
+
_parent = self._path_stack[-1]
|
|
688
|
+
_parent[2][tag] = _parent[2].get(tag, 0) + 1
|
|
689
|
+
_seg = path_segment(tag, _parent[2][tag])
|
|
690
|
+
_path = _parent[1] + '>' + _seg
|
|
691
|
+
else:
|
|
692
|
+
_path = path_segment(tag, 1)
|
|
693
|
+
self._elem_paths[id(a)] = _path
|
|
694
|
+
if tag not in VOID_TAGS:
|
|
695
|
+
self._path_stack.append((tag, _path, {}))
|
|
511
696
|
# rasgos estructurales para el scope de aplicabilidad (a11yscope):
|
|
512
697
|
# evidencia POSITIVA — cero <video> habilita proponer 1.2.x como no
|
|
513
698
|
# aplicable; la ausencia de señal jamás cuenta como ausencia de
|
|
@@ -517,7 +702,8 @@ class _Auditor(HTMLParser):
|
|
|
517
702
|
pass
|
|
518
703
|
else:
|
|
519
704
|
self.features[tag] = self.features.get(tag, 0) + 1
|
|
520
|
-
if a.get('id'):
|
|
705
|
+
if a.get('id') and not self._in_template:
|
|
706
|
+
# ids dentro de <template> no existen: ni dup_ids ni refs rotas
|
|
521
707
|
self.ids[a['id']] = self.ids.get(a['id'], 0) + 1
|
|
522
708
|
if self.root_tag is None:
|
|
523
709
|
self.root_tag = tag
|
|
@@ -534,6 +720,11 @@ class _Auditor(HTMLParser):
|
|
|
534
720
|
_hidden_aria = False
|
|
535
721
|
_hidden = _inh or 'hidden' in a or 'display:none' in _style \
|
|
536
722
|
or 'visibility:hidden' in _style or _hidden_aria
|
|
723
|
+
# <template> es contenido INERTE (spec HTML): no renderiza, no recibe
|
|
724
|
+
# foco, sus ids no existen — se audita como oculto y los colectores
|
|
725
|
+
# que no consultan _hidden llevan guardia explícita
|
|
726
|
+
if self._in_template:
|
|
727
|
+
_hidden = True
|
|
537
728
|
if tag not in _VOID:
|
|
538
729
|
self._depth += 1
|
|
539
730
|
self._hidden_stack.append((_hidden, _hidden_aria))
|
|
@@ -550,10 +741,34 @@ class _Auditor(HTMLParser):
|
|
|
550
741
|
self._nav_ids.add(a['id'])
|
|
551
742
|
if a.get('onclick'):
|
|
552
743
|
self._toggle_onclicks.append(a['onclick'])
|
|
553
|
-
if tag == '
|
|
554
|
-
self._in_head = True
|
|
555
|
-
elif tag == 'template':
|
|
744
|
+
if tag == 'template':
|
|
556
745
|
self._in_template += 1
|
|
746
|
+
elif tag == 'svg':
|
|
747
|
+
self._svg_depth += 1
|
|
748
|
+
# svg hijo de un control: su aria-label/aria-labelledby/<title>
|
|
749
|
+
# aporta al nombre del control (accname 2F.ii: name-from-content
|
|
750
|
+
# incluye el nombre accesible de cada descendiente — Chrome y
|
|
751
|
+
# Firefox nombran «Submit Search» al botón-buscador del W3C WAI
|
|
752
|
+
# así). aria-hidden en el svg lo excluye (icono decorativo).
|
|
753
|
+
if self._ctrl and (a.get('aria-label') or a.get('aria-labelledby')) \
|
|
754
|
+
and (a.get('aria-hidden') or '').strip().lower() != 'true':
|
|
755
|
+
self._ctrl[-1]['img_attrs'].append(a)
|
|
756
|
+
# y los ROLES sobre el propio svg se procesan igual que en un tag
|
|
757
|
+
# cualquiera: svg[role=img] sin nombre ES un 1.1.1 (ACT 23a2a8),
|
|
758
|
+
# svg[role=button] exige nombre+tabindex — el elif de arriba se
|
|
759
|
+
# comía el svg antes de llegar a la maquinaria de roles
|
|
760
|
+
_svg_role = (a.get('role') or '').strip().lower()
|
|
761
|
+
if not self._in_template:
|
|
762
|
+
if _svg_role == 'img':
|
|
763
|
+
self.imgs_all.append((a, _hidden))
|
|
764
|
+
elif _svg_role in ('button', 'link'):
|
|
765
|
+
self._ctrl.append({'tag': tag, 'attrs': a, 'text': [],
|
|
766
|
+
'text_visible': [], 'inner_img': False,
|
|
767
|
+
'img_attrs': [], 'hidden': _hidden,
|
|
768
|
+
'depth': self._depth, 'kind': 'role:' + _svg_role})
|
|
769
|
+
if 'tabindex' not in a and not _hidden:
|
|
770
|
+
self.role_no_tabindex.append(f'{tag}[role={_svg_role}]')
|
|
771
|
+
self.role_no_tabindex_elems.append(a)
|
|
557
772
|
elif tag == 'html':
|
|
558
773
|
self.saw_html = True
|
|
559
774
|
self.lang = (a.get('lang') or '').strip()
|
|
@@ -563,11 +778,15 @@ class _Auditor(HTMLParser):
|
|
|
563
778
|
self.lang_region_invalid = self.lang
|
|
564
779
|
elif tag == 'body':
|
|
565
780
|
self.saw_body = True
|
|
566
|
-
elif tag == 'title' and not self._in_template:
|
|
781
|
+
elif tag == 'title' and not self._in_template and self._svg_depth == 0:
|
|
567
782
|
# TODOS los <title> se acumulan en orden de documento: decide el
|
|
568
783
|
# PRIMERO (modelo de ACT 2779a5: head vacío + body con texto falla;
|
|
569
|
-
# title solo en body pasa; los de <template> son inertes)
|
|
784
|
+
# title solo en body pasa; los de <template> son inertes). El
|
|
785
|
+
# <title> de un <svg> es el NOMBRE del svg (accname): otra vía.
|
|
570
786
|
self._in_title = True
|
|
787
|
+
elif tag == 'title' and self._svg_depth > 0 and not self._in_template:
|
|
788
|
+
self._in_svg_title = True
|
|
789
|
+
self._svg_title_buf = []
|
|
571
790
|
elif tag == 'script':
|
|
572
791
|
self._in_script = True
|
|
573
792
|
if a.get('src'):
|
|
@@ -577,12 +796,18 @@ class _Auditor(HTMLParser):
|
|
|
577
796
|
elif tag == 'link':
|
|
578
797
|
if (a.get('rel') or '').lower() == 'stylesheet' and a.get('href'):
|
|
579
798
|
self._icon_links.append(a['href'])
|
|
799
|
+
elif tag == 'canvas':
|
|
800
|
+
# attrs ahora; el texto de reserva se recoge en el endtag (pop)
|
|
801
|
+
self.canvas_hidden[id(a)] = _hidden
|
|
580
802
|
elif tag == 'meta':
|
|
581
|
-
if a.get('name'
|
|
582
|
-
|
|
803
|
+
if (a.get('name') or '').lower() == 'viewport':
|
|
804
|
+
# el ÚLTIMO content decide (así se consume): su elem también
|
|
805
|
+
self.viewport = (a.get('content') or '')
|
|
806
|
+
self._viewport_elem = a
|
|
583
807
|
elif (a.get('http-equiv') or '').lower() == 'refresh':
|
|
584
|
-
self.meta_refresh = a.get('content'
|
|
585
|
-
self.meta_refreshes.append(a.get('content'
|
|
808
|
+
self.meta_refresh = (a.get('content') or '')
|
|
809
|
+
self.meta_refreshes.append((a.get('content') or ''))
|
|
810
|
+
self._meta_refresh_elems.append(a)
|
|
586
811
|
elif tag == 'img':
|
|
587
812
|
# la decisión de nombre es POST-parse (nombre accesible = alt u
|
|
588
813
|
# otras fuentes; presentación/none y hiddens quedan fuera)
|
|
@@ -592,6 +817,10 @@ class _Auditor(HTMLParser):
|
|
|
592
817
|
# la imagen interna aporta SU nombre completo al control
|
|
593
818
|
# (alt, aria-label, title, labelledby — resuelto post-parse)
|
|
594
819
|
self._ctrl[-1]['img_attrs'].append(a)
|
|
820
|
+
if a.get('id') and alt and not self._in_template:
|
|
821
|
+
# el alt de una img ES su nombre accesible: un aria-labelledby
|
|
822
|
+
# que apunte a esta img resuelve al alt (accname), no a ''
|
|
823
|
+
self._id_text_parts.setdefault(a['id'], []).append(alt)
|
|
595
824
|
if alt and not _hidden:
|
|
596
825
|
# el alt SE LEE: cuenta como texto bajo el lang de su
|
|
597
826
|
# contexto (de46e4 — una img con alt es contenido textual)
|
|
@@ -599,13 +828,16 @@ class _Auditor(HTMLParser):
|
|
|
599
828
|
if self._heading_level is not None and not _hidden \
|
|
600
829
|
and (a.get('role') or '').strip().lower() not in ('presentation', 'none'):
|
|
601
830
|
# nombre de la imagen (alt u otras fuentes) alimenta al
|
|
602
|
-
# encabezado — salvo presentación/none u oculta (ffd0e9)
|
|
831
|
+
# encabezado — salvo presentación/none u oculta (ffd0e9).
|
|
832
|
+
# NOTA: una img DENTRO de un heading no es evidencia de
|
|
833
|
+
# «imagen de texto» (1.4.5 exime logotipos; un gráfico de
|
|
834
|
+
# datos no es texto) — solo el alt kilométrico sigue siendo
|
|
835
|
+
# señal de revisión
|
|
603
836
|
_nom_img = alt or (a.get('aria-label') or '').strip() \
|
|
604
837
|
or (a.get('title') or '').strip()
|
|
605
838
|
if _nom_img:
|
|
606
839
|
self._heading_text.append(_nom_img)
|
|
607
|
-
|
|
608
|
-
elif len(alt) > 120:
|
|
840
|
+
if len(alt) > 120:
|
|
609
841
|
self.images_of_text.append(f'alt de {len(alt)} caracteres')
|
|
610
842
|
elif tag == 'iframe':
|
|
611
843
|
self.iframes_all.append((a, _hidden))
|
|
@@ -630,6 +862,8 @@ class _Auditor(HTMLParser):
|
|
|
630
862
|
elif tag == 'input':
|
|
631
863
|
self._field_note()
|
|
632
864
|
kind = (a.get('type') or 'text').lower()
|
|
865
|
+
if kind == 'password':
|
|
866
|
+
self._form_auth = True # 3.3.8: form con password = autenticación
|
|
633
867
|
if kind == 'image':
|
|
634
868
|
self.inputs_image.append((a, _hidden))
|
|
635
869
|
elif kind in ('submit', 'button', 'reset'):
|
|
@@ -639,18 +873,19 @@ class _Auditor(HTMLParser):
|
|
|
639
873
|
if kind == 'search' or re.search(r'search|busqueda|b[uú]squeda', (a.get('name') or '') + (a.get('id') or ''), re.I):
|
|
640
874
|
self.has_search = True
|
|
641
875
|
if kind in _FIELDS:
|
|
642
|
-
self.fields_raw.append((tag, kind, a, self.
|
|
876
|
+
self.fields_raw.append((tag, kind, a, self._wrap_labels(a), _hidden))
|
|
643
877
|
if 'autocomplete' not in a and kind != 'search' and (
|
|
644
878
|
kind in ('email', 'tel')
|
|
645
879
|
or _PERSONAL_DATA.search((a.get('name') or '') + ' ' + (a.get('id') or ''))):
|
|
646
880
|
self.missing_autocomplete.append(f'input type={kind} name={a.get("name") or "?"}'[:44])
|
|
881
|
+
self.autocomplete_elems.append(a)
|
|
647
882
|
if tag == 'input' and 'autocomplete' in a and 'disabled' not in a \
|
|
648
883
|
and (a.get('aria-disabled') or '').strip().lower() != 'true' and not _hidden:
|
|
649
884
|
# ABNF exacta de la regla ACT 73f2c2 (HTML autofill): [section-*]?
|
|
650
885
|
# [shipping|billing]? [home|work|mobile|fax|pager — solo si el
|
|
651
886
|
# siguiente es email/impp/tel/tel-*]? campo [webauthn]? — los
|
|
652
887
|
# campos disabled u hiddens quedan fuera (aplicabilidad)
|
|
653
|
-
_toks = (a['autocomplete'] or '').split()
|
|
888
|
+
_toks = [t.lower() for t in (a['autocomplete'] or '').split()]
|
|
654
889
|
_mal = None
|
|
655
890
|
if not (_toks == ['on'] or _toks == ['off']):
|
|
656
891
|
_i = 0
|
|
@@ -671,16 +906,26 @@ class _Auditor(HTMLParser):
|
|
|
671
906
|
_mal = _remainder[1]
|
|
672
907
|
elif len(_remainder) > 2:
|
|
673
908
|
_mal = _remainder[1]
|
|
909
|
+
if _mal is None and _remainder:
|
|
910
|
+
# 1.3.5 propósito contradicho: el type y el token de
|
|
911
|
+
# autocomplete de familias de dato distintas (determinista:
|
|
912
|
+
# type=email + postal-code SIEMPRE es error; type=email +
|
|
913
|
+
# username es el login por correo y queda exento)
|
|
914
|
+
_contra = _AUTOCOMPLETE_CONTRA.get(kind or 'text')
|
|
915
|
+
if _contra and _remainder[0].split(':')[-1] in _contra:
|
|
916
|
+
self.autocomplete_mismatch.append(
|
|
917
|
+
f'type={kind} autocomplete="{(a.get("autocomplete") or "")[:20]}"'[:56])
|
|
674
918
|
if _mal:
|
|
675
919
|
self.autocomplete_invalid.append(
|
|
676
920
|
f'{_mal} (input name={a.get("name") or "?"})'[:60])
|
|
677
921
|
elif tag in ('select', 'textarea'):
|
|
678
922
|
self._field_note()
|
|
679
|
-
self.fields_raw.append((tag, tag, a, self.
|
|
923
|
+
self.fields_raw.append((tag, tag, a, self._wrap_labels(a), _hidden))
|
|
680
924
|
elif tag == 'label':
|
|
681
925
|
self._label_depth += 1
|
|
682
926
|
self._label_text_current = []
|
|
683
927
|
self._labels_stack.append(False)
|
|
928
|
+
self._label_for_stack.append(a.get('for') or None)
|
|
684
929
|
if a.get('for'):
|
|
685
930
|
self._labels_for[a['for']] = self._labels_for.get(a['for'], 0) + 1
|
|
686
931
|
if self._labels_for[a['for']] > 1:
|
|
@@ -691,32 +936,77 @@ class _Auditor(HTMLParser):
|
|
|
691
936
|
elif tag == 'blink':
|
|
692
937
|
self.mobiles.append('<blink>')
|
|
693
938
|
elif tag == 'track':
|
|
694
|
-
kind
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
939
|
+
# sin kind (o kind vacío/None), el valor por defecto del spec HTML
|
|
940
|
+
# es «subtitles» — cuenta como captions (no exigir el atributo).
|
|
941
|
+
# SOLO dentro de un <video>: un track huérfano (o en <template>)
|
|
942
|
+
# jamás acredita captions de un vídeo que no es suyo
|
|
943
|
+
kind = (a.get('kind') or 'subtitles').lower()
|
|
944
|
+
if self._video_caps_stack and not self._in_template:
|
|
945
|
+
if kind == 'descriptions':
|
|
946
|
+
self._video_caps_stack[-1][2] = True
|
|
947
|
+
elif kind in ('captions', 'subtitles'):
|
|
948
|
+
self._video_caps_stack[-1][1] = True
|
|
699
949
|
elif tag in ('video', 'audio'):
|
|
700
|
-
if tag == 'video':
|
|
950
|
+
if tag == 'video' and 'muted' not in a:
|
|
951
|
+
# muted = el hero de fondo sin pista audible: 1.2.2/1.2.3
|
|
952
|
+
# aplican a vídeo CON audio — no se exige track a lo inaudible
|
|
701
953
|
self.videos += 1
|
|
702
954
|
self._in_video = True
|
|
703
|
-
|
|
955
|
+
self._video_caps_stack.append([a, False, False])
|
|
956
|
+
# 1.4.2 aplica a audio QUE SUENA sin control: muted = nada audible;
|
|
957
|
+
# controls = el usuario puede pararlo — ambos pasan (el hero-video
|
|
958
|
+
# muted de toda landing no es un fallo de Audio Control)
|
|
959
|
+
if 'autoplay' in a and 'muted' not in a and 'controls' not in a \
|
|
960
|
+
and not self._in_template:
|
|
704
961
|
self.media_autoplay += 1
|
|
962
|
+
self.media_autoplay_elems.append(a)
|
|
705
963
|
elif tag in ('ul', 'ol'):
|
|
706
964
|
self._list_depth += 1
|
|
707
965
|
elif tag == 'li':
|
|
708
966
|
self._li_depth += 1
|
|
709
967
|
elif tag == 'table':
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
968
|
+
# role=presentation/none la declara de MAQUETACIÓN: no se exige th
|
|
969
|
+
# (el mail HTML y las grids legacy viven aquí) — y el contenido de
|
|
970
|
+
# <template> es inerte
|
|
971
|
+
if (a.get('role') or '').strip().lower() in ('presentation', 'none') \
|
|
972
|
+
or self._in_template:
|
|
973
|
+
pass
|
|
974
|
+
else:
|
|
975
|
+
self.tables += 1
|
|
976
|
+
self._in_table = True
|
|
977
|
+
# sospecha de maquetación (attrs presentacionales de la era
|
|
978
|
+
# <table width=… cellpadding=0 border=0>): sin th NI marcadores
|
|
979
|
+
# de datos no se exige th (FP clásico años-90). OJO border:
|
|
980
|
+
# el spec dice que border≠0 declara tabla de DATOS — solo el
|
|
981
|
+
# «0» (o sin valor, que es 0) es maquetación
|
|
982
|
+
_bv = (a.get('border') or '0').strip()
|
|
983
|
+
_border_data = _bv.isdecimal() and int(_bv) > 0
|
|
984
|
+
_suspect = (bool({'cellpadding', 'cellspacing', 'width'} & set(a))
|
|
985
|
+
or ('border' in a and not _border_data)) and not _border_data
|
|
986
|
+
_data = 'summary' in a or _border_data
|
|
987
|
+
# pila por tabla anidada, CON IDENTIDAD: una </table> de una
|
|
988
|
+
# tabla presentation/none (no apilada) jamás popea la entrada
|
|
989
|
+
# de la tabla externa que la envuelve
|
|
990
|
+
self._table_stack.append([self._th_in_table, a, _suspect, _data])
|
|
991
|
+
self._th_in_table = False
|
|
713
992
|
elif tag == 'th':
|
|
714
993
|
self._th_in_table = True
|
|
994
|
+
elif tag == 'caption' and self._table_stack:
|
|
995
|
+
self._table_stack[-1][3] = True # marcador de tabla de DATOS
|
|
996
|
+
elif tag == 'td' and self._table_stack and ('scope' in a or 'headers' in a):
|
|
997
|
+
self._table_stack[-1][3] = True # asociaciones explícitas = datos
|
|
715
998
|
elif tag == 'main' or (a.get('role') or '').lower() == 'main':
|
|
716
999
|
self.hay_main = True
|
|
1000
|
+
if a.get('id'):
|
|
1001
|
+
self._landmark_ids.add(a['id'])
|
|
717
1002
|
elif tag not in _CONTROLS + ('input', 'select', 'textarea', 'label', 'option',
|
|
718
1003
|
'video', 'audio', 'details', 'summary'):
|
|
719
|
-
_role_v = a.get('role'
|
|
1004
|
+
_role_v = (a.get('role') or '').strip().lower()
|
|
1005
|
+
if _role_v in ('group', 'radiogroup') and not self._in_template:
|
|
1006
|
+
# grupo con nombre accesible = alternativa legítima al fieldset
|
|
1007
|
+
# (técnica ARIA de H71): se computa al abrir, se cierra en endtag
|
|
1008
|
+
if a.get('aria-label') or a.get('aria-labelledby'):
|
|
1009
|
+
self._group_role_depth += 1
|
|
720
1010
|
if _role_v in _ROLE_FIELDS and _role_v not in ('none', 'presentation'):
|
|
721
1011
|
if a.get('id'):
|
|
722
1012
|
self._role_field_ids.add(a['id'])
|
|
@@ -733,16 +1023,35 @@ class _Auditor(HTMLParser):
|
|
|
733
1023
|
'inner_img': False,
|
|
734
1024
|
'img_attrs': [], 'hidden': _hidden, 'depth': self._depth,
|
|
735
1025
|
'kind': 'role:' + _role_v})
|
|
1026
|
+
# 2.1.1: un rol interactivo en tag NO enfocable de nacimiento
|
|
1027
|
+
# exige tabindex — sin él el control es inalcanzable por
|
|
1028
|
+
# teclado (el JS podría añadirlo en runtime: señal de revisión,
|
|
1029
|
+
# el pase rendered confirma). Los <template> son inertes.
|
|
1030
|
+
if 'tabindex' not in a and not _hidden:
|
|
1031
|
+
self.role_no_tabindex.append(f'{tag}[role={_role_v}]')
|
|
1032
|
+
self.role_no_tabindex_elems.append(a)
|
|
736
1033
|
elif _role_v == 'img' and tag != 'img':
|
|
737
1034
|
# div[role=img] con imagen de fondo: también necesita nombre (23a2a8)
|
|
738
1035
|
self.imgs_all.append((a, _hidden))
|
|
739
|
-
if a.get('onclick') and not
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
1036
|
+
if a.get('onclick') and _role_v not in ('button', 'link') \
|
|
1037
|
+
and 'tabindex' not in a and not self._in_template:
|
|
1038
|
+
# candidato a «click no enfocable»: se CONFIRMA al cerrar salvo
|
|
1039
|
+
# que el subárbol contenga un control nativo (delegación de
|
|
1040
|
+
# eventos / wrappers de analytics sobre un <button> real)
|
|
1041
|
+
if tag in _VOID:
|
|
1042
|
+
self.stray_clicks.append(tag)
|
|
1043
|
+
self.stray_click_elems.append(a)
|
|
1044
|
+
else:
|
|
1045
|
+
self._stray_pend.append([tag, a, self._depth, False])
|
|
1046
|
+
# v3.9: 2.5.2 sospecha de activación en down-event — PERO solo si el
|
|
1047
|
+
# elemento no completa en up (onclick/onpointerup/onmouseup presentes):
|
|
1048
|
+
# un mousedown de arrastre/selección con click normal NO es down-event
|
|
1049
|
+
if not self._in_template:
|
|
1050
|
+
for _de in ('onmousedown', 'ontouchstart', 'onpointerdown'):
|
|
1051
|
+
if a.get(_de):
|
|
1052
|
+
if not (a.get('onclick') or a.get('onpointerup') or a.get('onmouseup')):
|
|
1053
|
+
self.down_events.append(f'{tag}[{_de}]')
|
|
1054
|
+
break
|
|
746
1055
|
# v3.12: 2.2.2 inline looping animation
|
|
747
1056
|
style = a.get('style') or ''
|
|
748
1057
|
if 'animation' in style and 'infinite' in style:
|
|
@@ -751,29 +1060,39 @@ class _Auditor(HTMLParser):
|
|
|
751
1060
|
if a.get('ontouchmove') or a.get('ondrag'):
|
|
752
1061
|
if not (a.get('onclick') or tag in ('input', 'button', 'a')):
|
|
753
1062
|
self.gestures.append(f'{tag}[{list(a)[0] if a else ""}]')
|
|
1063
|
+
# 2.1.1: onfocus="blur()" — el control se quita a sí mismo el foco
|
|
1064
|
+
# en cuanto el teclado lo deja ahí: inalcanzable por teclado. El
|
|
1065
|
+
# caso exacto que el scanner de GitHub no caza (issue 288 suyo).
|
|
1066
|
+
_of = (a.get('onfocus') or '')
|
|
1067
|
+
if 'blur' in _of.lower():
|
|
1068
|
+
self.focus_blur.append(f'<{tag} onfocus="{_of[:30]}">')
|
|
1069
|
+
self.focus_blur_elems.append(a)
|
|
754
1070
|
# forms: placeholder-only, required sin indicio, financial
|
|
755
1071
|
if tag == 'form':
|
|
756
1072
|
self._financial_form = False
|
|
757
1073
|
self._confirm_form = False
|
|
758
|
-
|
|
1074
|
+
self._form_captchas = []
|
|
1075
|
+
action = (a.get('action') or '').lower() + (a.get('id') or '').lower()
|
|
759
1076
|
if re.search(r'pay|purchase|checkout|buy|order|contract|legal|billing',
|
|
760
1077
|
action, re.I):
|
|
761
1078
|
self._financial_form = True
|
|
1079
|
+
if re.search(r'login|log-in|signin|sign-in|auth|session|sso|register|'
|
|
1080
|
+
r'registro|acces|password', action, re.I):
|
|
1081
|
+
self._form_auth = True
|
|
762
1082
|
if tag in ('input', 'textarea') and a.get('placeholder') \
|
|
763
1083
|
and not (a.get('aria-label') or a.get('aria-labelledby')):
|
|
764
1084
|
# candidato a placeholder-only: se confirma POST-parse (un
|
|
765
1085
|
# <label for> con su id le da nombre real y lo retira)
|
|
766
|
-
self._placeholder_candidates.append((tag, a, self.
|
|
1086
|
+
self._placeholder_candidates.append((tag, a, self._wrap_labels(a), _hidden))
|
|
767
1087
|
if a.get('required') is not None or 'required' in a or a.get('aria-required') == 'true':
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
self.required_no_indication.append(
|
|
772
|
-
f'{tag}[name={a.get("name","?")}]')
|
|
1088
|
+
# required sin indicación: la decisión es POST-parse — el «*»
|
|
1089
|
+
# puede vivir en el texto del <label for> (declarado después)
|
|
1090
|
+
self._required_pend.append((tag, a))
|
|
773
1091
|
if tag == 'input' and a.get('type') == 'radio':
|
|
774
1092
|
nm = a.get('name') or '(no name)'
|
|
775
1093
|
self._radio_group[nm] = self._radio_group.get(nm, 0) + 1
|
|
776
1094
|
self._radio_in_fieldset[nm] = self._in_fieldset
|
|
1095
|
+
self._radio_in_group[nm] = self._group_role_depth > 0
|
|
777
1096
|
if tag == 'fieldset':
|
|
778
1097
|
self._in_fieldset = True
|
|
779
1098
|
if tag in ('button', 'input'):
|
|
@@ -783,15 +1102,18 @@ class _Auditor(HTMLParser):
|
|
|
783
1102
|
# checkbox de términos
|
|
784
1103
|
if tag == 'input' and a.get('type') == 'checkbox':
|
|
785
1104
|
nm = (a.get('name') or '').lower()
|
|
786
|
-
|
|
1105
|
+
# el patrón español más común («confirmo», «revisado») era
|
|
1106
|
+
# invisible para un regex anglocéntrico: una casilla de
|
|
1107
|
+
# confirmación/revisión ES un paso de revisión (3.3.4)
|
|
1108
|
+
if re.search(r'terms|accept|agree|terminos|aceptar|legal|privacy'
|
|
1109
|
+
r'|confirm|revisado|revisar', nm):
|
|
787
1110
|
self._confirm_form = True
|
|
788
1111
|
if a.get('draggable') and (a.get('draggable') or '').lower() != 'false':
|
|
789
1112
|
if not a.get('onclick') and tag not in ('input', 'button'):
|
|
790
1113
|
self.drag_handlers.append(f'{tag}[draggable]')
|
|
791
1114
|
if a.get('aria-live') or (a.get('role') or '').lower() in ('status', 'alert', 'log'):
|
|
792
|
-
self.
|
|
793
|
-
|
|
794
|
-
self.char_shortcuts.append(f'{tag}[accesskey]')
|
|
1115
|
+
if not self._in_template:
|
|
1116
|
+
self.status_regions += 1
|
|
795
1117
|
# v3.12: 2.5.4 motion actuation handlers
|
|
796
1118
|
for _ma in ('ondeviceorientation', 'ondevicemotion'):
|
|
797
1119
|
if a.get(_ma):
|
|
@@ -800,19 +1122,22 @@ class _Auditor(HTMLParser):
|
|
|
800
1122
|
if tag == 'meta' and 'orientation' in (a.get('content') or '').lower() \
|
|
801
1123
|
and 'lock' in (a.get('content') or '').lower():
|
|
802
1124
|
self.orientation_locks.append('meta orientation lock')
|
|
803
|
-
# v3.9: 3.3.8 captcha
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
1125
|
+
# v3.9: 3.3.8 captcha — SOLO dentro de un form de autenticación (la
|
|
1126
|
+
# decisión es del endtag del form: ahí se sabe si hubo password/login)
|
|
1127
|
+
if not self._in_template:
|
|
1128
|
+
for _v in (a.get('src') or '', a.get('href') or '', a.get('id') or ''):
|
|
1129
|
+
if re.search(r'recaptcha|hcaptcha|turnstile|captcha', _v, re.I):
|
|
1130
|
+
self._form_captchas.append(f'{tag} {_v[:50]}')
|
|
1131
|
+
break
|
|
1132
|
+
if (a.get('name') or '').lower().find('captcha') >= 0:
|
|
1133
|
+
self._form_captchas.append(f'input name={a["name"][:30]}')
|
|
1134
|
+
# v3.1/v3.3: validez ARIA (atributos, referencias y VALORES) — el
|
|
1135
|
+
# contenido de <template> es inerte: sus aria-* no existen en el DOM
|
|
1136
|
+
for _ar in _ARIA_IDREFS if not self._in_template else ():
|
|
812
1137
|
if a.get(_ar):
|
|
813
1138
|
for _ref in a[_ar].split():
|
|
814
1139
|
self.aria_refs.append((_ar, _ref))
|
|
815
|
-
for _ar, _val in a.items():
|
|
1140
|
+
for _ar, _val in a.items() if not self._in_template else ():
|
|
816
1141
|
if not _ar.startswith('aria-'):
|
|
817
1142
|
continue
|
|
818
1143
|
_val = (_val or '').strip().lower()
|
|
@@ -822,7 +1147,11 @@ class _Auditor(HTMLParser):
|
|
|
822
1147
|
and not (_val == 'mixed' and _ar in ('aria-pressed', 'aria-checked')) \
|
|
823
1148
|
and not (_val == 'undefined' and _ar in _ARIA_BOOL_UNDEFINED):
|
|
824
1149
|
self.aria_values.append({'attr': _ar, 'val': _val, 'type': 'bool'})
|
|
825
|
-
elif _ar in _ARIA_INT and not _val.isdigit()
|
|
1150
|
+
elif _ar in _ARIA_INT and not _val.isdigit() \
|
|
1151
|
+
and not (_val == '-1' and _ar in ('aria-rowcount', 'aria-colcount',
|
|
1152
|
+
'aria-setsize')):
|
|
1153
|
+
# -1 en rowcount/colcount/setsize es OBLIGATORIO cuando el
|
|
1154
|
+
# total es desconocido (ARIA 1.2) — grids virtualizadas
|
|
826
1155
|
self.aria_values.append({'attr': _ar, 'val': _val, 'type': 'int'})
|
|
827
1156
|
elif _ar in _ARIA_NUM:
|
|
828
1157
|
try:
|
|
@@ -839,7 +1168,7 @@ class _Auditor(HTMLParser):
|
|
|
839
1168
|
self.aria_values.append({'attr': _ar, 'val': _val,
|
|
840
1169
|
'type': 'tokens',
|
|
841
1170
|
'valid_tokens': '/'.join(sorted(v for v in _ARIA_TOKENS[_ar] if v))})
|
|
842
|
-
if a.get('role'):
|
|
1171
|
+
if a.get('role') and not self._in_template:
|
|
843
1172
|
# role admite LISTA de tokens separados por espacios (con
|
|
844
1173
|
# fallback): TODOS deben ser roles válidos, no solo el primero
|
|
845
1174
|
for role in a['role'].strip().lower().split():
|
|
@@ -851,35 +1180,47 @@ class _Auditor(HTMLParser):
|
|
|
851
1180
|
landmark_role = a.get('role', '').lower() if a.get('role') in (
|
|
852
1181
|
'banner', 'contentinfo', 'navigation', 'complementary', 'main', 'form', 'search', 'region') else None
|
|
853
1182
|
lm = tag if tag in ('header', 'footer', 'nav', 'aside', 'main', 'search') else landmark_role
|
|
854
|
-
if lm and not
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
1183
|
+
if lm and not self._in_template:
|
|
1184
|
+
if a.get('id'):
|
|
1185
|
+
self._landmark_ids.add(a['id'])
|
|
1186
|
+
if lm == 'search':
|
|
1187
|
+
# un landmark search ES un mecanismo de búsqueda (2.4.5)
|
|
1188
|
+
self.has_search = True
|
|
1189
|
+
if not (a.get('aria-label') or a.get('aria-labelledby')):
|
|
1190
|
+
t = self.landmarks.setdefault(lm, [0, 0])
|
|
1191
|
+
t[0] += 1
|
|
1192
|
+
t[1] += 1
|
|
1193
|
+
else:
|
|
1194
|
+
self.landmarks.setdefault(lm, [0, 0])[1] += 1
|
|
1195
|
+
if a.get('accesskey') and not self._in_template:
|
|
1196
|
+
k = (a.get('accesskey') or '').strip().lower()
|
|
1197
|
+
if k:
|
|
1198
|
+
self.accesskeys[k] = self.accesskeys.get(k, 0) + 1
|
|
863
1199
|
if self._list_depth > 0 and self._li_depth == 0 \
|
|
864
1200
|
and tag not in ('li', 'script', 'template', 'ul', 'ol'):
|
|
865
1201
|
self._bad_list += 1
|
|
866
1202
|
# 4.1.2/2.1.2: enfocable dentro de un subárbol aria-hidden=true — el
|
|
867
1203
|
# aria-hidden=false anidado NO exime (ACT 6cfa84). No es enfocable:
|
|
868
|
-
# hidden por CSS/hidden (fuera de la navegación por tab
|
|
869
|
-
#
|
|
1204
|
+
# hidden por CSS/hidden (fuera de la navegación por tab — INCLUIDO el
|
|
1205
|
+
# display:none POR CLASE, el patrón hamburguesa .menu{display:none}),
|
|
1206
|
+
# tabindex negativo (cualquiera, no solo -1), o disabled.
|
|
870
1207
|
_ti_raw = (a.get('tabindex') or '').strip()
|
|
871
1208
|
_ti_num = None
|
|
872
|
-
|
|
1209
|
+
# isdecimal (NO isdigit): '²' pasa isdigit y revienta int() — un
|
|
1210
|
+
# atributo exótico jamás destruye el informe de 3 MB
|
|
1211
|
+
_ti_dec = _ti_raw if _ti_raw.isdecimal() else (
|
|
1212
|
+
_ti_raw[1:] if _ti_raw[:1] == '-' and _ti_raw[1:].isdecimal() else '')
|
|
1213
|
+
if _ti_dec != '':
|
|
873
1214
|
_ti_num = int(_ti_raw)
|
|
874
1215
|
_css_hidden = 'hidden' in a or 'display:none' in _style or 'visibility:hidden' in _style \
|
|
875
|
-
or self._css_hidden_stack[-1]
|
|
1216
|
+
or self._css_hidden_stack[-1] or self._focus_hidden_class()
|
|
876
1217
|
_native = (tag in ('button', 'summary', 'select', 'textarea', 'iframe')
|
|
877
1218
|
or (tag in ('a', 'area') and (a.get('href') or '').strip())
|
|
878
1219
|
or (tag == 'input' and (a.get('type') or 'text').lower() != 'hidden')
|
|
879
1220
|
or (tag in ('video', 'audio') and 'controls' in a))
|
|
880
1221
|
_enfocable = ((_native and 'disabled' not in a)
|
|
881
1222
|
or (_ti_num is not None and _ti_num >= 0))
|
|
882
|
-
if _ti_num
|
|
1223
|
+
if (_ti_num is not None and _ti_num < 0) or _css_hidden:
|
|
883
1224
|
_enfocable = False
|
|
884
1225
|
# centinela de foco off-screen (patrón modal): un link fuera de vista
|
|
885
1226
|
# cuyo id aparece en los scripts (el wiring de focus) NO cuenta — la
|
|
@@ -887,59 +1228,136 @@ class _Auditor(HTMLParser):
|
|
|
887
1228
|
# llegar DESPUÉS del link: la decisión se difiere a post-parse
|
|
888
1229
|
if (_hidden_aria or self._ah_true_depth > 0) and _enfocable:
|
|
889
1230
|
if re.search(r'(top|left)\s*:\s*-\d{3,}', a.get('style') or '', re.I):
|
|
890
|
-
self._ahf_deferred.append((tag, a.get('id')))
|
|
1231
|
+
self._ahf_deferred.append((tag, a, a.get('id')))
|
|
891
1232
|
else:
|
|
892
1233
|
self.aria_hidden_focusable.append(tag)
|
|
1234
|
+
self.aria_hidden_focusable_elems.append(a)
|
|
893
1235
|
if tag == 'area' and (a.get('href') or '').strip():
|
|
894
1236
|
# <area> es void: sin pila de control — se registra directo (el
|
|
895
1237
|
# nombre le llega del alt)
|
|
896
1238
|
self.controls_raw.append(('area', a, '', [], _hidden))
|
|
897
1239
|
if tag in ('h1', 'h2', 'h3', 'h4', 'h5', 'h6'):
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
1240
|
+
# role=none/presentation APAGA la semántica del encabezado; un
|
|
1241
|
+
# aria-level válido la SOBRESCRIBE (accname: h3[aria-level=4] ES 4)
|
|
1242
|
+
if (a.get('role') or '').strip().lower() in ('none', 'presentation') \
|
|
1243
|
+
or self._in_template:
|
|
1244
|
+
pass
|
|
1245
|
+
else:
|
|
1246
|
+
self._heading_level = int(tag[1])
|
|
1247
|
+
_alv = re.match(r'\d+', str(a.get('aria-level') or ''))
|
|
1248
|
+
if _alv:
|
|
1249
|
+
self._heading_level = int(_alv.group())
|
|
1250
|
+
self._heading_text = []
|
|
1251
|
+
self._heading_attrs = a
|
|
1252
|
+
self._heading_route = self._elem_paths.get(id(a))
|
|
1253
|
+
self._heading_hidden = _hidden
|
|
1254
|
+
self._heading_tag = tag
|
|
1255
|
+
elif (a.get('role') or '').lower() == 'heading' and not self._in_template:
|
|
1256
|
+
# role=heading cuenta como encabezado para el nombre (ffd0e9); sin
|
|
1257
|
+
# aria-level el nivel por defecto de ARIA es 2 — y un aria-level
|
|
1258
|
+
# basura JAMÁS tira el parse (int guardado)
|
|
1259
|
+
_alv = re.match(r'\d+', str(a.get('aria-level') or ''))
|
|
1260
|
+
self._heading_level = int(_alv.group()) if _alv else 2
|
|
906
1261
|
self._heading_text = []
|
|
907
1262
|
self._heading_attrs = a
|
|
1263
|
+
self._heading_route = self._elem_paths.get(id(a))
|
|
908
1264
|
self._heading_hidden = _hidden
|
|
909
1265
|
self._heading_tag = tag
|
|
910
1266
|
ti = a.get('tabindex')
|
|
911
|
-
if ti and ti.
|
|
1267
|
+
if ti and ti.isdecimal() and int(ti) > 0 and not self._in_template:
|
|
912
1268
|
self.positive_tabindices.append((tag, int(ti)))
|
|
1269
|
+
self.positive_tabindex_elems.append(a)
|
|
913
1270
|
|
|
914
1271
|
def handle_endtag(self, tag):
|
|
1272
|
+
# pila de rutas del kernel: pop normal si casa; si hay anidamiento
|
|
1273
|
+
# malformado, se descarta hasta el que casa; suelto, se ignora
|
|
1274
|
+
if self._path_stack:
|
|
1275
|
+
if self._path_stack[-1][0] == tag:
|
|
1276
|
+
self._path_stack.pop()
|
|
1277
|
+
else:
|
|
1278
|
+
for _i in range(len(self._path_stack) - 1, -1, -1):
|
|
1279
|
+
if self._path_stack[_i][0] == tag:
|
|
1280
|
+
del self._path_stack[_i:]
|
|
1281
|
+
break
|
|
915
1282
|
if tag not in _VOID:
|
|
916
|
-
|
|
917
|
-
|
|
1283
|
+
# LAS PILAS SE SINCRONIZAN como _path_stack: buscar el frame que
|
|
1284
|
+
# casa y descartar hasta él (un </span> suelto ya no arrastra el
|
|
1285
|
+
# elemento abierto de verdad — el texto no se malatribuye)
|
|
1286
|
+
_idx = None
|
|
1287
|
+
for _i in range(len(self._el_stack) - 1, -1, -1):
|
|
1288
|
+
if self._el_stack[_i][0] == tag:
|
|
1289
|
+
_idx = _i
|
|
1290
|
+
break
|
|
1291
|
+
if _idx is None:
|
|
1292
|
+
# endtag suelto… salvo controles: el navegador MANTIENE el
|
|
1293
|
+
# <a> abierto a través del </div> que lo arrastró (adoption
|
|
1294
|
+
# agency) — el enlace es real y hay que contarlo
|
|
1295
|
+
if tag in _CONTROLS:
|
|
1296
|
+
self._close_control(tag)
|
|
1297
|
+
return
|
|
1298
|
+
_nframes = len(self._el_stack) - _idx
|
|
1299
|
+
_closed_attrs = None # attrs del frame que CASA (el último popeado)
|
|
1300
|
+
for _ in range(_nframes):
|
|
1301
|
+
if not self._el_stack:
|
|
1302
|
+
break
|
|
918
1303
|
_etag, _eattrs, _ebuf = self._el_stack.pop()
|
|
1304
|
+
_closed_attrs = _eattrs
|
|
1305
|
+
if _etag == 'canvas':
|
|
1306
|
+
self.canvases.append((_eattrs, ' '.join(_ebuf).strip(),
|
|
1307
|
+
self.canvas_hidden.pop(id(_eattrs), False)))
|
|
919
1308
|
if _eattrs.get('id') and _eattrs['id'] in self._role_field_ids:
|
|
920
1309
|
self._field_buffers[_eattrs['id']] = _ebuf
|
|
921
1310
|
elif (_eattrs.get('role') or '').strip().lower() in _ROLE_FIELDS:
|
|
922
1311
|
self._role_field_text.append((_eattrs, ' '.join(_ebuf).strip()))
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
1312
|
+
if (_eattrs.get('role') or '').strip().lower() in ('group', 'radiogroup') \
|
|
1313
|
+
and self._group_role_depth > 0:
|
|
1314
|
+
self._group_role_depth -= 1
|
|
1315
|
+
# candidato stray-click que cierra: confirmar salvo delegación
|
|
1316
|
+
for _sp in self._stray_pend[:]:
|
|
1317
|
+
if _sp[1] is _eattrs:
|
|
1318
|
+
self._stray_pend.remove(_sp)
|
|
1319
|
+
if not _sp[3]:
|
|
1320
|
+
self.stray_clicks.append(_sp[0])
|
|
1321
|
+
self.stray_click_elems.append(_sp[1])
|
|
1322
|
+
if len(self._hidden_stack) > 1:
|
|
1323
|
+
self._hidden_stack.pop()
|
|
1324
|
+
self._css_hidden_stack.pop()
|
|
1325
|
+
if self._ah_true_stack and self._ah_true_stack.pop():
|
|
928
1326
|
self._ah_true_depth = max(0, self._ah_true_depth - 1)
|
|
1327
|
+
self._depth = max(0, self._depth - _nframes)
|
|
929
1328
|
self._open_ids = [(i, d) for (i, d) in self._open_ids if d <= self._depth]
|
|
930
1329
|
# controles cierran con SU etiqueta Y a SU profundidad — un <div>
|
|
931
1330
|
# anidado dentro de un div[role=button] no cierra el control (React)
|
|
932
1331
|
if self._ctrl and self._ctrl[-1]['tag'] == tag \
|
|
933
1332
|
and self._depth == self._ctrl[-1].get('depth', 0) - 1:
|
|
934
1333
|
self._close_control(tag)
|
|
935
|
-
if tag == '
|
|
936
|
-
self._in_head = False
|
|
937
|
-
elif tag == 'template':
|
|
1334
|
+
if tag == 'template':
|
|
938
1335
|
self._in_template = max(0, self._in_template - 1)
|
|
1336
|
+
if tag == 'svg':
|
|
1337
|
+
self._svg_depth = max(0, self._svg_depth - 1)
|
|
939
1338
|
if tag == 'title':
|
|
940
|
-
self.
|
|
941
|
-
|
|
942
|
-
|
|
1339
|
+
if self._in_svg_title:
|
|
1340
|
+
# <title> de svg: nombre del svg — alimenta al control abierto
|
|
1341
|
+
# (name-from-content: el botón-icono del W3C) y al registro
|
|
1342
|
+
# id→texto (labelledby al svg resuelve a su título)
|
|
1343
|
+
_svgtxt = ' '.join(self._svg_title_buf).strip()
|
|
1344
|
+
if _svgtxt:
|
|
1345
|
+
if self._ctrl:
|
|
1346
|
+
# nombre SÍ (accname from content); VISIBLE no — el
|
|
1347
|
+
# <title> de svg es texto alternativo, no renderizado
|
|
1348
|
+
self._ctrl[-1]['text'].append(_svgtxt)
|
|
1349
|
+
for _fr in reversed(self._el_stack):
|
|
1350
|
+
if _fr[0] == 'svg':
|
|
1351
|
+
self._svg_titles[id(_fr[1])] = _svgtxt
|
|
1352
|
+
if _fr[1].get('id'):
|
|
1353
|
+
self._id_text_parts.setdefault(_fr[1]['id'], []).append(_svgtxt)
|
|
1354
|
+
break
|
|
1355
|
+
self._in_svg_title = False
|
|
1356
|
+
self._svg_title_buf = []
|
|
1357
|
+
else:
|
|
1358
|
+
self._in_title = False
|
|
1359
|
+
self._titles_in_order.append(' '.join(self._title_buf))
|
|
1360
|
+
self._title_buf = []
|
|
943
1361
|
elif tag == 'script':
|
|
944
1362
|
self._in_script = False
|
|
945
1363
|
elif tag == 'style':
|
|
@@ -952,6 +1370,11 @@ class _Auditor(HTMLParser):
|
|
|
952
1370
|
if txt and (len(txt) < 2 or re.fullmatch(
|
|
953
1371
|
r'(campo|field|input|texto|text|dato|value|entrada|box|caja)[\s\d]*', lowered)):
|
|
954
1372
|
self.vague_labels.append(f'"{txt[:30]}"')
|
|
1373
|
+
# texto del label POR SU for: el «*» del required puede vivir aquí
|
|
1374
|
+
if self._label_for_stack:
|
|
1375
|
+
_lfor = self._label_for_stack.pop()
|
|
1376
|
+
if _lfor and txt:
|
|
1377
|
+
self._label_text_for[_lfor] = txt
|
|
955
1378
|
if self._labels_stack and not self._labels_stack.pop():
|
|
956
1379
|
self.orphan_labels += 1
|
|
957
1380
|
elif tag == 'fieldset':
|
|
@@ -959,6 +1382,13 @@ class _Auditor(HTMLParser):
|
|
|
959
1382
|
elif tag == 'form':
|
|
960
1383
|
if self._financial_form and not self._confirm_form:
|
|
961
1384
|
self.financial_no_confirm += 1
|
|
1385
|
+
# 3.3.8 Accessible Authentication: SOLO en proceso de autenticación
|
|
1386
|
+
# (form con password o acción de login) — un captcha en un form de
|
|
1387
|
+
# contacto no es un fallo de 3.3.8
|
|
1388
|
+
if self._form_auth:
|
|
1389
|
+
self.captchas.extend(self._form_captchas)
|
|
1390
|
+
self._form_captchas = []
|
|
1391
|
+
self._form_auth = False
|
|
962
1392
|
elif tag == 'nav':
|
|
963
1393
|
self._in_nav = max(0, self._in_nav - 1)
|
|
964
1394
|
elif tag == 'li':
|
|
@@ -969,13 +1399,29 @@ class _Auditor(HTMLParser):
|
|
|
969
1399
|
self._close_control(tag)
|
|
970
1400
|
elif tag == 'video':
|
|
971
1401
|
self._in_video = False
|
|
1402
|
+
if self._video_caps_stack:
|
|
1403
|
+
_vattrs, _vcaps, _vdesc = self._video_caps_stack.pop()
|
|
1404
|
+
if not _vcaps:
|
|
1405
|
+
self.videos_no_caps_elems.append(_vattrs)
|
|
1406
|
+
if not _vdesc:
|
|
1407
|
+
self.videos_no_desc_elems.append(_vattrs)
|
|
972
1408
|
elif tag == 'table':
|
|
973
|
-
if self.
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
1409
|
+
if self._table_stack and _closed_attrs is not None:
|
|
1410
|
+
_th_saved, _tattrs, _suspect, _data = self._table_stack[-1]
|
|
1411
|
+
# IDENTIDAD: solo decide la entrada cuya tabla se CIERRA (el
|
|
1412
|
+
# </table> de una presentation/template NUNCA apilada resbala
|
|
1413
|
+
# sin tocar la pila — antes popeaba la entrada de la externa)
|
|
1414
|
+
if _closed_attrs is _tattrs:
|
|
1415
|
+
self._table_stack.pop()
|
|
1416
|
+
if self._th_in_table:
|
|
1417
|
+
self.tables_with_th += 1
|
|
1418
|
+
elif _data or not _suspect:
|
|
1419
|
+
self.tables_no_th_elems.append(_tattrs)
|
|
1420
|
+
else:
|
|
1421
|
+
# maquetación por heurística: fuera del cómputo
|
|
1422
|
+
self.tables -= 1
|
|
1423
|
+
self._th_in_table = _th_saved
|
|
1424
|
+
self._in_table = bool(self._table_stack)
|
|
979
1425
|
elif tag == 'th':
|
|
980
1426
|
pass
|
|
981
1427
|
elif self._heading_level and tag == getattr(self, '_heading_tag', None):
|
|
@@ -983,7 +1429,8 @@ class _Auditor(HTMLParser):
|
|
|
983
1429
|
# aria-label tras strip, nombres de imgs internas)
|
|
984
1430
|
self.headings_raw.append((self._heading_level, dict(self._heading_attrs or {}),
|
|
985
1431
|
' '.join(self._heading_text).strip(),
|
|
986
|
-
getattr(self, '_heading_hidden', False)
|
|
1432
|
+
getattr(self, '_heading_hidden', False),
|
|
1433
|
+
getattr(self, '_heading_route', None)))
|
|
987
1434
|
self._heading_level = None
|
|
988
1435
|
|
|
989
1436
|
_RE_CHAR_KEY = re.compile(r'key(?:Code)?\s*===?\s*["\']([a-zA-Z0-9])["\']', re.S)
|
|
@@ -1026,26 +1473,49 @@ class _Auditor(HTMLParser):
|
|
|
1026
1473
|
self.lang_parts_invalid.append(_mark)
|
|
1027
1474
|
return
|
|
1028
1475
|
|
|
1029
|
-
_RE_RULE = re.compile(r'
|
|
1476
|
+
_RE_RULE = re.compile(r'([^{}]+)\{([^}]*)\}')
|
|
1030
1477
|
_RE_HIDDEN_STYLE = re.compile(r'clip-path|display\s*:\s*none|visibility\s*:\s*hidden'
|
|
1031
1478
|
r'|height\s*:\s*1px|width\s*:\s*1px|opacity\s*:\s*0')
|
|
1479
|
+
# subconjunto ESTRICTO para focuseabilidad: solo lo que saca del tab
|
|
1480
|
+
_RE_RULE_DISPLAY = re.compile(r'display\s*:\s*none|visibility\s*:\s*hidden')
|
|
1032
1481
|
|
|
1033
1482
|
def _hidden_class_style(self):
|
|
1034
1483
|
"""¿Algún ancestro abierto del control tiene una clase que el
|
|
1035
1484
|
<style> de la página declara como oculta (clip-path, position
|
|
1036
1485
|
absolute + 1px, display none, visibility hidden)? Las reglas se
|
|
1037
1486
|
cachean: reparsear TODO el css por nodo de texto era cuadrático."""
|
|
1487
|
+
return self._class_hides('hidden')
|
|
1488
|
+
|
|
1489
|
+
def _focus_hidden_class(self):
|
|
1490
|
+
"""Clase que saca el elemento del TAB (display:none/visibility:hidden
|
|
1491
|
+
por <style>) — MÁS ESTRICTA que _hidden_class_style: un
|
|
1492
|
+
.visually-hidden (clip/1px) SIGUE enfocable (el skip link vive ahí)."""
|
|
1493
|
+
return self._class_hides('focus')
|
|
1494
|
+
|
|
1495
|
+
def _class_hides(self, mode):
|
|
1496
|
+
"""¿Una clase abierta (del control o de un ancestro) la declara el
|
|
1497
|
+
<style> como oculta? Los SETS de clases-ocultas se computan UNA VEZ
|
|
1498
|
+
por <style> (no por elemento: reglas×profundidad×elementos era
|
|
1499
|
+
cuadrático — 2.15 s en deep-800×413-reglas, ahora lineal)."""
|
|
1038
1500
|
if self._styles_text is not self._styles_cached_src:
|
|
1039
1501
|
self._styles_cached_src = self._styles_text
|
|
1040
|
-
|
|
1502
|
+
# selectores agrupados (.a, .b {…}): cada clase del grupo cuenta
|
|
1503
|
+
self._style_rules = [
|
|
1504
|
+
(cls.lstrip('. '), body)
|
|
1505
|
+
for sel, body in self._RE_RULE.findall(self._styles_text)
|
|
1506
|
+
for cls in sel.split(',')]
|
|
1507
|
+
self._hidden_cls_set = {_s for _s, _b in self._style_rules
|
|
1508
|
+
if self._RE_HIDDEN_STYLE.search(_b)}
|
|
1509
|
+
self._nohiding_cls_set = {_s for _s, _b in self._style_rules
|
|
1510
|
+
if self._RE_RULE_DISPLAY.search(_b)}
|
|
1511
|
+
_set = self._hidden_cls_set if mode == 'hidden' else self._nohiding_cls_set
|
|
1512
|
+
if not _set:
|
|
1513
|
+
return False
|
|
1041
1514
|
_open_classes = [c.get('attrs', {}).get('class') for c in self._ctrl]
|
|
1042
|
-
|
|
1043
|
-
_open_classes.append(self._el_stack[-1][1].get('class'))
|
|
1515
|
+
_open_classes += (_fr[1].get('class') for _fr in self._el_stack)
|
|
1044
1516
|
for _cls in filter(None, _open_classes):
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
if _nom == _selector and self._RE_HIDDEN_STYLE.search(_body):
|
|
1048
|
-
return True
|
|
1517
|
+
if _set.intersection(_cls.split()):
|
|
1518
|
+
return True
|
|
1049
1519
|
return False
|
|
1050
1520
|
|
|
1051
1521
|
def handle_data(self, data):
|
|
@@ -1058,10 +1528,14 @@ class _Auditor(HTMLParser):
|
|
|
1058
1528
|
# lista por id + join único post-parse: la concatenación por
|
|
1059
1529
|
# nodo era cuadrática en páginas con wrappers id grandes
|
|
1060
1530
|
self._id_text_parts.setdefault(_id, []).append(data)
|
|
1531
|
+
if self._in_template:
|
|
1532
|
+
return # contenido INERTE: ni prosa visible, ni lang, ni nombres
|
|
1061
1533
|
if data.strip() and not in_code and not self._in_title:
|
|
1062
1534
|
self._visible_text.append(data) # prosa visible: ni JS, ni CSS, ni título
|
|
1063
1535
|
if self._in_title:
|
|
1064
1536
|
self._title_buf.append(data)
|
|
1537
|
+
elif self._in_svg_title:
|
|
1538
|
+
self._svg_title_buf.append(data)
|
|
1065
1539
|
elif getattr(self, '_in_script', False):
|
|
1066
1540
|
self.handle_script_wait(data)
|
|
1067
1541
|
elif getattr(self, '_in_style', False):
|
|
@@ -1117,11 +1591,13 @@ def normalize_report(report):
|
|
|
1117
1591
|
if not isinstance(report, dict):
|
|
1118
1592
|
return report
|
|
1119
1593
|
findings = report.get('findings')
|
|
1120
|
-
if not findings:
|
|
1594
|
+
if not isinstance(findings, list):
|
|
1595
|
+
if findings:
|
|
1596
|
+
return dict(report, findings=[]) # dict/str/… hostil: sin hallazgos
|
|
1121
1597
|
return report
|
|
1122
1598
|
out = dict(report)
|
|
1123
1599
|
out['findings'] = [dict(h, signal=normalize_signal(h.get('signal', '')))
|
|
1124
|
-
for h in findings]
|
|
1600
|
+
for h in findings if isinstance(h, dict)]
|
|
1125
1601
|
return out
|
|
1126
1602
|
|
|
1127
1603
|
|
|
@@ -1190,12 +1666,25 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1190
1666
|
p.feed(html_text[:MAX_HTML])
|
|
1191
1667
|
p.close()
|
|
1192
1668
|
except Exception as e: # noqa: BLE001
|
|
1193
|
-
|
|
1669
|
+
# un atributo hostil NO puede tirar la auditoría de 3 MB de página
|
|
1670
|
+
# válida: el mensaje viaja por el catálogo (es/en), como todo lo visible
|
|
1671
|
+
return {'error': _t(lang, 'err_unparseable').format(e=str(e)[:120])}
|
|
1194
1672
|
|
|
1195
|
-
# 1.3.1: grupos de radio (name compartido, ≥2) sin fieldset
|
|
1673
|
+
# 1.3.1: grupos de radio (name compartido, ≥2) sin fieldset NI grupo ARIA
|
|
1674
|
+
# con nombre (role=group/radiogroup + aria-label: la otra técnica de H71)
|
|
1196
1675
|
for nm, count in p._radio_group.items():
|
|
1197
|
-
if count >= 2 and not p._radio_in_fieldset.get(nm, False)
|
|
1676
|
+
if count >= 2 and not p._radio_in_fieldset.get(nm, False) \
|
|
1677
|
+
and not p._radio_in_group.get(nm, False):
|
|
1198
1678
|
p.missing_fieldsets += 1
|
|
1679
|
+
# 3.3.2: required sin indicación — la marca («*», «obligatorio») puede
|
|
1680
|
+
# vivir en el TEXTO del <label for> que el parser vio después del campo
|
|
1681
|
+
for tag, a in p._required_pend:
|
|
1682
|
+
ph = (a.get('placeholder') or '').lower()
|
|
1683
|
+
title_ = (a.get('title') or '').lower()
|
|
1684
|
+
_lbl = p._label_text_for.get(a.get('id') or '', '').lower()
|
|
1685
|
+
if not re.search(r'\*|requerid|obligator|required|necesari|precisa',
|
|
1686
|
+
ph + title_ + _lbl):
|
|
1687
|
+
p.required_no_indication.append(f'{tag}[name={a.get("name","?")}]')
|
|
1199
1688
|
|
|
1200
1689
|
# id→texto resuelto de una vez (partes acumuladas en streaming)
|
|
1201
1690
|
for _id, _parts in p._id_text_parts.items():
|
|
@@ -1203,9 +1692,16 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1203
1692
|
|
|
1204
1693
|
# centinela off-screen: decidir con los scripts YA completos (el <script>
|
|
1205
1694
|
# llega después del link en el documento) — sin id o sin wiring = fallo
|
|
1206
|
-
for _tag, _tid in p._ahf_deferred:
|
|
1695
|
+
for _tag, _tattrs, _tid in p._ahf_deferred:
|
|
1207
1696
|
if not _tid or _tid not in p._scripts_text:
|
|
1208
1697
|
p.aria_hidden_focusable.append(_tag)
|
|
1698
|
+
p.aria_hidden_focusable_elems.append(_tattrs)
|
|
1699
|
+
# candidatos stray-click que nunca cerraron (HTML truncado): sin
|
|
1700
|
+
# interactivo dentro registrado, cuentan igual — el documento está roto
|
|
1701
|
+
for _sp in p._stray_pend:
|
|
1702
|
+
if not _sp[3]:
|
|
1703
|
+
p.stray_clicks.append(_sp[0])
|
|
1704
|
+
p.stray_click_elems.append(_sp[1])
|
|
1209
1705
|
|
|
1210
1706
|
# ── decisiones de nombre POST-parse ─────────────────────────────────────
|
|
1211
1707
|
# Los ids de un aria-labelledby pueden declararse DESPUÉS del elemento que
|
|
@@ -1223,7 +1719,7 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1223
1719
|
# PERO un img presentacional ENFOCABLE (tabindex ≥ 0) sigue necesitando
|
|
1224
1720
|
# nombre: sigue en la navegación por tab (ACT 23a2a8)
|
|
1225
1721
|
_ti = (a.get('tabindex') or '').strip()
|
|
1226
|
-
_enfocable_img = _ti.
|
|
1722
|
+
_enfocable_img = _ti.isdecimal() and int(_ti) >= 0
|
|
1227
1723
|
if hidden or ((a.get('role') or '').strip().lower() in ('presentation', 'none')
|
|
1228
1724
|
and not _enfocable_img):
|
|
1229
1725
|
continue
|
|
@@ -1232,14 +1728,71 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1232
1728
|
if 'alt' in a and (a['alt'] or '') == '':
|
|
1233
1729
|
continue
|
|
1234
1730
|
lb, al, ti = _name_sources(a)
|
|
1235
|
-
|
|
1731
|
+
# <svg role=img> con <title> hijo: el título ES su nombre (accname)
|
|
1732
|
+
# — la vía recomendada por el W3C para gráficos accesibles
|
|
1733
|
+
_svgt = p._svg_titles.get(id(a), '')
|
|
1734
|
+
if not (al or lb or ti or _svgt):
|
|
1236
1735
|
p.imgs_no_alt.append((a.get('src') or a.get('aria-label') or '(role=img)')[:100])
|
|
1736
|
+
p.imgs_no_alt_elems.append(a)
|
|
1737
|
+
|
|
1738
|
+
# 1.1.1: alt PRESENTE pero basura — filenames, palabras genéricas o
|
|
1739
|
+
# marcadores que PASAN el chequeo de presencia (axe image-alt incluido)
|
|
1740
|
+
# y aun así no dicen nada. Filtro, no veredicto: media, con ejemplos y
|
|
1741
|
+
# rutas. alt="" no entra (decorativo legítimo); sin alt lo juzga arriba.
|
|
1742
|
+
_alt_bad = []
|
|
1743
|
+
_alt_seen = {}
|
|
1744
|
+
for a, hidden in p.imgs_all:
|
|
1745
|
+
if hidden or (a.get('role') or '').strip().lower() in ('presentation', 'none'):
|
|
1746
|
+
continue
|
|
1747
|
+
_altv = ' '.join((a.get('alt') or '').split())
|
|
1748
|
+
if not _altv:
|
|
1749
|
+
continue
|
|
1750
|
+
_low = _altv.casefold()
|
|
1751
|
+
_reason = ''
|
|
1752
|
+
if _ALT_EXT_RX.search(_low):
|
|
1753
|
+
_reason = 'filename'
|
|
1754
|
+
elif _ALT_DUMP_RX.match(_low):
|
|
1755
|
+
_reason = 'filename'
|
|
1756
|
+
elif _low in _ALT_GENERIC:
|
|
1757
|
+
_reason = 'generic'
|
|
1758
|
+
elif len(_low.replace('.', '').strip()) <= 2:
|
|
1759
|
+
_reason = 'placeholder'
|
|
1760
|
+
if _reason:
|
|
1761
|
+
_alt_bad.append((_reason, _altv, a))
|
|
1762
|
+
else:
|
|
1763
|
+
_alt_seen.setdefault(_low, []).append(a)
|
|
1764
|
+
# duplicación en masa: el MISMO alt no vacío en ≥4 imágenes casi siempre
|
|
1765
|
+
# es una icon-list que debía ser alt=""
|
|
1766
|
+
for _low, _elems in _alt_seen.items():
|
|
1767
|
+
if len(_elems) >= 4:
|
|
1768
|
+
_alt_bad.append(('repeated', _elems[0].get('alt', _low), _elems[0]))
|
|
1769
|
+
_alt_pair_seen = set()
|
|
1770
|
+
_alt_bad_d = []
|
|
1771
|
+
for _reason, _altv, _a in _alt_bad:
|
|
1772
|
+
_key = (_reason, _altv.casefold())
|
|
1773
|
+
if _key in _alt_pair_seen:
|
|
1774
|
+
continue
|
|
1775
|
+
_alt_pair_seen.add(_key)
|
|
1776
|
+
_alt_bad_d.append((_reason, _altv, _a))
|
|
1777
|
+
p.alt_quality_bad = _alt_bad_d
|
|
1237
1778
|
for a, hidden in p.inputs_image:
|
|
1238
1779
|
if hidden:
|
|
1239
1780
|
continue
|
|
1240
1781
|
lb, al, ti = _name_sources(a)
|
|
1241
1782
|
if not ((a.get('alt') or '').strip() or al or lb or ti):
|
|
1242
1783
|
p.input_img_no_alt += 1
|
|
1784
|
+
for a, fallback, hidden in p.canvases:
|
|
1785
|
+
# canvas: la capa accesible suele inyectarla JS al renderizar el
|
|
1786
|
+
# gráfico — la señal estática es FILTRO (media); el pase rendered
|
|
1787
|
+
# juzga el nombre computado. Conservador: oculto/decorativo no acusa;
|
|
1788
|
+
# con texto de reserva no acusa (fallback content)
|
|
1789
|
+
if hidden or (a.get('role') or '').strip().lower() in ('presentation', 'none'):
|
|
1790
|
+
continue
|
|
1791
|
+
lb, al, ti = _name_sources(a)
|
|
1792
|
+
if al or lb or ti or fallback:
|
|
1793
|
+
continue
|
|
1794
|
+
p.canvas_no_layer.append(a)
|
|
1795
|
+
p.canvas_no_layer_elems.append(a)
|
|
1243
1796
|
for a, hidden in p.iframes_all:
|
|
1244
1797
|
# tabindex=-1 saca el iframe del orden de tab: la regla lo excluye;
|
|
1245
1798
|
# role=none/presentation le quita la semántica de iframe (ACT cae760)
|
|
@@ -1249,6 +1802,7 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1249
1802
|
lb, al, ti = _name_sources(a)
|
|
1250
1803
|
if not ((a.get('title') or '').strip() or al or lb):
|
|
1251
1804
|
p.iframes_no_title.append((a.get('src') or '')[:100])
|
|
1805
|
+
p.iframes_no_title_elems.append(a)
|
|
1252
1806
|
for kind, a, text, img_attrs, hidden in p.controls_raw:
|
|
1253
1807
|
# input submit/reset/button llevan valor por defecto del navegador;
|
|
1254
1808
|
# disabled/hidden quedan fuera. El value de un <button> NO es su
|
|
@@ -1258,13 +1812,18 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1258
1812
|
lb, al, ti = _name_sources(a)
|
|
1259
1813
|
_img_names = []
|
|
1260
1814
|
for ia in img_attrs:
|
|
1815
|
+
# el interior aria-hidden NO es nombre (accname: excluido del
|
|
1816
|
+
# name-from-content) — el icono decorativo junto al texto no miente
|
|
1817
|
+
if (ia.get('aria-hidden') or '').strip().lower() == 'true':
|
|
1818
|
+
_img_names.append('')
|
|
1819
|
+
continue
|
|
1261
1820
|
ilb, ial, iti = _name_sources(ia)
|
|
1262
1821
|
_img_names.append((ia.get('alt') or '').strip() or ial or ilb or iti)
|
|
1263
1822
|
if not (text.strip() or al or lb or ti
|
|
1264
1823
|
or ' '.join(x for x in _img_names if x).strip()
|
|
1265
1824
|
or (a.get('alt') or '').strip()):
|
|
1266
1825
|
p.controls_by_kind.setdefault(kind, []).append(a)
|
|
1267
|
-
for level, a, text, hidden in p.headings_raw:
|
|
1826
|
+
for level, a, text, hidden, _hroute in p.headings_raw:
|
|
1268
1827
|
if hidden:
|
|
1269
1828
|
continue
|
|
1270
1829
|
lb, al, _ti = _name_sources(a)
|
|
@@ -1276,7 +1835,11 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1276
1835
|
if level == 1:
|
|
1277
1836
|
p.h1s += 1
|
|
1278
1837
|
lowered = heading_name.lower().strip()
|
|
1279
|
-
|
|
1838
|
+
# encabezado corto: solo SOSPECHOSO si no es un acrónimo/término
|
|
1839
|
+
# técnico conocido («FAQ», «API», «CSS»…) — len<4 en solitario
|
|
1840
|
+
# no prueba vaguedad
|
|
1841
|
+
_short_ok = heading_name.upper().replace(' ', '') in _SHORT_HEADINGS
|
|
1842
|
+
if (len(heading_name) < 4 and not _short_ok) or len(heading_name) > 120:
|
|
1280
1843
|
p.vague_headings.append(f'h{level} "{heading_name[:40]}"')
|
|
1281
1844
|
elif re.fullmatch(r'(secci[oó]n|section|chapter|cap[ií]tulo|m[aá]s|more|info|informaci[oó]n|information|details|detalle|click|ver|see|leer|read|continue|seguir)[\s\d.]*', lowered):
|
|
1282
1845
|
p.vague_headings.append(f'h{level} "{heading_name[:40]}"')
|
|
@@ -1310,6 +1873,7 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1310
1873
|
or _content_name)
|
|
1311
1874
|
if not (_has_real_name or _placeholder):
|
|
1312
1875
|
p.fields_no_label.append((kind or tag, (a.get('name') or '')[:60], a.get('id')))
|
|
1876
|
+
p.fields_no_label_elems.append(a)
|
|
1313
1877
|
for tag, a, en_label, hidden in p._placeholder_candidates:
|
|
1314
1878
|
# placeholder como ÚNICO nombre: revisión 3.3.2 (el accname del
|
|
1315
1879
|
# navegador lo cuenta, pero como etiqueta es débil — se declara)
|
|
@@ -1319,6 +1883,7 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1319
1883
|
if not (lb or al or ti or en_label
|
|
1320
1884
|
or (a.get('id') and a['id'] in p._labels_for)):
|
|
1321
1885
|
p.placeholder_only.append(f'{tag}[placeholder="{(a.get("placeholder") or "")[:30]}"]')
|
|
1886
|
+
p.placeholder_only_elems.append(a)
|
|
1322
1887
|
|
|
1323
1888
|
findings = []
|
|
1324
1889
|
|
|
@@ -1326,28 +1891,58 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1326
1891
|
h = {'severity': severity, 'criterion': _crit(lang, code), 'signal': key_msg,
|
|
1327
1892
|
'issue': _t(lang, key_msg, n=fmt.get('n')).format(**fmt)}
|
|
1328
1893
|
h['remediation'] = _t(lang, key_msg + '_rem').format(**fmt)
|
|
1894
|
+
paths = fmt.pop('paths', None)
|
|
1895
|
+
if paths:
|
|
1896
|
+
h['paths'] = paths[:5]
|
|
1329
1897
|
findings.append(h)
|
|
1330
1898
|
|
|
1331
1899
|
def add_ej(severity, code, key_msg, examples, **fmt):
|
|
1332
1900
|
add(severity, code, key_msg, **fmt)
|
|
1333
1901
|
findings[-1]['examples'] = examples[:5]
|
|
1334
1902
|
|
|
1903
|
+
if p.alt_quality_bad:
|
|
1904
|
+
_p_q = [p._elem_paths[id(_a)] for _r, _alt, _a in p.alt_quality_bad
|
|
1905
|
+
if id(_a) in p._elem_paths][:5]
|
|
1906
|
+
add_ej('medium', '1.1.1', 'alt_quality',
|
|
1907
|
+
[_alt[:40] for _r, _alt, _a in p.alt_quality_bad],
|
|
1908
|
+
n=len(p.alt_quality_bad), paths=_p_q)
|
|
1335
1909
|
if p.imgs_no_alt:
|
|
1336
|
-
|
|
1910
|
+
_p_img = [p._elem_paths[id(_a)] for _a in p.imgs_no_alt_elems
|
|
1911
|
+
if id(_a) in p._elem_paths][:5]
|
|
1912
|
+
add_ej('high', '1.1.1', 'img_no_alt', p.imgs_no_alt,
|
|
1913
|
+
n=len(p.imgs_no_alt), paths=_p_img)
|
|
1337
1914
|
if p.input_img_no_alt:
|
|
1338
1915
|
add('high', '1.1.1', 'input_img_alt', n=p.input_img_no_alt)
|
|
1916
|
+
if p.canvas_no_layer:
|
|
1917
|
+
_p_canvas = [p._elem_paths[id(_a)] for _a in p.canvas_no_layer_elems
|
|
1918
|
+
if id(_a) in p._elem_paths][:5]
|
|
1919
|
+
add_ej('medium', '1.1.1', 'canvas_no_accessible_layer', p.canvas_no_layer,
|
|
1920
|
+
n=len(p.canvas_no_layer), paths=_p_canvas)
|
|
1339
1921
|
for tag, controls in p.controls_by_kind.items():
|
|
1340
|
-
add('high', '4.1.2', 'ctrl_name', n=len(controls), tag=tag
|
|
1922
|
+
add('high', '4.1.2', 'ctrl_name', n=len(controls), tag=tag,
|
|
1923
|
+
paths=[p._elem_paths[id(_a)] for _a in controls
|
|
1924
|
+
if id(_a) in p._elem_paths][:5])
|
|
1341
1925
|
if p.aria_hidden_focusable:
|
|
1342
1926
|
add('high', '4.1.2', 'aria_hidden_focusable',
|
|
1343
|
-
n=len(p.aria_hidden_focusable), tag=p.aria_hidden_focusable[0]
|
|
1927
|
+
n=len(p.aria_hidden_focusable), tag=p.aria_hidden_focusable[0],
|
|
1928
|
+
paths=[p._elem_paths[id(_a)] for _a in p.aria_hidden_focusable_elems
|
|
1929
|
+
if id(_a) in p._elem_paths][:5])
|
|
1344
1930
|
if p.fields_no_label:
|
|
1345
1931
|
add_ej('high', '3.3.2', 'field_label',
|
|
1346
1932
|
[f'{t} name={n or "(no name)"}' for t, n, _i in p.fields_no_label],
|
|
1347
|
-
n=len(p.fields_no_label)
|
|
1933
|
+
n=len(p.fields_no_label),
|
|
1934
|
+
paths=[p._elem_paths[id(_a)] for _a in p.fields_no_label_elems
|
|
1935
|
+
if id(_a) in p._elem_paths][:5])
|
|
1348
1936
|
if p.stray_clicks:
|
|
1349
1937
|
add('high', '2.1.1', 'click_nonfocusable',
|
|
1350
|
-
n=len(p.stray_clicks), tag=p.stray_clicks[0]
|
|
1938
|
+
n=len(p.stray_clicks), tag=p.stray_clicks[0],
|
|
1939
|
+
paths=[p._elem_paths[id(_a)] for _a in p.stray_click_elems
|
|
1940
|
+
if id(_a) in p._elem_paths][:5])
|
|
1941
|
+
if p.role_no_tabindex:
|
|
1942
|
+
add_ej('low', '2.1.1', 'role_no_tabindex', p.role_no_tabindex,
|
|
1943
|
+
n=len(p.role_no_tabindex), example=', '.join(p.role_no_tabindex[:3]),
|
|
1944
|
+
paths=[p._elem_paths[id(_a)] for _a in p.role_no_tabindex_elems
|
|
1945
|
+
if id(_a) in p._elem_paths][:5])
|
|
1351
1946
|
if p.orphan_labels:
|
|
1352
1947
|
add('low', '3.3.2', 'label_orphan', n=p.orphan_labels)
|
|
1353
1948
|
if p._bad_list:
|
|
@@ -1357,7 +1952,8 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1357
1952
|
# (idioma, título, bypass, encabezados) no aplican (ACT b5c3f8/3e12e1)
|
|
1358
1953
|
pass
|
|
1359
1954
|
elif not p.lang:
|
|
1360
|
-
add('medium', '3.1.1', 'lang_missing'
|
|
1955
|
+
add('medium', '3.1.1', 'lang_missing',
|
|
1956
|
+
paths=[path_segment('html', 1)])
|
|
1361
1957
|
elif p.lang.lower().split('-')[0] not in _LANG_CODES:
|
|
1362
1958
|
add('medium', '3.1.1', 'lang_invalid', lang=p.lang)
|
|
1363
1959
|
elif p.lang_region_invalid:
|
|
@@ -1365,16 +1961,21 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1365
1961
|
# el PRIMER <title> del documento decide (modelo ACT 2779a5)
|
|
1366
1962
|
p.title = p._titles_in_order[0] if p._titles_in_order else ''
|
|
1367
1963
|
t_clean = (p.title or '').strip().lower()
|
|
1368
|
-
if not t_clean:
|
|
1964
|
+
if not t_clean and p.root_tag not in ('svg', 'math'):
|
|
1369
1965
|
add('medium', '2.4.2', 'title_missing')
|
|
1370
1966
|
elif t_clean in ('untitled', 'documento', 'documento sin título', 'sin título',
|
|
1371
1967
|
'home', 'inicio', 'page 1', 'new page', 'página 1',
|
|
1372
1968
|
'untitled document', 'sin nombre', 'document'):
|
|
1373
1969
|
add('low', '2.4.2', 'title_generic', t=t_clean)
|
|
1374
1970
|
if p.iframes_no_title:
|
|
1375
|
-
add_ej('medium', '4.1.2', 'iframe_title', p.iframes_no_title,
|
|
1376
|
-
|
|
1377
|
-
|
|
1971
|
+
add_ej('medium', '4.1.2', 'iframe_title', p.iframes_no_title,
|
|
1972
|
+
n=len(p.iframes_no_title),
|
|
1973
|
+
paths=[p._elem_paths[id(_a)] for _a in p.iframes_no_title_elems
|
|
1974
|
+
if id(_a) in p._elem_paths][:5])
|
|
1975
|
+
if p.videos and p.videos_no_caps_elems:
|
|
1976
|
+
add('medium', '1.2.2', 'video_captions', n=len(p.videos_no_caps_elems),
|
|
1977
|
+
paths=[p._elem_paths[id(_a)] for _a in p.videos_no_caps_elems
|
|
1978
|
+
if id(_a) in p._elem_paths][:5])
|
|
1378
1979
|
if p.viewport:
|
|
1379
1980
|
# valores inválidos también blocksn (ACT b4f0c3): user-scalable ha de
|
|
1380
1981
|
# ser yes/true o numérico ≥ 1; maximum-scale numérico — si no parsea,
|
|
@@ -1387,7 +1988,9 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1387
1988
|
except ValueError:
|
|
1388
1989
|
allows = v in ('yes', 'true')
|
|
1389
1990
|
if not allows:
|
|
1390
|
-
add('high', '1.4.4', 'zoom_no'
|
|
1991
|
+
add('high', '1.4.4', 'zoom_no',
|
|
1992
|
+
paths=([p._elem_paths[id(p._viewport_elem)]]
|
|
1993
|
+
if p._viewport_elem and id(p._viewport_elem) in p._elem_paths else None))
|
|
1391
1994
|
m_ms = re.search(r'maximum-scale\s*=\s*([\w.-]+)', p.viewport, re.I)
|
|
1392
1995
|
if m_ms:
|
|
1393
1996
|
_v_ms = m_ms.group(1)
|
|
@@ -1398,23 +2001,34 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1398
2001
|
blocks = _v_ms.lower() not in ('device-width', 'device-height',
|
|
1399
2002
|
'initial-scale', 'width', 'height')
|
|
1400
2003
|
if blocks:
|
|
1401
|
-
|
|
2004
|
+
# mismo daño que user-scalable=no (bloquea el zoom del usuario):
|
|
2005
|
+
# misma severidad — ACT b4f0c3 no las distingue
|
|
2006
|
+
add('high', '1.4.4', 'zoom_max', v=_v_ms,
|
|
2007
|
+
paths=([p._elem_paths[id(p._viewport_elem)]]
|
|
2008
|
+
if p._viewport_elem and id(p._viewport_elem) in p._elem_paths else None))
|
|
1402
2009
|
# meta refresh (2.2.1/ACT bc659a): gana el PRIMER meta que parsea según
|
|
1403
2010
|
# los pasos del HTML (dígitos + ; o , o fin — un «0: url» con dos puntos
|
|
1404
2011
|
# NO parsea y se salta); 0 segundos = redirección inmediata y > 72000
|
|
1405
2012
|
# (20 h) quedan EXENTOS
|
|
1406
2013
|
_mr = None
|
|
1407
|
-
|
|
2014
|
+
_mr_elem = None
|
|
2015
|
+
for _idx_mr, _content in enumerate(p.meta_refreshes
|
|
2016
|
+
or ([p.meta_refresh] if p.meta_refresh else [])):
|
|
1408
2017
|
_m = re.match(r'\s*(\d+)\s*(?:[;,]|$)', _content or '')
|
|
1409
2018
|
if _m:
|
|
1410
2019
|
_mr = int(_m.group(1))
|
|
2020
|
+
_mr_elem = p._meta_refresh_elems[_idx_mr] if _idx_mr < len(p._meta_refresh_elems) else None
|
|
1411
2021
|
break
|
|
1412
2022
|
if _mr is not None and 0 < _mr <= 72000:
|
|
1413
|
-
add('medium', '2.2.1', 'meta_refresh', v=_mr
|
|
2023
|
+
add('medium', '2.2.1', 'meta_refresh', v=_mr,
|
|
2024
|
+
paths=([p._elem_paths[id(_mr_elem)]]
|
|
2025
|
+
if _mr_elem and id(_mr_elem) in p._elem_paths else None))
|
|
1414
2026
|
if p.positive_tabindices:
|
|
1415
2027
|
add_ej('medium', '2.4.3', 'tabindex_pos',
|
|
1416
2028
|
[f'{t}[tabindex={i}]' for t, i in p.positive_tabindices],
|
|
1417
|
-
n=len(p.positive_tabindices)
|
|
2029
|
+
n=len(p.positive_tabindices),
|
|
2030
|
+
paths=[p._elem_paths[id(_a)] for _a in p.positive_tabindex_elems
|
|
2031
|
+
if id(_a) in p._elem_paths][:5])
|
|
1418
2032
|
# un toggle cuenta como mecanismo de abatido SOLO si la función que
|
|
1419
2033
|
# invoca colapsa de verdad (su cuerpo, en el script de la página, toca
|
|
1420
2034
|
# `display`): mover off-screen o aria-hidden no colapsa el bloque (3e12e1)
|
|
@@ -1439,12 +2053,16 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1439
2053
|
_nav_collapsible = not re.search(r'visib|aria', _nom) \
|
|
1440
2054
|
and bool(re.search(r'hide|hidden|collapse|display', _nom))
|
|
1441
2055
|
if p.root_tag not in ('svg', 'math') and not (p.hay_main or p.hay_skip or _nav_collapsible):
|
|
1442
|
-
|
|
2056
|
+
# revisión (best-practice al nivel de axe «bypass»): 2.4.1 aplica a
|
|
2057
|
+
# bloques REPETIDOS — en estático no se puede saber si se repiten
|
|
2058
|
+
add('low', '2.4.1', 'no_bypass')
|
|
1443
2059
|
|
|
1444
2060
|
levels = [n for n, _ in p.headings]
|
|
1445
2061
|
if levels:
|
|
1446
2062
|
if p.h1s == 0:
|
|
1447
|
-
|
|
2063
|
+
# best-practice (axe page-has-heading-one), no fallo 1.3.1: WCAG
|
|
2064
|
+
# no exige h1 — y en SPAs el h1 suele llegar del render del cliente
|
|
2065
|
+
add('low', '1.3.1', 'no_h1')
|
|
1448
2066
|
elif p.h1s > 1:
|
|
1449
2067
|
add('low', '1.3.1', 'multi_h1', n=p.h1s)
|
|
1450
2068
|
prev = 0
|
|
@@ -1456,16 +2074,22 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1456
2074
|
if jumps:
|
|
1457
2075
|
add('low', '1.3.1', 'heading_skips', skips=', '.join(jumps[:5]))
|
|
1458
2076
|
elif p.root_tag not in ('svg', 'math'):
|
|
1459
|
-
add('
|
|
2077
|
+
add('low', '1.3.1', 'no_headings')
|
|
1460
2078
|
if p.empty_h:
|
|
1461
2079
|
add('low', '1.3.1', 'empty_heading', n=p.empty_h)
|
|
1462
2080
|
if p.tables and p.tables_with_th < p.tables:
|
|
1463
|
-
add('medium', '1.3.1', 'table_no_th', n=p.tables - p.tables_with_th
|
|
2081
|
+
add('medium', '1.3.1', 'table_no_th', n=p.tables - p.tables_with_th,
|
|
2082
|
+
paths=[p._elem_paths[id(_a)] for _a in p.tables_no_th_elems
|
|
2083
|
+
if id(_a) in p._elem_paths][:5])
|
|
1464
2084
|
if p.blank_no_warning:
|
|
1465
|
-
add('low', '3.2.5', 'blank_no_warning', n=p.blank_no_warning
|
|
2085
|
+
add('low', '3.2.5', 'blank_no_warning', n=p.blank_no_warning,
|
|
2086
|
+
paths=[p._elem_paths[id(_a)] for _a in p.blank_no_warning_elems
|
|
2087
|
+
if id(_a) in p._elem_paths][:5])
|
|
1466
2088
|
dups = sum(1 for _c, k in p.ids.items() if k > 1)
|
|
1467
2089
|
if dups:
|
|
1468
|
-
|
|
2090
|
+
add_ej('low', '4.1.2', 'dup_ids',
|
|
2091
|
+
[f'"{_c}" ×{_k}' for _c, _k in list(p.ids.items()) if _k > 1],
|
|
2092
|
+
n=dups)
|
|
1469
2093
|
|
|
1470
2094
|
# --- v3.1: validez ARIA, autocomplete, enlaces, landmarks, accesskey ---
|
|
1471
2095
|
broken_refs = [f'{attr}="#{ref}"' for attr, ref in p.aria_refs if ref not in p.ids]
|
|
@@ -1488,12 +2112,19 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1488
2112
|
n=len(p.roles_without_state), example=', '.join(p.roles_without_state[:4]))
|
|
1489
2113
|
if p.missing_autocomplete:
|
|
1490
2114
|
add_ej('medium', '1.3.5', 'autocomplete', p.missing_autocomplete,
|
|
1491
|
-
n=len(p.missing_autocomplete), example=', '.join(p.missing_autocomplete[:4])
|
|
2115
|
+
n=len(p.missing_autocomplete), example=', '.join(p.missing_autocomplete[:4]),
|
|
2116
|
+
paths=[p._elem_paths[id(_a)] for _a in p.autocomplete_elems
|
|
2117
|
+
if id(_a) in p._elem_paths][:5])
|
|
1492
2118
|
if p.autocomplete_invalid:
|
|
1493
2119
|
add_ej('medium', '1.3.5', 'autocomplete_invalid', p.autocomplete_invalid,
|
|
1494
2120
|
n=len(p.autocomplete_invalid), example=', '.join(p.autocomplete_invalid[:4]))
|
|
2121
|
+
if p.autocomplete_mismatch:
|
|
2122
|
+
add_ej('medium', '1.3.5', 'autocomplete_mismatch', p.autocomplete_mismatch,
|
|
2123
|
+
n=len(p.autocomplete_mismatch), example=', '.join(p.autocomplete_mismatch[:4]))
|
|
1495
2124
|
if p.media_autoplay:
|
|
1496
|
-
add('medium', '1.4.2', 'video_autoplay', n=p.media_autoplay
|
|
2125
|
+
add('medium', '1.4.2', 'video_autoplay', n=p.media_autoplay,
|
|
2126
|
+
paths=[p._elem_paths[id(_a)] for _a in p.media_autoplay_elems
|
|
2127
|
+
if id(_a) in p._elem_paths][:5])
|
|
1497
2128
|
if p.label_no_name:
|
|
1498
2129
|
_ln = p.label_no_name[0]
|
|
1499
2130
|
add_ej('medium', '2.5.3', 'label_in_name',
|
|
@@ -1508,7 +2139,9 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1508
2139
|
# forms deep-dive
|
|
1509
2140
|
if p.placeholder_only:
|
|
1510
2141
|
add_ej('high', '3.3.2', 'placeholder_only', p.placeholder_only,
|
|
1511
|
-
n=len(p.placeholder_only), example=', '.join(p.placeholder_only[:3])
|
|
2142
|
+
n=len(p.placeholder_only), example=', '.join(p.placeholder_only[:3]),
|
|
2143
|
+
paths=[p._elem_paths[id(_a)] for _a in p.placeholder_only_elems
|
|
2144
|
+
if id(_a) in p._elem_paths][:5])
|
|
1512
2145
|
if p.required_no_indication:
|
|
1513
2146
|
add_ej('low', '3.3.2', 'required_no_indication', p.required_no_indication,
|
|
1514
2147
|
n=len(p.required_no_indication), example=', '.join(p.required_no_indication[:3]))
|
|
@@ -1528,10 +2161,13 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1528
2161
|
if p.drag_handlers:
|
|
1529
2162
|
add_ej('low', '2.5.7', 'drag_no_alt', p.drag_handlers,
|
|
1530
2163
|
n=len(p.drag_handlers), example=', '.join(p.drag_handlers[:3]))
|
|
1531
|
-
# 4.1.3:
|
|
1532
|
-
|
|
2164
|
+
# 4.1.3: señal de REVISIÓN y solo con evidencia fuerte de interactividad
|
|
2165
|
+
# propia (handlers de arrastre/clicks huérfanos/atajos) — un <script>
|
|
2166
|
+
# cualquiera (analytics, JSON-LD) o un campo sin label NO crean mensajes
|
|
2167
|
+
# de estado: 4.1.3 solo aplica cuando EXISTEN mensajes que anunciar
|
|
2168
|
+
dynamic = bool(p.stray_clicks or p.char_shortcuts or p.drag_handlers)
|
|
1533
2169
|
if dynamic and p.status_regions == 0:
|
|
1534
|
-
add('
|
|
2170
|
+
add('low', '4.1.3', 'no_status_regions')
|
|
1535
2171
|
if p.images_of_text:
|
|
1536
2172
|
add_ej('low', '1.4.5', 'images_of_text', p.images_of_text,
|
|
1537
2173
|
n=len(p.images_of_text), ej2='')
|
|
@@ -1545,14 +2181,21 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1545
2181
|
if p.gestures:
|
|
1546
2182
|
add_ej('low', '2.5.1', 'gesture_no_click', p.gestures,
|
|
1547
2183
|
n=len(p.gestures), example=', '.join(p.gestures[:3]))
|
|
2184
|
+
if p.focus_blur:
|
|
2185
|
+
add_ej('high', '2.1.1', 'onfocus_blur', p.focus_blur,
|
|
2186
|
+
n=len(p.focus_blur),
|
|
2187
|
+
paths=[p._elem_paths[id(_a)] for _a in p.focus_blur_elems
|
|
2188
|
+
if id(_a) in p._elem_paths][:5])
|
|
1548
2189
|
if p.motions:
|
|
1549
2190
|
add_ej('low', '2.5.4', 'motion_actuation', p.motions,
|
|
1550
2191
|
n=len(p.motions), example=', '.join(p.motions[:3]))
|
|
1551
2192
|
if p.orientation_locks:
|
|
1552
2193
|
add_ej('low', '1.3.4', 'orientation_lock', p.orientation_locks,
|
|
1553
2194
|
n=len(p.orientation_locks), example=', '.join(p.orientation_locks[:2]))
|
|
1554
|
-
if p.videos and p.
|
|
1555
|
-
add('low', '1.2.3', 'audio_desc_missing', n=p.
|
|
2195
|
+
if p.videos and p.videos_no_desc_elems:
|
|
2196
|
+
add('low', '1.2.3', 'audio_desc_missing', n=len(p.videos_no_desc_elems),
|
|
2197
|
+
paths=[p._elem_paths[id(_a)] for _a in p.videos_no_desc_elems
|
|
2198
|
+
if id(_a) in p._elem_paths][:5])
|
|
1556
2199
|
if p.sensory:
|
|
1557
2200
|
add('low', '1.3.3', 'sensory_text', example='; '.join(p.sensory[:2])[:70])
|
|
1558
2201
|
lm_dups = [f'{lm} ×{t[1]}' for lm, t in p.landmarks.items()
|
|
@@ -1579,9 +2222,11 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1579
2222
|
reading = _reading_level(' '.join(p._visible_text),
|
|
1580
2223
|
page_lang if page_lang in ('es', 'en') else lang)
|
|
1581
2224
|
|
|
2225
|
+
import hashlib as _hl
|
|
1582
2226
|
res = {
|
|
1583
2227
|
'mode': 'static',
|
|
1584
2228
|
'url': url,
|
|
2229
|
+
'source_sha256': _hl.sha256(html_text.encode('utf-8', 'replace')).hexdigest(),
|
|
1585
2230
|
'reading_level': reading,
|
|
1586
2231
|
'score': compute_score(findings),
|
|
1587
2232
|
'score_note': _t(lang, 'score_note'),
|
|
@@ -1605,6 +2250,13 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1605
2250
|
_cl = _enstd.clause_for(h['criterion'].split(' ')[0], _tgt)
|
|
1606
2251
|
if _cl:
|
|
1607
2252
|
h['clause'] = _cl
|
|
2253
|
+
elif standard == 'rgaa':
|
|
2254
|
+
from . import a11yrgaa as _rg
|
|
2255
|
+
res['standard'] = _rg.standard_block(lang)
|
|
2256
|
+
for h in findings:
|
|
2257
|
+
_rgaa = _rg.rgaa_for_sc(h['criterion'].split(' ')[0])
|
|
2258
|
+
if _rgaa:
|
|
2259
|
+
h['rgaa'] = _rgaa
|
|
1608
2260
|
# overlays detectados: dato del informe (diligencia de compra), nunca un
|
|
1609
2261
|
# hallazgo — no hay criterio WCAG que anclar y el score no se toca
|
|
1610
2262
|
overlays, _seen = [], set()
|
|
@@ -1620,18 +2272,61 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1620
2272
|
return res
|
|
1621
2273
|
|
|
1622
2274
|
|
|
2275
|
+
class _FetchError(ValueError):
|
|
2276
|
+
"""Error de descarga CON CLAVE de catálogo (es/en): el mensaje visible
|
|
2277
|
+
viaja por locales, no hardcodeado — invariante bilingüe del repo."""
|
|
2278
|
+
def __init__(self, key, **fmt):
|
|
2279
|
+
super().__init__(key)
|
|
2280
|
+
self.key, self.fmt = key, fmt
|
|
2281
|
+
|
|
2282
|
+
|
|
1623
2283
|
# ── redirect policy hook ───────────────────────────────────────────────────
|
|
1624
2284
|
# urlopen follows 3xx (up to 10 hops) to ANY host without asking: every hop
|
|
1625
|
-
# is a NEW destination nobody validated.
|
|
1626
|
-
#
|
|
1627
|
-
#
|
|
1628
|
-
|
|
2285
|
+
# is a NEW destination nobody validated. DEFAULT: every redirect hop is
|
|
2286
|
+
# resolved and rejected if it lands on a private network (loopback, RFC1918,
|
|
2287
|
+
# link-local incl. cloud metadata 169.254.169.254…) — the classic SSRF pivot
|
|
2288
|
+
# (public URL → internal hop). The URL the USER typed is explicit intent and
|
|
2289
|
+
# is never blocked; only implicit hops are. Callers can inject their own
|
|
2290
|
+
# validator (callable(url) -> bool) or pass True to allow everything.
|
|
2291
|
+
validate_redirect = None # inyectable: callable(url) -> bool
|
|
2292
|
+
|
|
2293
|
+
|
|
2294
|
+
def _redirect_to_private(url):
|
|
2295
|
+
"""True si la URL resuelve a una IP no pública (fail-closed)."""
|
|
2296
|
+
import ipaddress
|
|
2297
|
+
import socket
|
|
2298
|
+
from urllib.parse import urlsplit
|
|
2299
|
+
try:
|
|
2300
|
+
host = urlsplit(url).hostname or ''
|
|
2301
|
+
infos = socket.getaddrinfo(host, None)
|
|
2302
|
+
except (OSError, ValueError):
|
|
2303
|
+
return True # no resuelve: cerrar, no seguir
|
|
2304
|
+
for _fam, _ty, _pr, _ad, sa in infos:
|
|
2305
|
+
try:
|
|
2306
|
+
ip = ipaddress.ip_address(sa[0])
|
|
2307
|
+
except ValueError:
|
|
2308
|
+
return True
|
|
2309
|
+
if ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved \
|
|
2310
|
+
or ip.is_multicast or ip.is_unspecified:
|
|
2311
|
+
return True
|
|
2312
|
+
return False
|
|
1629
2313
|
|
|
1630
2314
|
|
|
1631
2315
|
class _CheckedRedirect(urllib.request.HTTPRedirectHandler):
|
|
1632
2316
|
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
1633
|
-
|
|
1634
|
-
|
|
2317
|
+
_guard = validate_redirect
|
|
2318
|
+
if _guard is None:
|
|
2319
|
+
# saltos que MANTIENEN el host que el usuario escribió conservan
|
|
2320
|
+
# su intent explícito (dev en localhost: /app→/app/, http→https):
|
|
2321
|
+
# solo los saltos a OTRO destino pasan el filtro de red privada
|
|
2322
|
+
from urllib.parse import urlsplit as _us
|
|
2323
|
+
try:
|
|
2324
|
+
_same = (_us(newurl).netloc.lower() == (req.host or '').lower())
|
|
2325
|
+
except Exception: # noqa: BLE001
|
|
2326
|
+
_same = False
|
|
2327
|
+
_guard = (lambda _u: _same or not _redirect_to_private(_u))
|
|
2328
|
+
if _guard is not True and not _guard(newurl):
|
|
2329
|
+
raise _FetchError('err_redirect_blocked', url=newurl[:96])
|
|
1635
2330
|
return super().redirect_request(req, fp, code, msg, headers, newurl)
|
|
1636
2331
|
|
|
1637
2332
|
|
|
@@ -1669,7 +2364,7 @@ def _fetch(url, timeout=30, truncate_at=None, accept_ct=()):
|
|
|
1669
2364
|
break
|
|
1670
2365
|
data += chunk
|
|
1671
2366
|
if len(data) > ceiling and truncate_at is None:
|
|
1672
|
-
raise
|
|
2367
|
+
raise _FetchError('err_too_big', mb=MAX_HTML // 1000000)
|
|
1673
2368
|
if (r.headers.get('Content-Encoding') or '').lower() == 'gzip' or data[:2] == b'\x1f\x8b':
|
|
1674
2369
|
import zlib
|
|
1675
2370
|
d = zlib.decompressobj(16 + zlib.MAX_WBITS)
|
|
@@ -1680,7 +2375,7 @@ def _fetch(url, timeout=30, truncate_at=None, accept_ct=()):
|
|
|
1680
2375
|
base = ctype.split(';')[0].strip()
|
|
1681
2376
|
extra_ok = any(base == p or base.startswith(p + '/') for p in accept_ct)
|
|
1682
2377
|
if ctype and not extra_ok and 'html' not in ctype and 'xml' not in ctype and base:
|
|
1683
|
-
raise
|
|
2378
|
+
raise _FetchError('err_not_html', ct=base)
|
|
1684
2379
|
# the HEADER charset wins over body sniffing (HTTP has priority over
|
|
1685
2380
|
# <meta>): a server declaring iso-8859-1 without a meta tag otherwise
|
|
1686
2381
|
# produces U+FFFD inside findings
|
|
@@ -1709,6 +2404,8 @@ def audit_url(url, timeout=30, lang='en', standard=None, target=None):
|
|
|
1709
2404
|
return {'error': _T_SCHEME.get(lang, _T_SCHEME['es'])}
|
|
1710
2405
|
try:
|
|
1711
2406
|
html_text = _fetch(url, timeout=timeout)
|
|
2407
|
+
except _FetchError as e:
|
|
2408
|
+
return {'error': _t(lang, e.key).format(**e.fmt)}
|
|
1712
2409
|
except ValueError as e:
|
|
1713
2410
|
return {'error': str(e)}
|
|
1714
2411
|
except Exception as e: # noqa: BLE001
|
|
@@ -1795,7 +2492,10 @@ def evaluate_site(parsers, lang='en'):
|
|
|
1795
2492
|
'issue': _t(lang, 'help_inconsistent').format(
|
|
1796
2493
|
example=f'{len(set(signatures_help))} variantes en {len(signatures_help)} páginas'),
|
|
1797
2494
|
'remediation': _t(lang, 'help_inconsistent_rem')})
|
|
1798
|
-
|
|
2495
|
+
# 2.4.5 exige múltiples formas de encontrar PÁGINAS: con una muestra de
|
|
2496
|
+
# una sola página no hay proceso multi-página que reclamarlo (FP en
|
|
2497
|
+
# sitios de una página — la excepción del propio criterio)
|
|
2498
|
+
if len(parsers) >= 2 and not any(p.has_search or p.has_sitemap for p in parsers):
|
|
1799
2499
|
out.append({'severity': 'medium', 'criterion': _crit(lang, '2.4.5'),
|
|
1800
2500
|
'signal': 'no_multiple_ways',
|
|
1801
2501
|
'issue': _t(lang, 'no_multiple_ways'),
|
|
@@ -1812,12 +2512,25 @@ def audit_site(url, max_pages=5, timeout=30, lang='en', from_sitemap=True,
|
|
|
1812
2512
|
deadline = (time.monotonic() + budget) if budget else None
|
|
1813
2513
|
try:
|
|
1814
2514
|
html_text = _fetch(url, timeout=timeout)
|
|
2515
|
+
except _FetchError as e:
|
|
2516
|
+
return {'error': _t(lang, e.key).format(**e.fmt)}
|
|
1815
2517
|
except ValueError as e:
|
|
1816
2518
|
return {'error': str(e)}
|
|
1817
2519
|
except Exception as e: # noqa: BLE001
|
|
1818
2520
|
return {'error': _t(lang, 'fetch_error').format(e=e)}
|
|
1819
|
-
|
|
1820
|
-
|
|
2521
|
+
# el parser jamás tira el crawl entero: una página hostil → informe de
|
|
2522
|
+
# error de ESA página y se sigue con la cola
|
|
2523
|
+
def _parse_page(html_txt, page_url):
|
|
2524
|
+
pg = _Auditor()
|
|
2525
|
+
try:
|
|
2526
|
+
pg.feed(html_txt[:MAX_HTML])
|
|
2527
|
+
pg.close()
|
|
2528
|
+
except Exception as e: # noqa: BLE001
|
|
2529
|
+
return pg, {'url': page_url, 'error': _t(lang, 'err_unparseable').format(e=str(e)[:120])}
|
|
2530
|
+
return pg, None
|
|
2531
|
+
p0, p0_err = _parse_page(html_text, url)
|
|
2532
|
+
if p0_err:
|
|
2533
|
+
return p0_err
|
|
1821
2534
|
reports = [audit_html(html_text, url, lang=lang)]
|
|
1822
2535
|
parsers = [p0]
|
|
1823
2536
|
seen = {url.split('#')[0].rstrip('/')}
|
|
@@ -1835,9 +2548,10 @@ def audit_site(url, max_pages=5, timeout=30, lang='en', from_sitemap=True,
|
|
|
1835
2548
|
html_pg = _fetch(next, timeout=timeout)
|
|
1836
2549
|
except Exception: # noqa: BLE001
|
|
1837
2550
|
continue
|
|
2551
|
+
pg, pg_err = _parse_page(html_pg, next)
|
|
2552
|
+
if pg_err is not None:
|
|
2553
|
+
continue # página rota: no cuenta, el crawl sigue
|
|
1838
2554
|
reports.append(audit_html(html_pg, next, lang=lang))
|
|
1839
|
-
pg = _Auditor()
|
|
1840
|
-
pg.feed(html_pg[:MAX_HTML]); pg.close()
|
|
1841
2555
|
parsers.append(pg)
|
|
1842
2556
|
if len(reports) < max_pages and not from_sitemap:
|
|
1843
2557
|
for new in _internal_links(html_pg, next, url):
|
|
@@ -1848,6 +2562,9 @@ def audit_site(url, max_pages=5, timeout=30, lang='en', from_sitemap=True,
|
|
|
1848
2562
|
for inf in reports[:1]:
|
|
1849
2563
|
inf.setdefault('findings', []).append(h)
|
|
1850
2564
|
inf['score'] = compute_score(inf['findings'])
|
|
2565
|
+
# el summary también: un score recalculado con summary viejo miente
|
|
2566
|
+
inf['summary'] = {s: sum(1 for f2 in inf['findings'] if f2['severity'] == s)
|
|
2567
|
+
for s in ('high', 'medium', 'low')}
|
|
1851
2568
|
scores = [pg['score'] for pg in reports if 'score' in pg]
|
|
1852
2569
|
findings_by_signal = {}
|
|
1853
2570
|
for pg in reports:
|
|
@@ -1939,18 +2656,29 @@ def audit_changed(base='HEAD', lang='en', cwd='.'):
|
|
|
1939
2656
|
|
|
1940
2657
|
|
|
1941
2658
|
def _apply_standard(res, standard, target, lang):
|
|
1942
|
-
""" Enriquecimiento post-hoc EN 301 549 (site crawl, --changed):
|
|
1943
|
-
bloque standard y cláusula por hallazgo. standard=None →
|
|
1944
|
-
|
|
2659
|
+
""" Enriquecimiento post-hoc EN 301 549 / RGAA (site crawl, --changed):
|
|
2660
|
+
añade bloque standard y cláusula/issue RGAA por hallazgo. standard=None →
|
|
2661
|
+
res intacto. Antes solo EN: con --standard rgaa y --pages>1 (o --changed)
|
|
2662
|
+
el estándar se descartaba EN SILENCIO."""
|
|
2663
|
+
if not isinstance(res, dict) or 'error' in res:
|
|
1945
2664
|
return res
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
|
|
1950
|
-
for
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
2665
|
+
if standard == 'en301549':
|
|
2666
|
+
from . import a11yen301549 as _enstd
|
|
2667
|
+
_tgt = target or _enstd.target_for_mode(res.get('mode', 'static'))
|
|
2668
|
+
res['standard'] = _enstd.standard_block(_tgt, lang)
|
|
2669
|
+
for _pg in res.get('reports', [res]):
|
|
2670
|
+
for h in _pg.get('findings', []):
|
|
2671
|
+
_cl = _enstd.clause_for(h.get('criterion'), _tgt)
|
|
2672
|
+
if _cl:
|
|
2673
|
+
h['clause'] = _cl
|
|
2674
|
+
elif standard == 'rgaa':
|
|
2675
|
+
from . import a11yrgaa as _rg
|
|
2676
|
+
res['standard'] = _rg.standard_block(lang)
|
|
2677
|
+
for _pg in res.get('reports', [res]):
|
|
2678
|
+
for h in _pg.get('findings', []):
|
|
2679
|
+
_rgaa = _rg.rgaa_for_sc((h.get('criterion') or '').split(' ')[0])
|
|
2680
|
+
if _rgaa:
|
|
2681
|
+
h['rgaa'] = _rgaa
|
|
1954
2682
|
return res
|
|
1955
2683
|
|
|
1956
2684
|
|
|
@@ -1968,7 +2696,7 @@ def main(argv):
|
|
|
1968
2696
|
help='crawl ligero mismo dominio (1 = solo la página)')
|
|
1969
2697
|
ap.add_argument('--no-sitemap', action='store_true',
|
|
1970
2698
|
help='descubre por enlaces, sin leer el sitemap')
|
|
1971
|
-
ap.add_argument('--standard', choices=['en301549'], default=None,
|
|
2699
|
+
ap.add_argument('--standard', choices=['en301549', 'rgaa'], default=None,
|
|
1972
2700
|
help='añade a cada hallazgo su cláusula EN 301 549 V4.1.1 '
|
|
1973
2701
|
'(9.x web por defecto)')
|
|
1974
2702
|
ap.add_argument('--target', choices=['web', 'documents', 'software'],
|
|
@@ -1991,7 +2719,7 @@ def main(argv):
|
|
|
1991
2719
|
standard=a.standard,
|
|
1992
2720
|
target=a.target))
|
|
1993
2721
|
except Exception as e: # noqa: BLE001
|
|
1994
|
-
print(json.dumps({'error':
|
|
2722
|
+
print(json.dumps({'error': _t(a.lang, 'fetch_error').format(e=e)}))
|
|
1995
2723
|
return 1
|
|
1996
2724
|
else:
|
|
1997
2725
|
with open(a.file, encoding='utf-8', errors='replace') as f:
|