@kinti/a11y-toolkit 5.25.2 → 5.27.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 +31 -4
- package/a11y_toolkit/a11yact.py +9 -1
- package/a11y_toolkit/a11yannotate.py +185 -0
- package/a11y_toolkit/a11yaudit.py +903 -186
- 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 +110 -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 +451 -96
- package/a11y_toolkit/a11yen301549.py +147 -0
- package/a11y_toolkit/a11yengines.py +157 -0
- package/a11y_toolkit/a11yevidence.py +182 -36
- package/a11y_toolkit/a11yfix.py +131 -52
- package/a11y_toolkit/a11yinit.py +30 -5
- 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 +28 -7
- 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 +70 -21
- package/a11y_toolkit/a11yscope.py +296 -0
- 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 +54 -11
- 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 +222 -24
- package/a11y_toolkit/locales/es.json +223 -25
- package/a11y_toolkit/rgaa.json +2661 -0
- package/a11y_toolkit/server.py +247 -59
- 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,9 +51,24 @@ _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
74
|
_LANG_CODES = set('''af am ar az be bg bn bs ca cs cy da de el en es et eu fa fi fr ga gl
|
|
@@ -86,8 +115,9 @@ _SENSORIAL = re.compile(
|
|
|
86
115
|
|
|
87
116
|
# Campos que con frecuencia recogen datos personales (1.3.5)
|
|
88
117
|
_PERSONAL_DATA = re.compile(
|
|
89
|
-
r'(^|[\W_])(name|nombre|email|correo|
|
|
90
|
-
r'
|
|
118
|
+
r'(^|[\W_])(full[_-]?name|first[_-]?name|last[_-]?name|name|nombre|email|correo|'
|
|
119
|
+
r'phone|telefono|tel|address|direccion|postal|zip|city|ciudad|country|pais|'
|
|
120
|
+
r'organi[sz]ation|company|empresa|street|user(name)?|usuario)([\W_]|$)', re.I)
|
|
91
121
|
|
|
92
122
|
# Tokens autofill válidos (HTML §7.5 — subconjunto práctico del estándar;
|
|
93
123
|
# one-time-code incluido: los campos OTP lo exigen y los lectores lo usan)
|
|
@@ -118,10 +148,6 @@ _MOD_ADDRESS = {'shipping', 'billing'}
|
|
|
118
148
|
# el modificador de contacto solo vale pegado a estos campos (ABNF 73f2c2)
|
|
119
149
|
_FIELDS_AFTER_CONTACT = {'email', 'impp', 'tel', 'tel-country-code', 'tel-national',
|
|
120
150
|
'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
151
|
_FIELDS_AFTER_ADDRMOD = {'street-address', 'address-line1', 'address-line2', 'address-line3',
|
|
126
152
|
'address-level1', 'address-level2', 'address-level3', 'address-level4',
|
|
127
153
|
'country', 'country-name', 'postal-code'}
|
|
@@ -278,6 +304,16 @@ _OVERLAY_WIDGETS = (
|
|
|
278
304
|
("FACIL'ITI", ('facil-iti.com', 'facil-iti.org')),
|
|
279
305
|
)
|
|
280
306
|
|
|
307
|
+
# texto de un skip link (es/en/pt/fr — el vocabulario del patrón 3e12e1)
|
|
308
|
+
_SKIP_TEXT = re.compile(
|
|
309
|
+
r'skip|jump to|saltar|ir al contenido|ir para o conte[uú]do|passer au contenu', re.I)
|
|
310
|
+
|
|
311
|
+
# encabezados cortos legítimos (acrónimos y términos técnicos): «FAQ», «API»…
|
|
312
|
+
_SHORT_HEADINGS = {'FAQ', 'API', 'CSS', 'APP', 'MAP', 'EN', 'DE', 'ES', 'PT', 'FR',
|
|
313
|
+
'IT', 'UI', 'UX', 'ID', 'TV', 'HR', 'PR', 'AI', 'PC', 'OK', '3D',
|
|
314
|
+
'IOS', 'OS', 'GB', 'MB', 'KB', 'PDF', 'RSS', 'URL', 'WWW', 'XML',
|
|
315
|
+
'HTTP', 'FAQS', 'BLOG', 'HOME', 'INICIO', 'NOTAS', 'AGENDA'}
|
|
316
|
+
|
|
281
317
|
|
|
282
318
|
def _t(lang, key, n=None):
|
|
283
319
|
"""Message by key; `{"one","other"}` entries resolve via the locale's
|
|
@@ -291,11 +327,31 @@ def _crit(lang, code):
|
|
|
291
327
|
|
|
292
328
|
|
|
293
329
|
class _Auditor(HTMLParser):
|
|
330
|
+
# rasgos contados para el scope (evidencia positiva de aplicabilidad)
|
|
331
|
+
FEATURE_TAGS = ('video', 'audio', 'track', 'embed', 'object', 'iframe',
|
|
332
|
+
'form', 'input', 'select', 'textarea', 'table')
|
|
333
|
+
|
|
294
334
|
def __init__(self):
|
|
335
|
+
# ── anotación por elemento (kernel a11yannotate) ──────────────────
|
|
336
|
+
# identidad determinista: cada elemento del parseo recibe su ruta
|
|
337
|
+
# CSS (tag:nth-of-type(n) desde la raíz). id(attrs) es estable dentro
|
|
338
|
+
# del parseo (cada attrs es un dict nuevo) → los recolectores pueden
|
|
339
|
+
# resolver la ruta de LO QUE COGIERON sin cambiar sus tuplas.
|
|
340
|
+
self._path_stack = [] # [(tag, path, {tag: nth})] del elemento abierto
|
|
341
|
+
self._elem_paths = {} # id(attrs) → ruta del elemento
|
|
295
342
|
super().__init__(convert_charrefs=True)
|
|
296
343
|
self.imgs_no_alt = []
|
|
344
|
+
self.alt_quality_bad = [] # (razón, alt, attrs) — emitida en findings
|
|
345
|
+
# elementos (attrs) detrás de cada ejemplo, para el kernel de anotación
|
|
346
|
+
self.imgs_no_alt_elems = []
|
|
347
|
+
self.canvas_no_layer = [] # canvas sin capa accesible (1.1.1)
|
|
348
|
+
self.canvas_no_layer_elems = []
|
|
349
|
+
self.iframes_no_title_elems = []
|
|
350
|
+
self.placeholder_only_elems = []
|
|
351
|
+
self.autocomplete_elems = []
|
|
297
352
|
self.controls_by_kind = {} # tag → lista de atributos de controles sin nombre
|
|
298
353
|
self.fields_no_label = []
|
|
354
|
+
self.fields_no_label_elems = []
|
|
299
355
|
self.iframes_no_title = []
|
|
300
356
|
self.lang = None
|
|
301
357
|
self.lang_region_invalid = None
|
|
@@ -308,9 +364,12 @@ class _Auditor(HTMLParser):
|
|
|
308
364
|
self._heading_level = None
|
|
309
365
|
self._heading_text = []
|
|
310
366
|
self._visible_text = []
|
|
311
|
-
self._heading_text = []
|
|
312
367
|
self.positive_tabindices = []
|
|
368
|
+
self.positive_tabindex_elems = []
|
|
369
|
+
self.blank_no_warning_elems = [] # anchors _blank sin aviso (paths)
|
|
313
370
|
self.viewport = None
|
|
371
|
+
self._viewport_elem = None # attrs del meta viewport (path)
|
|
372
|
+
self._meta_refresh_elems = [] # attrs de cada meta refresh (path)
|
|
314
373
|
self.elements = 0
|
|
315
374
|
# Pila de controles interactivos (a/button/summary) para recoger su
|
|
316
375
|
# texto interno, que es la fuente más habitual de nombre accesible.
|
|
@@ -321,16 +380,27 @@ class _Auditor(HTMLParser):
|
|
|
321
380
|
self.orphan_labels = 0
|
|
322
381
|
# Nuevas señales
|
|
323
382
|
self.aria_hidden_focusable = [] # tag de interactivos con aria-hidden
|
|
383
|
+
self.aria_hidden_focusable_elems = []
|
|
324
384
|
self.stray_clicks = [] # tags no interactivos con onclick
|
|
385
|
+
self.stray_click_elems = [] # attrs de cada uno (paths del kernel)
|
|
386
|
+
self._stray_pend = [] # (tag, attrs, frame) hasta cerrar: se
|
|
387
|
+
# confirma salvo que el subárbol contenga un control nativo (delegación)
|
|
388
|
+
self.role_no_tabindex = [] # [role=button/link] sin tabindex (2.1.1)
|
|
389
|
+
self.role_no_tabindex_elems = []
|
|
325
390
|
self.meta_refresh = None
|
|
326
391
|
self.meta_refreshes = [] # todos los meta refresh: gana el 1º parseable (spec HTML)
|
|
327
392
|
self.saw_html = False
|
|
328
393
|
self.saw_body = False
|
|
329
394
|
self.root_tag = None
|
|
330
|
-
self._in_head = False
|
|
331
395
|
self._in_template = 0
|
|
332
396
|
self._title_buf = []
|
|
333
397
|
self._titles_in_order = []
|
|
398
|
+
# svg: <title> DENTRO de <svg> es el nombre del svg (accname), no el
|
|
399
|
+
# título del documento — se rastrea por profundidad de svg abiertos
|
|
400
|
+
self._svg_depth = 0
|
|
401
|
+
self._in_svg_title = False
|
|
402
|
+
self._svg_title_buf = []
|
|
403
|
+
self._svg_titles = {} # id(attrs del svg) → texto de su <title>
|
|
334
404
|
# accname (ola de precisión ACT): visibilidad HEREDADA (aria-hidden con
|
|
335
405
|
# re-activación por false, attr hidden, display:none/visibility:hidden)
|
|
336
406
|
# y registro id→texto para resolver aria-labelledby a un salto — los ids
|
|
@@ -348,6 +418,8 @@ class _Auditor(HTMLParser):
|
|
|
348
418
|
self._styles_text = '' # contenido de <style>: clases ocultas y fuentes-icono
|
|
349
419
|
self._styles_cached_src = None
|
|
350
420
|
self._style_rules = []
|
|
421
|
+
self._hidden_cls_set = set() # clases que el <style> oculta (caché)
|
|
422
|
+
self._nohiding_cls_set = set() # subconjunto display:none/visibility (foco)
|
|
351
423
|
self._icon_links = []
|
|
352
424
|
self._ahf_deferred = [] # (tag, id) off-screen: decidir post-parse con los scripts completos
|
|
353
425
|
self._el_stack = [] # (tag, attrs, [texto directo]) — texto propio del elemento
|
|
@@ -367,10 +439,16 @@ class _Auditor(HTMLParser):
|
|
|
367
439
|
self.videos = 0
|
|
368
440
|
self.videos_with_captions = 0
|
|
369
441
|
self._in_video = False
|
|
442
|
+
self._video_caps_stack = [] # [attrs, captions, descriptions] por <video>
|
|
443
|
+
self.videos_no_caps_elems = []
|
|
444
|
+
self.videos_no_desc_elems = []
|
|
445
|
+
self.media_autoplay_elems = []
|
|
370
446
|
self.tables = 0
|
|
371
447
|
self.tables_with_th = 0
|
|
372
448
|
self._in_table = False
|
|
373
449
|
self._th_in_table = False
|
|
450
|
+
self._table_stack = [] # (th_había, attrs) por <table> abierta
|
|
451
|
+
self.tables_no_th_elems = []
|
|
374
452
|
self.blank_no_warning = 0
|
|
375
453
|
self.blank_total = 0
|
|
376
454
|
self.hay_main = False
|
|
@@ -379,6 +457,8 @@ class _Auditor(HTMLParser):
|
|
|
379
457
|
self.empty_h = 0
|
|
380
458
|
self.ids = {}
|
|
381
459
|
self.input_img_no_alt = 0
|
|
460
|
+
self.canvases = [] # [(attrs, texto_interno, hidden)] — capa accesible del canvas
|
|
461
|
+
self.canvas_hidden = {} # id(attrs) → hidden, del starttag al endtag
|
|
382
462
|
# v3.1: validez ARIA, autocomplete, enlaces, landmarks, accesskey, autoplay
|
|
383
463
|
self.aria_refs = [] # (attr, id) referenciados por aria-labelledby/describedby
|
|
384
464
|
self.aria_values = [] # valores aria-* inválidos
|
|
@@ -391,6 +471,8 @@ class _Auditor(HTMLParser):
|
|
|
391
471
|
self.links = {} # nombre normalizado → set de hrefs
|
|
392
472
|
self.generics = 0
|
|
393
473
|
self.labels_for_dups = {} # id → n labels (los >1, varios)
|
|
474
|
+
self._label_for_stack = [] # valor `for` de cada <label> abierto (None = envolvente)
|
|
475
|
+
self._label_text_for = {} # id del for → texto del label (decisión post-parse)
|
|
394
476
|
self.media_autoplay = 0
|
|
395
477
|
self._list_depth = 0
|
|
396
478
|
self._li_depth = 0
|
|
@@ -398,8 +480,12 @@ class _Auditor(HTMLParser):
|
|
|
398
480
|
self.label_no_name = [] # (texto visible, aria-label) 2.5.3
|
|
399
481
|
self.lang_parts_invalid = [] # lang inválidos en elementos no-html
|
|
400
482
|
self.down_events = [] # onmousedown/ontouchstart/onpointerdown
|
|
401
|
-
self.captchas = [] # detección 3.3.8
|
|
483
|
+
self.captchas = [] # detección 3.3.8 — SOLO en contexto de autenticación
|
|
484
|
+
self._form_captchas = [] # candidatos del <form> abierto (3.3.8 aplica a auth)
|
|
485
|
+
self._form_auth = False # form actual: acción de login o input password
|
|
486
|
+
self._required_pend = [] # (tag, attrs) required: decide post-parse con el label
|
|
402
487
|
self.mobiles = [] # marquee/blink/inline infinite animation (2.2.2)
|
|
488
|
+
self._landmark_ids = set() # ids de landmarks: objetivos válidos de skip link
|
|
403
489
|
self.nav_hrefs = set() # hrefs inside <nav> (site-level 3.2.3 signature)
|
|
404
490
|
self.help_hrefs = set() # help/contact links (site-level 3.2.6 signature)
|
|
405
491
|
self.images_of_text = []
|
|
@@ -413,20 +499,22 @@ class _Auditor(HTMLParser):
|
|
|
413
499
|
self.missing_fieldsets = 0 # 1.3.1: radio/check groups sin fieldset
|
|
414
500
|
self._radio_group = {}
|
|
415
501
|
self._radio_in_fieldset = {} # name → count (para detectar grupos)
|
|
502
|
+
self._radio_in_group = {} # name → dentro de role=group con nombre
|
|
416
503
|
self.vague_labels = [] # 2.4.6: label quality
|
|
417
504
|
self.financial_no_confirm = 0 # 3.3.4: financial form no confirm
|
|
418
505
|
self._financial_form = False
|
|
419
|
-
self._confirm_form = False #
|
|
506
|
+
self._confirm_form = False # 3.3.4: pista de confirmación en form financiero
|
|
420
507
|
self._in_nav = 0
|
|
421
508
|
self._in_fieldset = False
|
|
509
|
+
self._group_role_depth = 0 # <div role=group/radiogroup> abierto (con nombre)
|
|
422
510
|
self.has_search = False
|
|
423
511
|
self.has_sitemap = False
|
|
424
512
|
self.gestures = [] # touchmove/drag handlers (2.5.1)
|
|
513
|
+
self.features = {} # tag → n (rasgos de aplicabilidad)
|
|
425
514
|
self.motions = [] # deviceorientation/devicemotion (2.5.4)
|
|
426
515
|
self.orientation_locks = [] # screen.orientation.lock / orientation MQ (1.3.4)
|
|
427
516
|
self.videos_descriptions = 0 # videos WITH descriptions track
|
|
428
517
|
self.sensory = [] # sensory-only instruction patterns (1.3.3)
|
|
429
|
-
self._skip_labels_pend = [] # labels declarados antes que su campo
|
|
430
518
|
|
|
431
519
|
def _close_control(self, tag):
|
|
432
520
|
if not self._ctrl:
|
|
@@ -459,7 +547,10 @@ class _Auditor(HTMLParser):
|
|
|
459
547
|
self._styles_text, re.I)) or bool(re.search(
|
|
460
548
|
r'fonts\.googleapis\.com/icon|/material-icons|font-?awesome|/icomoon',
|
|
461
549
|
' '.join(getattr(self, '_icon_links', [])), re.I))
|
|
462
|
-
|
|
550
|
+
# página con fuente-icono: el «texto» del control puede ser un glifo
|
|
551
|
+
# no verbal (ligadura Material «shopping_cart») — exento en CUALQUIER
|
|
552
|
+
# control (enlaces-icono incluidos), no solo <button>
|
|
553
|
+
if not _icon_font and _vis and _al:
|
|
463
554
|
def _lin_words(txt):
|
|
464
555
|
txt = re.sub(r'\([^)]*\)', ' ', txt)
|
|
465
556
|
# la puntuación se ELIMINA sin partir palabras («11×3=33» →
|
|
@@ -479,14 +570,23 @@ class _Auditor(HTMLParser):
|
|
|
479
570
|
for i in range(len(_ap2) - len(_vp) + 1))
|
|
480
571
|
if _mismatch:
|
|
481
572
|
self.label_no_name.append((_vis[:40], _al[:60]))
|
|
482
|
-
if tag == 'a':
|
|
573
|
+
if tag == 'a' and not c.get('hidden'):
|
|
483
574
|
if (a.get('target') or '').lower() == '_blank':
|
|
484
575
|
self.blank_total += 1
|
|
576
|
+
_img_alts = ' '.join((ia.get('alt') or '')
|
|
577
|
+
for ia in c.get('img_attrs', []))
|
|
485
578
|
if not _BLANK_HINT.search(text) and not _BLANK_HINT.search(a.get('aria-label') or '') \
|
|
486
|
-
and not _BLANK_HINT.search(a.get('title') or '')
|
|
579
|
+
and not _BLANK_HINT.search(a.get('title') or '') \
|
|
580
|
+
and not _BLANK_HINT.search(_img_alts):
|
|
487
581
|
self.blank_no_warning += 1
|
|
488
|
-
|
|
489
|
-
|
|
582
|
+
self.blank_no_warning_elems.append(a)
|
|
583
|
+
elif (a.get('href') or '').strip().startswith('#') \
|
|
584
|
+
and len((a.get('href') or '').strip()) > 1 and text:
|
|
585
|
+
# skip link REAL: ancla interna cuyo objetivo es un landmark o
|
|
586
|
+
# cuyo texto lo dice — un TOC/footnote no abate bloques (3e12e1)
|
|
587
|
+
if (a.get('href') or '').strip()[1:] in self._landmark_ids \
|
|
588
|
+
or _SKIP_TEXT.search(text):
|
|
589
|
+
self.hay_skip = True
|
|
490
590
|
name = (text or a.get('aria-label') or a.get('title') or '').strip()
|
|
491
591
|
href = (a.get('href') or '').strip()
|
|
492
592
|
if name and href:
|
|
@@ -500,10 +600,66 @@ class _Auditor(HTMLParser):
|
|
|
500
600
|
if self._labels_stack:
|
|
501
601
|
self._labels_stack[-1] = True
|
|
502
602
|
|
|
603
|
+
def _wrap_labels(self, a):
|
|
604
|
+
"""¿Un <label> ABIERTO etiqueta ESTE campo? El label envolvente solo
|
|
605
|
+
asocia cuando NO tiene `for` (o su `for` apunta al propio campo):
|
|
606
|
+
<label for=email>…<input id=pw>> NO etiqueta a pw (el for manda)."""
|
|
607
|
+
if not self._label_for_stack:
|
|
608
|
+
return False
|
|
609
|
+
_fid = a.get('id')
|
|
610
|
+
return any(_f is None or (_fid and _f == _fid)
|
|
611
|
+
for _f in self._label_for_stack)
|
|
612
|
+
|
|
503
613
|
def handle_starttag(self, tag, attrs):
|
|
504
|
-
|
|
614
|
+
# atributos DUPLICADOS: gana el PRIMERO (spec HTML: los repetidos se
|
|
615
|
+
# descartan) — dict(attrs) dejaría ganar al último y <img alt="x" alt="">
|
|
616
|
+
# pasaría por decorativa
|
|
617
|
+
a = {}
|
|
618
|
+
for _k, _v in attrs:
|
|
619
|
+
if _k not in a:
|
|
620
|
+
a[_k] = _v
|
|
505
621
|
self.elements += 1
|
|
506
|
-
|
|
622
|
+
# delegación de eventos: un control interactivo REAL dentro de un
|
|
623
|
+
# candidato a «click no enfocable» lo exime (wrapper de analytics
|
|
624
|
+
# sobre un <button> real). «Interactivo» exige OPERABILIDAD: un <a>
|
|
625
|
+
# SIN href no recibe foco, un input hidden/disabled tampoco, y el
|
|
626
|
+
# contenido de <template> es inerte — ninguno salva al wrapper
|
|
627
|
+
if self._stray_pend and not self._in_template:
|
|
628
|
+
_ti_mark = (a.get('tabindex') or '').strip()
|
|
629
|
+
_rolemark = (a.get('role') or '').strip().lower() in ('button', 'link')
|
|
630
|
+
_nav = (tag == 'a' and bool((a.get('href') or '').strip()))
|
|
631
|
+
_native = (tag in ('button', 'summary', 'select', 'textarea')
|
|
632
|
+
or _nav
|
|
633
|
+
or (tag == 'input' and (a.get('type') or 'text').lower() != 'hidden'
|
|
634
|
+
and 'disabled' not in a))
|
|
635
|
+
if _native or _rolemark \
|
|
636
|
+
or (_ti_mark.isdecimal() and int(_ti_mark) >= 0):
|
|
637
|
+
for _sp in self._stray_pend:
|
|
638
|
+
_sp[3] = True
|
|
639
|
+
# ruta determinista del elemento (kernel de anotación): nth-of-type
|
|
640
|
+
# SIEMPRE (los id duplicados no pueden romper la ruta) y los void no
|
|
641
|
+
# abren pila (no tienen handle_endtag)
|
|
642
|
+
if self._path_stack:
|
|
643
|
+
_parent = self._path_stack[-1]
|
|
644
|
+
_parent[2][tag] = _parent[2].get(tag, 0) + 1
|
|
645
|
+
_seg = path_segment(tag, _parent[2][tag])
|
|
646
|
+
_path = _parent[1] + '>' + _seg
|
|
647
|
+
else:
|
|
648
|
+
_path = path_segment(tag, 1)
|
|
649
|
+
self._elem_paths[id(a)] = _path
|
|
650
|
+
if tag not in VOID_TAGS:
|
|
651
|
+
self._path_stack.append((tag, _path, {}))
|
|
652
|
+
# rasgos estructurales para el scope de aplicabilidad (a11yscope):
|
|
653
|
+
# evidencia POSITIVA — cero <video> habilita proponer 1.2.x como no
|
|
654
|
+
# aplicable; la ausencia de señal jamás cuenta como ausencia de
|
|
655
|
+
# contenido. input type=hidden no es un campo visible.
|
|
656
|
+
if tag in self.FEATURE_TAGS:
|
|
657
|
+
if tag == 'input' and (a.get('type') or '').strip().lower() == 'hidden':
|
|
658
|
+
pass
|
|
659
|
+
else:
|
|
660
|
+
self.features[tag] = self.features.get(tag, 0) + 1
|
|
661
|
+
if a.get('id') and not self._in_template:
|
|
662
|
+
# ids dentro de <template> no existen: ni dup_ids ni refs rotas
|
|
507
663
|
self.ids[a['id']] = self.ids.get(a['id'], 0) + 1
|
|
508
664
|
if self.root_tag is None:
|
|
509
665
|
self.root_tag = tag
|
|
@@ -520,6 +676,11 @@ class _Auditor(HTMLParser):
|
|
|
520
676
|
_hidden_aria = False
|
|
521
677
|
_hidden = _inh or 'hidden' in a or 'display:none' in _style \
|
|
522
678
|
or 'visibility:hidden' in _style or _hidden_aria
|
|
679
|
+
# <template> es contenido INERTE (spec HTML): no renderiza, no recibe
|
|
680
|
+
# foco, sus ids no existen — se audita como oculto y los colectores
|
|
681
|
+
# que no consultan _hidden llevan guardia explícita
|
|
682
|
+
if self._in_template:
|
|
683
|
+
_hidden = True
|
|
523
684
|
if tag not in _VOID:
|
|
524
685
|
self._depth += 1
|
|
525
686
|
self._hidden_stack.append((_hidden, _hidden_aria))
|
|
@@ -536,10 +697,34 @@ class _Auditor(HTMLParser):
|
|
|
536
697
|
self._nav_ids.add(a['id'])
|
|
537
698
|
if a.get('onclick'):
|
|
538
699
|
self._toggle_onclicks.append(a['onclick'])
|
|
539
|
-
if tag == '
|
|
540
|
-
self._in_head = True
|
|
541
|
-
elif tag == 'template':
|
|
700
|
+
if tag == 'template':
|
|
542
701
|
self._in_template += 1
|
|
702
|
+
elif tag == 'svg':
|
|
703
|
+
self._svg_depth += 1
|
|
704
|
+
# svg hijo de un control: su aria-label/aria-labelledby/<title>
|
|
705
|
+
# aporta al nombre del control (accname 2F.ii: name-from-content
|
|
706
|
+
# incluye el nombre accesible de cada descendiente — Chrome y
|
|
707
|
+
# Firefox nombran «Submit Search» al botón-buscador del W3C WAI
|
|
708
|
+
# así). aria-hidden en el svg lo excluye (icono decorativo).
|
|
709
|
+
if self._ctrl and (a.get('aria-label') or a.get('aria-labelledby')) \
|
|
710
|
+
and (a.get('aria-hidden') or '').strip().lower() != 'true':
|
|
711
|
+
self._ctrl[-1]['img_attrs'].append(a)
|
|
712
|
+
# y los ROLES sobre el propio svg se procesan igual que en un tag
|
|
713
|
+
# cualquiera: svg[role=img] sin nombre ES un 1.1.1 (ACT 23a2a8),
|
|
714
|
+
# svg[role=button] exige nombre+tabindex — el elif de arriba se
|
|
715
|
+
# comía el svg antes de llegar a la maquinaria de roles
|
|
716
|
+
_svg_role = (a.get('role') or '').strip().lower()
|
|
717
|
+
if not self._in_template:
|
|
718
|
+
if _svg_role == 'img':
|
|
719
|
+
self.imgs_all.append((a, _hidden))
|
|
720
|
+
elif _svg_role in ('button', 'link'):
|
|
721
|
+
self._ctrl.append({'tag': tag, 'attrs': a, 'text': [],
|
|
722
|
+
'text_visible': [], 'inner_img': False,
|
|
723
|
+
'img_attrs': [], 'hidden': _hidden,
|
|
724
|
+
'depth': self._depth, 'kind': 'role:' + _svg_role})
|
|
725
|
+
if 'tabindex' not in a and not _hidden:
|
|
726
|
+
self.role_no_tabindex.append(f'{tag}[role={_svg_role}]')
|
|
727
|
+
self.role_no_tabindex_elems.append(a)
|
|
543
728
|
elif tag == 'html':
|
|
544
729
|
self.saw_html = True
|
|
545
730
|
self.lang = (a.get('lang') or '').strip()
|
|
@@ -549,11 +734,15 @@ class _Auditor(HTMLParser):
|
|
|
549
734
|
self.lang_region_invalid = self.lang
|
|
550
735
|
elif tag == 'body':
|
|
551
736
|
self.saw_body = True
|
|
552
|
-
elif tag == 'title' and not self._in_template:
|
|
737
|
+
elif tag == 'title' and not self._in_template and self._svg_depth == 0:
|
|
553
738
|
# TODOS los <title> se acumulan en orden de documento: decide el
|
|
554
739
|
# PRIMERO (modelo de ACT 2779a5: head vacío + body con texto falla;
|
|
555
|
-
# title solo en body pasa; los de <template> son inertes)
|
|
740
|
+
# title solo en body pasa; los de <template> son inertes). El
|
|
741
|
+
# <title> de un <svg> es el NOMBRE del svg (accname): otra vía.
|
|
556
742
|
self._in_title = True
|
|
743
|
+
elif tag == 'title' and self._svg_depth > 0 and not self._in_template:
|
|
744
|
+
self._in_svg_title = True
|
|
745
|
+
self._svg_title_buf = []
|
|
557
746
|
elif tag == 'script':
|
|
558
747
|
self._in_script = True
|
|
559
748
|
if a.get('src'):
|
|
@@ -563,12 +752,18 @@ class _Auditor(HTMLParser):
|
|
|
563
752
|
elif tag == 'link':
|
|
564
753
|
if (a.get('rel') or '').lower() == 'stylesheet' and a.get('href'):
|
|
565
754
|
self._icon_links.append(a['href'])
|
|
755
|
+
elif tag == 'canvas':
|
|
756
|
+
# attrs ahora; el texto de reserva se recoge en el endtag (pop)
|
|
757
|
+
self.canvas_hidden[id(a)] = _hidden
|
|
566
758
|
elif tag == 'meta':
|
|
567
|
-
if a.get('name'
|
|
568
|
-
|
|
759
|
+
if (a.get('name') or '').lower() == 'viewport':
|
|
760
|
+
# el ÚLTIMO content decide (así se consume): su elem también
|
|
761
|
+
self.viewport = (a.get('content') or '')
|
|
762
|
+
self._viewport_elem = a
|
|
569
763
|
elif (a.get('http-equiv') or '').lower() == 'refresh':
|
|
570
|
-
self.meta_refresh = a.get('content'
|
|
571
|
-
self.meta_refreshes.append(a.get('content'
|
|
764
|
+
self.meta_refresh = (a.get('content') or '')
|
|
765
|
+
self.meta_refreshes.append((a.get('content') or ''))
|
|
766
|
+
self._meta_refresh_elems.append(a)
|
|
572
767
|
elif tag == 'img':
|
|
573
768
|
# la decisión de nombre es POST-parse (nombre accesible = alt u
|
|
574
769
|
# otras fuentes; presentación/none y hiddens quedan fuera)
|
|
@@ -578,6 +773,10 @@ class _Auditor(HTMLParser):
|
|
|
578
773
|
# la imagen interna aporta SU nombre completo al control
|
|
579
774
|
# (alt, aria-label, title, labelledby — resuelto post-parse)
|
|
580
775
|
self._ctrl[-1]['img_attrs'].append(a)
|
|
776
|
+
if a.get('id') and alt and not self._in_template:
|
|
777
|
+
# el alt de una img ES su nombre accesible: un aria-labelledby
|
|
778
|
+
# que apunte a esta img resuelve al alt (accname), no a ''
|
|
779
|
+
self._id_text_parts.setdefault(a['id'], []).append(alt)
|
|
581
780
|
if alt and not _hidden:
|
|
582
781
|
# el alt SE LEE: cuenta como texto bajo el lang de su
|
|
583
782
|
# contexto (de46e4 — una img con alt es contenido textual)
|
|
@@ -585,13 +784,16 @@ class _Auditor(HTMLParser):
|
|
|
585
784
|
if self._heading_level is not None and not _hidden \
|
|
586
785
|
and (a.get('role') or '').strip().lower() not in ('presentation', 'none'):
|
|
587
786
|
# nombre de la imagen (alt u otras fuentes) alimenta al
|
|
588
|
-
# encabezado — salvo presentación/none u oculta (ffd0e9)
|
|
787
|
+
# encabezado — salvo presentación/none u oculta (ffd0e9).
|
|
788
|
+
# NOTA: una img DENTRO de un heading no es evidencia de
|
|
789
|
+
# «imagen de texto» (1.4.5 exime logotipos; un gráfico de
|
|
790
|
+
# datos no es texto) — solo el alt kilométrico sigue siendo
|
|
791
|
+
# señal de revisión
|
|
589
792
|
_nom_img = alt or (a.get('aria-label') or '').strip() \
|
|
590
793
|
or (a.get('title') or '').strip()
|
|
591
794
|
if _nom_img:
|
|
592
795
|
self._heading_text.append(_nom_img)
|
|
593
|
-
|
|
594
|
-
elif len(alt) > 120:
|
|
796
|
+
if len(alt) > 120:
|
|
595
797
|
self.images_of_text.append(f'alt de {len(alt)} caracteres')
|
|
596
798
|
elif tag == 'iframe':
|
|
597
799
|
self.iframes_all.append((a, _hidden))
|
|
@@ -616,6 +818,8 @@ class _Auditor(HTMLParser):
|
|
|
616
818
|
elif tag == 'input':
|
|
617
819
|
self._field_note()
|
|
618
820
|
kind = (a.get('type') or 'text').lower()
|
|
821
|
+
if kind == 'password':
|
|
822
|
+
self._form_auth = True # 3.3.8: form con password = autenticación
|
|
619
823
|
if kind == 'image':
|
|
620
824
|
self.inputs_image.append((a, _hidden))
|
|
621
825
|
elif kind in ('submit', 'button', 'reset'):
|
|
@@ -625,18 +829,19 @@ class _Auditor(HTMLParser):
|
|
|
625
829
|
if kind == 'search' or re.search(r'search|busqueda|b[uú]squeda', (a.get('name') or '') + (a.get('id') or ''), re.I):
|
|
626
830
|
self.has_search = True
|
|
627
831
|
if kind in _FIELDS:
|
|
628
|
-
self.fields_raw.append((tag, kind, a, self.
|
|
832
|
+
self.fields_raw.append((tag, kind, a, self._wrap_labels(a), _hidden))
|
|
629
833
|
if 'autocomplete' not in a and kind != 'search' and (
|
|
630
834
|
kind in ('email', 'tel')
|
|
631
835
|
or _PERSONAL_DATA.search((a.get('name') or '') + ' ' + (a.get('id') or ''))):
|
|
632
836
|
self.missing_autocomplete.append(f'input type={kind} name={a.get("name") or "?"}'[:44])
|
|
837
|
+
self.autocomplete_elems.append(a)
|
|
633
838
|
if tag == 'input' and 'autocomplete' in a and 'disabled' not in a \
|
|
634
839
|
and (a.get('aria-disabled') or '').strip().lower() != 'true' and not _hidden:
|
|
635
840
|
# ABNF exacta de la regla ACT 73f2c2 (HTML autofill): [section-*]?
|
|
636
841
|
# [shipping|billing]? [home|work|mobile|fax|pager — solo si el
|
|
637
842
|
# siguiente es email/impp/tel/tel-*]? campo [webauthn]? — los
|
|
638
843
|
# campos disabled u hiddens quedan fuera (aplicabilidad)
|
|
639
|
-
_toks = (a['autocomplete'] or '').split()
|
|
844
|
+
_toks = [t.lower() for t in (a['autocomplete'] or '').split()]
|
|
640
845
|
_mal = None
|
|
641
846
|
if not (_toks == ['on'] or _toks == ['off']):
|
|
642
847
|
_i = 0
|
|
@@ -662,11 +867,12 @@ class _Auditor(HTMLParser):
|
|
|
662
867
|
f'{_mal} (input name={a.get("name") or "?"})'[:60])
|
|
663
868
|
elif tag in ('select', 'textarea'):
|
|
664
869
|
self._field_note()
|
|
665
|
-
self.fields_raw.append((tag, tag, a, self.
|
|
870
|
+
self.fields_raw.append((tag, tag, a, self._wrap_labels(a), _hidden))
|
|
666
871
|
elif tag == 'label':
|
|
667
872
|
self._label_depth += 1
|
|
668
873
|
self._label_text_current = []
|
|
669
874
|
self._labels_stack.append(False)
|
|
875
|
+
self._label_for_stack.append(a.get('for') or None)
|
|
670
876
|
if a.get('for'):
|
|
671
877
|
self._labels_for[a['for']] = self._labels_for.get(a['for'], 0) + 1
|
|
672
878
|
if self._labels_for[a['for']] > 1:
|
|
@@ -677,32 +883,77 @@ class _Auditor(HTMLParser):
|
|
|
677
883
|
elif tag == 'blink':
|
|
678
884
|
self.mobiles.append('<blink>')
|
|
679
885
|
elif tag == 'track':
|
|
680
|
-
kind
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
886
|
+
# sin kind (o kind vacío/None), el valor por defecto del spec HTML
|
|
887
|
+
# es «subtitles» — cuenta como captions (no exigir el atributo).
|
|
888
|
+
# SOLO dentro de un <video>: un track huérfano (o en <template>)
|
|
889
|
+
# jamás acredita captions de un vídeo que no es suyo
|
|
890
|
+
kind = (a.get('kind') or 'subtitles').lower()
|
|
891
|
+
if self._video_caps_stack and not self._in_template:
|
|
892
|
+
if kind == 'descriptions':
|
|
893
|
+
self._video_caps_stack[-1][2] = True
|
|
894
|
+
elif kind in ('captions', 'subtitles'):
|
|
895
|
+
self._video_caps_stack[-1][1] = True
|
|
685
896
|
elif tag in ('video', 'audio'):
|
|
686
|
-
if tag == 'video':
|
|
897
|
+
if tag == 'video' and 'muted' not in a:
|
|
898
|
+
# muted = el hero de fondo sin pista audible: 1.2.2/1.2.3
|
|
899
|
+
# aplican a vídeo CON audio — no se exige track a lo inaudible
|
|
687
900
|
self.videos += 1
|
|
688
901
|
self._in_video = True
|
|
689
|
-
|
|
902
|
+
self._video_caps_stack.append([a, False, False])
|
|
903
|
+
# 1.4.2 aplica a audio QUE SUENA sin control: muted = nada audible;
|
|
904
|
+
# controls = el usuario puede pararlo — ambos pasan (el hero-video
|
|
905
|
+
# muted de toda landing no es un fallo de Audio Control)
|
|
906
|
+
if 'autoplay' in a and 'muted' not in a and 'controls' not in a \
|
|
907
|
+
and not self._in_template:
|
|
690
908
|
self.media_autoplay += 1
|
|
909
|
+
self.media_autoplay_elems.append(a)
|
|
691
910
|
elif tag in ('ul', 'ol'):
|
|
692
911
|
self._list_depth += 1
|
|
693
912
|
elif tag == 'li':
|
|
694
913
|
self._li_depth += 1
|
|
695
914
|
elif tag == 'table':
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
915
|
+
# role=presentation/none la declara de MAQUETACIÓN: no se exige th
|
|
916
|
+
# (el mail HTML y las grids legacy viven aquí) — y el contenido de
|
|
917
|
+
# <template> es inerte
|
|
918
|
+
if (a.get('role') or '').strip().lower() in ('presentation', 'none') \
|
|
919
|
+
or self._in_template:
|
|
920
|
+
pass
|
|
921
|
+
else:
|
|
922
|
+
self.tables += 1
|
|
923
|
+
self._in_table = True
|
|
924
|
+
# sospecha de maquetación (attrs presentacionales de la era
|
|
925
|
+
# <table width=… cellpadding=0 border=0>): sin th NI marcadores
|
|
926
|
+
# de datos no se exige th (FP clásico años-90). OJO border:
|
|
927
|
+
# el spec dice que border≠0 declara tabla de DATOS — solo el
|
|
928
|
+
# «0» (o sin valor, que es 0) es maquetación
|
|
929
|
+
_bv = (a.get('border') or '0').strip()
|
|
930
|
+
_border_data = _bv.isdecimal() and int(_bv) > 0
|
|
931
|
+
_suspect = (bool({'cellpadding', 'cellspacing', 'width'} & set(a))
|
|
932
|
+
or ('border' in a and not _border_data)) and not _border_data
|
|
933
|
+
_data = 'summary' in a or _border_data
|
|
934
|
+
# pila por tabla anidada, CON IDENTIDAD: una </table> de una
|
|
935
|
+
# tabla presentation/none (no apilada) jamás popea la entrada
|
|
936
|
+
# de la tabla externa que la envuelve
|
|
937
|
+
self._table_stack.append([self._th_in_table, a, _suspect, _data])
|
|
938
|
+
self._th_in_table = False
|
|
699
939
|
elif tag == 'th':
|
|
700
940
|
self._th_in_table = True
|
|
941
|
+
elif tag == 'caption' and self._table_stack:
|
|
942
|
+
self._table_stack[-1][3] = True # marcador de tabla de DATOS
|
|
943
|
+
elif tag == 'td' and self._table_stack and ('scope' in a or 'headers' in a):
|
|
944
|
+
self._table_stack[-1][3] = True # asociaciones explícitas = datos
|
|
701
945
|
elif tag == 'main' or (a.get('role') or '').lower() == 'main':
|
|
702
946
|
self.hay_main = True
|
|
947
|
+
if a.get('id'):
|
|
948
|
+
self._landmark_ids.add(a['id'])
|
|
703
949
|
elif tag not in _CONTROLS + ('input', 'select', 'textarea', 'label', 'option',
|
|
704
950
|
'video', 'audio', 'details', 'summary'):
|
|
705
|
-
_role_v = a.get('role'
|
|
951
|
+
_role_v = (a.get('role') or '').strip().lower()
|
|
952
|
+
if _role_v in ('group', 'radiogroup') and not self._in_template:
|
|
953
|
+
# grupo con nombre accesible = alternativa legítima al fieldset
|
|
954
|
+
# (técnica ARIA de H71): se computa al abrir, se cierra en endtag
|
|
955
|
+
if a.get('aria-label') or a.get('aria-labelledby'):
|
|
956
|
+
self._group_role_depth += 1
|
|
706
957
|
if _role_v in _ROLE_FIELDS and _role_v not in ('none', 'presentation'):
|
|
707
958
|
if a.get('id'):
|
|
708
959
|
self._role_field_ids.add(a['id'])
|
|
@@ -719,16 +970,35 @@ class _Auditor(HTMLParser):
|
|
|
719
970
|
'inner_img': False,
|
|
720
971
|
'img_attrs': [], 'hidden': _hidden, 'depth': self._depth,
|
|
721
972
|
'kind': 'role:' + _role_v})
|
|
973
|
+
# 2.1.1: un rol interactivo en tag NO enfocable de nacimiento
|
|
974
|
+
# exige tabindex — sin él el control es inalcanzable por
|
|
975
|
+
# teclado (el JS podría añadirlo en runtime: señal de revisión,
|
|
976
|
+
# el pase rendered confirma). Los <template> son inertes.
|
|
977
|
+
if 'tabindex' not in a and not _hidden:
|
|
978
|
+
self.role_no_tabindex.append(f'{tag}[role={_role_v}]')
|
|
979
|
+
self.role_no_tabindex_elems.append(a)
|
|
722
980
|
elif _role_v == 'img' and tag != 'img':
|
|
723
981
|
# div[role=img] con imagen de fondo: también necesita nombre (23a2a8)
|
|
724
982
|
self.imgs_all.append((a, _hidden))
|
|
725
|
-
if a.get('onclick') and not
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
983
|
+
if a.get('onclick') and _role_v not in ('button', 'link') \
|
|
984
|
+
and 'tabindex' not in a and not self._in_template:
|
|
985
|
+
# candidato a «click no enfocable»: se CONFIRMA al cerrar salvo
|
|
986
|
+
# que el subárbol contenga un control nativo (delegación de
|
|
987
|
+
# eventos / wrappers de analytics sobre un <button> real)
|
|
988
|
+
if tag in _VOID:
|
|
989
|
+
self.stray_clicks.append(tag)
|
|
990
|
+
self.stray_click_elems.append(a)
|
|
991
|
+
else:
|
|
992
|
+
self._stray_pend.append([tag, a, self._depth, False])
|
|
993
|
+
# v3.9: 2.5.2 sospecha de activación en down-event — PERO solo si el
|
|
994
|
+
# elemento no completa en up (onclick/onpointerup/onmouseup presentes):
|
|
995
|
+
# un mousedown de arrastre/selección con click normal NO es down-event
|
|
996
|
+
if not self._in_template:
|
|
997
|
+
for _de in ('onmousedown', 'ontouchstart', 'onpointerdown'):
|
|
998
|
+
if a.get(_de):
|
|
999
|
+
if not (a.get('onclick') or a.get('onpointerup') or a.get('onmouseup')):
|
|
1000
|
+
self.down_events.append(f'{tag}[{_de}]')
|
|
1001
|
+
break
|
|
732
1002
|
# v3.12: 2.2.2 inline looping animation
|
|
733
1003
|
style = a.get('style') or ''
|
|
734
1004
|
if 'animation' in style and 'infinite' in style:
|
|
@@ -741,25 +1011,28 @@ class _Auditor(HTMLParser):
|
|
|
741
1011
|
if tag == 'form':
|
|
742
1012
|
self._financial_form = False
|
|
743
1013
|
self._confirm_form = False
|
|
744
|
-
|
|
1014
|
+
self._form_captchas = []
|
|
1015
|
+
action = (a.get('action') or '').lower() + (a.get('id') or '').lower()
|
|
745
1016
|
if re.search(r'pay|purchase|checkout|buy|order|contract|legal|billing',
|
|
746
1017
|
action, re.I):
|
|
747
1018
|
self._financial_form = True
|
|
1019
|
+
if re.search(r'login|log-in|signin|sign-in|auth|session|sso|register|'
|
|
1020
|
+
r'registro|acces|password', action, re.I):
|
|
1021
|
+
self._form_auth = True
|
|
748
1022
|
if tag in ('input', 'textarea') and a.get('placeholder') \
|
|
749
1023
|
and not (a.get('aria-label') or a.get('aria-labelledby')):
|
|
750
1024
|
# candidato a placeholder-only: se confirma POST-parse (un
|
|
751
1025
|
# <label for> con su id le da nombre real y lo retira)
|
|
752
|
-
self._placeholder_candidates.append((tag, a, self.
|
|
1026
|
+
self._placeholder_candidates.append((tag, a, self._wrap_labels(a), _hidden))
|
|
753
1027
|
if a.get('required') is not None or 'required' in a or a.get('aria-required') == 'true':
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
self.required_no_indication.append(
|
|
758
|
-
f'{tag}[name={a.get("name","?")}]')
|
|
1028
|
+
# required sin indicación: la decisión es POST-parse — el «*»
|
|
1029
|
+
# puede vivir en el texto del <label for> (declarado después)
|
|
1030
|
+
self._required_pend.append((tag, a))
|
|
759
1031
|
if tag == 'input' and a.get('type') == 'radio':
|
|
760
1032
|
nm = a.get('name') or '(no name)'
|
|
761
1033
|
self._radio_group[nm] = self._radio_group.get(nm, 0) + 1
|
|
762
1034
|
self._radio_in_fieldset[nm] = self._in_fieldset
|
|
1035
|
+
self._radio_in_group[nm] = self._group_role_depth > 0
|
|
763
1036
|
if tag == 'fieldset':
|
|
764
1037
|
self._in_fieldset = True
|
|
765
1038
|
if tag in ('button', 'input'):
|
|
@@ -769,15 +1042,18 @@ class _Auditor(HTMLParser):
|
|
|
769
1042
|
# checkbox de términos
|
|
770
1043
|
if tag == 'input' and a.get('type') == 'checkbox':
|
|
771
1044
|
nm = (a.get('name') or '').lower()
|
|
772
|
-
|
|
1045
|
+
# el patrón español más común («confirmo», «revisado») era
|
|
1046
|
+
# invisible para un regex anglocéntrico: una casilla de
|
|
1047
|
+
# confirmación/revisión ES un paso de revisión (3.3.4)
|
|
1048
|
+
if re.search(r'terms|accept|agree|terminos|aceptar|legal|privacy'
|
|
1049
|
+
r'|confirm|revisado|revisar', nm):
|
|
773
1050
|
self._confirm_form = True
|
|
774
1051
|
if a.get('draggable') and (a.get('draggable') or '').lower() != 'false':
|
|
775
1052
|
if not a.get('onclick') and tag not in ('input', 'button'):
|
|
776
1053
|
self.drag_handlers.append(f'{tag}[draggable]')
|
|
777
1054
|
if a.get('aria-live') or (a.get('role') or '').lower() in ('status', 'alert', 'log'):
|
|
778
|
-
self.
|
|
779
|
-
|
|
780
|
-
self.char_shortcuts.append(f'{tag}[accesskey]')
|
|
1055
|
+
if not self._in_template:
|
|
1056
|
+
self.status_regions += 1
|
|
781
1057
|
# v3.12: 2.5.4 motion actuation handlers
|
|
782
1058
|
for _ma in ('ondeviceorientation', 'ondevicemotion'):
|
|
783
1059
|
if a.get(_ma):
|
|
@@ -786,19 +1062,22 @@ class _Auditor(HTMLParser):
|
|
|
786
1062
|
if tag == 'meta' and 'orientation' in (a.get('content') or '').lower() \
|
|
787
1063
|
and 'lock' in (a.get('content') or '').lower():
|
|
788
1064
|
self.orientation_locks.append('meta orientation lock')
|
|
789
|
-
# v3.9: 3.3.8 captcha
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
1065
|
+
# v3.9: 3.3.8 captcha — SOLO dentro de un form de autenticación (la
|
|
1066
|
+
# decisión es del endtag del form: ahí se sabe si hubo password/login)
|
|
1067
|
+
if not self._in_template:
|
|
1068
|
+
for _v in (a.get('src') or '', a.get('href') or '', a.get('id') or ''):
|
|
1069
|
+
if re.search(r'recaptcha|hcaptcha|turnstile|captcha', _v, re.I):
|
|
1070
|
+
self._form_captchas.append(f'{tag} {_v[:50]}')
|
|
1071
|
+
break
|
|
1072
|
+
if (a.get('name') or '').lower().find('captcha') >= 0:
|
|
1073
|
+
self._form_captchas.append(f'input name={a["name"][:30]}')
|
|
1074
|
+
# v3.1/v3.3: validez ARIA (atributos, referencias y VALORES) — el
|
|
1075
|
+
# contenido de <template> es inerte: sus aria-* no existen en el DOM
|
|
1076
|
+
for _ar in _ARIA_IDREFS if not self._in_template else ():
|
|
798
1077
|
if a.get(_ar):
|
|
799
1078
|
for _ref in a[_ar].split():
|
|
800
1079
|
self.aria_refs.append((_ar, _ref))
|
|
801
|
-
for _ar, _val in a.items():
|
|
1080
|
+
for _ar, _val in a.items() if not self._in_template else ():
|
|
802
1081
|
if not _ar.startswith('aria-'):
|
|
803
1082
|
continue
|
|
804
1083
|
_val = (_val or '').strip().lower()
|
|
@@ -808,7 +1087,11 @@ class _Auditor(HTMLParser):
|
|
|
808
1087
|
and not (_val == 'mixed' and _ar in ('aria-pressed', 'aria-checked')) \
|
|
809
1088
|
and not (_val == 'undefined' and _ar in _ARIA_BOOL_UNDEFINED):
|
|
810
1089
|
self.aria_values.append({'attr': _ar, 'val': _val, 'type': 'bool'})
|
|
811
|
-
elif _ar in _ARIA_INT and not _val.isdigit()
|
|
1090
|
+
elif _ar in _ARIA_INT and not _val.isdigit() \
|
|
1091
|
+
and not (_val == '-1' and _ar in ('aria-rowcount', 'aria-colcount',
|
|
1092
|
+
'aria-setsize')):
|
|
1093
|
+
# -1 en rowcount/colcount/setsize es OBLIGATORIO cuando el
|
|
1094
|
+
# total es desconocido (ARIA 1.2) — grids virtualizadas
|
|
812
1095
|
self.aria_values.append({'attr': _ar, 'val': _val, 'type': 'int'})
|
|
813
1096
|
elif _ar in _ARIA_NUM:
|
|
814
1097
|
try:
|
|
@@ -825,7 +1108,7 @@ class _Auditor(HTMLParser):
|
|
|
825
1108
|
self.aria_values.append({'attr': _ar, 'val': _val,
|
|
826
1109
|
'type': 'tokens',
|
|
827
1110
|
'valid_tokens': '/'.join(sorted(v for v in _ARIA_TOKENS[_ar] if v))})
|
|
828
|
-
if a.get('role'):
|
|
1111
|
+
if a.get('role') and not self._in_template:
|
|
829
1112
|
# role admite LISTA de tokens separados por espacios (con
|
|
830
1113
|
# fallback): TODOS deben ser roles válidos, no solo el primero
|
|
831
1114
|
for role in a['role'].strip().lower().split():
|
|
@@ -837,35 +1120,47 @@ class _Auditor(HTMLParser):
|
|
|
837
1120
|
landmark_role = a.get('role', '').lower() if a.get('role') in (
|
|
838
1121
|
'banner', 'contentinfo', 'navigation', 'complementary', 'main', 'form', 'search', 'region') else None
|
|
839
1122
|
lm = tag if tag in ('header', 'footer', 'nav', 'aside', 'main', 'search') else landmark_role
|
|
840
|
-
if lm and not
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
1123
|
+
if lm and not self._in_template:
|
|
1124
|
+
if a.get('id'):
|
|
1125
|
+
self._landmark_ids.add(a['id'])
|
|
1126
|
+
if lm == 'search':
|
|
1127
|
+
# un landmark search ES un mecanismo de búsqueda (2.4.5)
|
|
1128
|
+
self.has_search = True
|
|
1129
|
+
if not (a.get('aria-label') or a.get('aria-labelledby')):
|
|
1130
|
+
t = self.landmarks.setdefault(lm, [0, 0])
|
|
1131
|
+
t[0] += 1
|
|
1132
|
+
t[1] += 1
|
|
1133
|
+
else:
|
|
1134
|
+
self.landmarks.setdefault(lm, [0, 0])[1] += 1
|
|
1135
|
+
if a.get('accesskey') and not self._in_template:
|
|
1136
|
+
k = (a.get('accesskey') or '').strip().lower()
|
|
1137
|
+
if k:
|
|
1138
|
+
self.accesskeys[k] = self.accesskeys.get(k, 0) + 1
|
|
849
1139
|
if self._list_depth > 0 and self._li_depth == 0 \
|
|
850
1140
|
and tag not in ('li', 'script', 'template', 'ul', 'ol'):
|
|
851
1141
|
self._bad_list += 1
|
|
852
1142
|
# 4.1.2/2.1.2: enfocable dentro de un subárbol aria-hidden=true — el
|
|
853
1143
|
# aria-hidden=false anidado NO exime (ACT 6cfa84). No es enfocable:
|
|
854
|
-
# hidden por CSS/hidden (fuera de la navegación por tab
|
|
855
|
-
#
|
|
1144
|
+
# hidden por CSS/hidden (fuera de la navegación por tab — INCLUIDO el
|
|
1145
|
+
# display:none POR CLASE, el patrón hamburguesa .menu{display:none}),
|
|
1146
|
+
# tabindex negativo (cualquiera, no solo -1), o disabled.
|
|
856
1147
|
_ti_raw = (a.get('tabindex') or '').strip()
|
|
857
1148
|
_ti_num = None
|
|
858
|
-
|
|
1149
|
+
# isdecimal (NO isdigit): '²' pasa isdigit y revienta int() — un
|
|
1150
|
+
# atributo exótico jamás destruye el informe de 3 MB
|
|
1151
|
+
_ti_dec = _ti_raw if _ti_raw.isdecimal() else (
|
|
1152
|
+
_ti_raw[1:] if _ti_raw[:1] == '-' and _ti_raw[1:].isdecimal() else '')
|
|
1153
|
+
if _ti_dec != '':
|
|
859
1154
|
_ti_num = int(_ti_raw)
|
|
860
1155
|
_css_hidden = 'hidden' in a or 'display:none' in _style or 'visibility:hidden' in _style \
|
|
861
|
-
or self._css_hidden_stack[-1]
|
|
1156
|
+
or self._css_hidden_stack[-1] or self._focus_hidden_class()
|
|
862
1157
|
_native = (tag in ('button', 'summary', 'select', 'textarea', 'iframe')
|
|
863
1158
|
or (tag in ('a', 'area') and (a.get('href') or '').strip())
|
|
864
1159
|
or (tag == 'input' and (a.get('type') or 'text').lower() != 'hidden')
|
|
865
1160
|
or (tag in ('video', 'audio') and 'controls' in a))
|
|
866
1161
|
_enfocable = ((_native and 'disabled' not in a)
|
|
867
1162
|
or (_ti_num is not None and _ti_num >= 0))
|
|
868
|
-
if _ti_num
|
|
1163
|
+
if (_ti_num is not None and _ti_num < 0) or _css_hidden:
|
|
869
1164
|
_enfocable = False
|
|
870
1165
|
# centinela de foco off-screen (patrón modal): un link fuera de vista
|
|
871
1166
|
# cuyo id aparece en los scripts (el wiring de focus) NO cuenta — la
|
|
@@ -873,59 +1168,136 @@ class _Auditor(HTMLParser):
|
|
|
873
1168
|
# llegar DESPUÉS del link: la decisión se difiere a post-parse
|
|
874
1169
|
if (_hidden_aria or self._ah_true_depth > 0) and _enfocable:
|
|
875
1170
|
if re.search(r'(top|left)\s*:\s*-\d{3,}', a.get('style') or '', re.I):
|
|
876
|
-
self._ahf_deferred.append((tag, a.get('id')))
|
|
1171
|
+
self._ahf_deferred.append((tag, a, a.get('id')))
|
|
877
1172
|
else:
|
|
878
1173
|
self.aria_hidden_focusable.append(tag)
|
|
1174
|
+
self.aria_hidden_focusable_elems.append(a)
|
|
879
1175
|
if tag == 'area' and (a.get('href') or '').strip():
|
|
880
1176
|
# <area> es void: sin pila de control — se registra directo (el
|
|
881
1177
|
# nombre le llega del alt)
|
|
882
1178
|
self.controls_raw.append(('area', a, '', [], _hidden))
|
|
883
1179
|
if tag in ('h1', 'h2', 'h3', 'h4', 'h5', 'h6'):
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
1180
|
+
# role=none/presentation APAGA la semántica del encabezado; un
|
|
1181
|
+
# aria-level válido la SOBRESCRIBE (accname: h3[aria-level=4] ES 4)
|
|
1182
|
+
if (a.get('role') or '').strip().lower() in ('none', 'presentation') \
|
|
1183
|
+
or self._in_template:
|
|
1184
|
+
pass
|
|
1185
|
+
else:
|
|
1186
|
+
self._heading_level = int(tag[1])
|
|
1187
|
+
_alv = re.match(r'\d+', str(a.get('aria-level') or ''))
|
|
1188
|
+
if _alv:
|
|
1189
|
+
self._heading_level = int(_alv.group())
|
|
1190
|
+
self._heading_text = []
|
|
1191
|
+
self._heading_attrs = a
|
|
1192
|
+
self._heading_route = self._elem_paths.get(id(a))
|
|
1193
|
+
self._heading_hidden = _hidden
|
|
1194
|
+
self._heading_tag = tag
|
|
1195
|
+
elif (a.get('role') or '').lower() == 'heading' and not self._in_template:
|
|
1196
|
+
# role=heading cuenta como encabezado para el nombre (ffd0e9); sin
|
|
1197
|
+
# aria-level el nivel por defecto de ARIA es 2 — y un aria-level
|
|
1198
|
+
# basura JAMÁS tira el parse (int guardado)
|
|
1199
|
+
_alv = re.match(r'\d+', str(a.get('aria-level') or ''))
|
|
1200
|
+
self._heading_level = int(_alv.group()) if _alv else 2
|
|
892
1201
|
self._heading_text = []
|
|
893
1202
|
self._heading_attrs = a
|
|
1203
|
+
self._heading_route = self._elem_paths.get(id(a))
|
|
894
1204
|
self._heading_hidden = _hidden
|
|
895
1205
|
self._heading_tag = tag
|
|
896
1206
|
ti = a.get('tabindex')
|
|
897
|
-
if ti and ti.
|
|
1207
|
+
if ti and ti.isdecimal() and int(ti) > 0 and not self._in_template:
|
|
898
1208
|
self.positive_tabindices.append((tag, int(ti)))
|
|
1209
|
+
self.positive_tabindex_elems.append(a)
|
|
899
1210
|
|
|
900
1211
|
def handle_endtag(self, tag):
|
|
1212
|
+
# pila de rutas del kernel: pop normal si casa; si hay anidamiento
|
|
1213
|
+
# malformado, se descarta hasta el que casa; suelto, se ignora
|
|
1214
|
+
if self._path_stack:
|
|
1215
|
+
if self._path_stack[-1][0] == tag:
|
|
1216
|
+
self._path_stack.pop()
|
|
1217
|
+
else:
|
|
1218
|
+
for _i in range(len(self._path_stack) - 1, -1, -1):
|
|
1219
|
+
if self._path_stack[_i][0] == tag:
|
|
1220
|
+
del self._path_stack[_i:]
|
|
1221
|
+
break
|
|
901
1222
|
if tag not in _VOID:
|
|
902
|
-
|
|
903
|
-
|
|
1223
|
+
# LAS PILAS SE SINCRONIZAN como _path_stack: buscar el frame que
|
|
1224
|
+
# casa y descartar hasta él (un </span> suelto ya no arrastra el
|
|
1225
|
+
# elemento abierto de verdad — el texto no se malatribuye)
|
|
1226
|
+
_idx = None
|
|
1227
|
+
for _i in range(len(self._el_stack) - 1, -1, -1):
|
|
1228
|
+
if self._el_stack[_i][0] == tag:
|
|
1229
|
+
_idx = _i
|
|
1230
|
+
break
|
|
1231
|
+
if _idx is None:
|
|
1232
|
+
# endtag suelto… salvo controles: el navegador MANTIENE el
|
|
1233
|
+
# <a> abierto a través del </div> que lo arrastró (adoption
|
|
1234
|
+
# agency) — el enlace es real y hay que contarlo
|
|
1235
|
+
if tag in _CONTROLS:
|
|
1236
|
+
self._close_control(tag)
|
|
1237
|
+
return
|
|
1238
|
+
_nframes = len(self._el_stack) - _idx
|
|
1239
|
+
_closed_attrs = None # attrs del frame que CASA (el último popeado)
|
|
1240
|
+
for _ in range(_nframes):
|
|
1241
|
+
if not self._el_stack:
|
|
1242
|
+
break
|
|
904
1243
|
_etag, _eattrs, _ebuf = self._el_stack.pop()
|
|
1244
|
+
_closed_attrs = _eattrs
|
|
1245
|
+
if _etag == 'canvas':
|
|
1246
|
+
self.canvases.append((_eattrs, ' '.join(_ebuf).strip(),
|
|
1247
|
+
self.canvas_hidden.pop(id(_eattrs), False)))
|
|
905
1248
|
if _eattrs.get('id') and _eattrs['id'] in self._role_field_ids:
|
|
906
1249
|
self._field_buffers[_eattrs['id']] = _ebuf
|
|
907
1250
|
elif (_eattrs.get('role') or '').strip().lower() in _ROLE_FIELDS:
|
|
908
1251
|
self._role_field_text.append((_eattrs, ' '.join(_ebuf).strip()))
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
1252
|
+
if (_eattrs.get('role') or '').strip().lower() in ('group', 'radiogroup') \
|
|
1253
|
+
and self._group_role_depth > 0:
|
|
1254
|
+
self._group_role_depth -= 1
|
|
1255
|
+
# candidato stray-click que cierra: confirmar salvo delegación
|
|
1256
|
+
for _sp in self._stray_pend[:]:
|
|
1257
|
+
if _sp[1] is _eattrs:
|
|
1258
|
+
self._stray_pend.remove(_sp)
|
|
1259
|
+
if not _sp[3]:
|
|
1260
|
+
self.stray_clicks.append(_sp[0])
|
|
1261
|
+
self.stray_click_elems.append(_sp[1])
|
|
1262
|
+
if len(self._hidden_stack) > 1:
|
|
1263
|
+
self._hidden_stack.pop()
|
|
1264
|
+
self._css_hidden_stack.pop()
|
|
1265
|
+
if self._ah_true_stack and self._ah_true_stack.pop():
|
|
914
1266
|
self._ah_true_depth = max(0, self._ah_true_depth - 1)
|
|
1267
|
+
self._depth = max(0, self._depth - _nframes)
|
|
915
1268
|
self._open_ids = [(i, d) for (i, d) in self._open_ids if d <= self._depth]
|
|
916
1269
|
# controles cierran con SU etiqueta Y a SU profundidad — un <div>
|
|
917
1270
|
# anidado dentro de un div[role=button] no cierra el control (React)
|
|
918
1271
|
if self._ctrl and self._ctrl[-1]['tag'] == tag \
|
|
919
1272
|
and self._depth == self._ctrl[-1].get('depth', 0) - 1:
|
|
920
1273
|
self._close_control(tag)
|
|
921
|
-
if tag == '
|
|
922
|
-
self._in_head = False
|
|
923
|
-
elif tag == 'template':
|
|
1274
|
+
if tag == 'template':
|
|
924
1275
|
self._in_template = max(0, self._in_template - 1)
|
|
1276
|
+
if tag == 'svg':
|
|
1277
|
+
self._svg_depth = max(0, self._svg_depth - 1)
|
|
925
1278
|
if tag == 'title':
|
|
926
|
-
self.
|
|
927
|
-
|
|
928
|
-
|
|
1279
|
+
if self._in_svg_title:
|
|
1280
|
+
# <title> de svg: nombre del svg — alimenta al control abierto
|
|
1281
|
+
# (name-from-content: el botón-icono del W3C) y al registro
|
|
1282
|
+
# id→texto (labelledby al svg resuelve a su título)
|
|
1283
|
+
_svgtxt = ' '.join(self._svg_title_buf).strip()
|
|
1284
|
+
if _svgtxt:
|
|
1285
|
+
if self._ctrl:
|
|
1286
|
+
# nombre SÍ (accname from content); VISIBLE no — el
|
|
1287
|
+
# <title> de svg es texto alternativo, no renderizado
|
|
1288
|
+
self._ctrl[-1]['text'].append(_svgtxt)
|
|
1289
|
+
for _fr in reversed(self._el_stack):
|
|
1290
|
+
if _fr[0] == 'svg':
|
|
1291
|
+
self._svg_titles[id(_fr[1])] = _svgtxt
|
|
1292
|
+
if _fr[1].get('id'):
|
|
1293
|
+
self._id_text_parts.setdefault(_fr[1]['id'], []).append(_svgtxt)
|
|
1294
|
+
break
|
|
1295
|
+
self._in_svg_title = False
|
|
1296
|
+
self._svg_title_buf = []
|
|
1297
|
+
else:
|
|
1298
|
+
self._in_title = False
|
|
1299
|
+
self._titles_in_order.append(' '.join(self._title_buf))
|
|
1300
|
+
self._title_buf = []
|
|
929
1301
|
elif tag == 'script':
|
|
930
1302
|
self._in_script = False
|
|
931
1303
|
elif tag == 'style':
|
|
@@ -938,6 +1310,11 @@ class _Auditor(HTMLParser):
|
|
|
938
1310
|
if txt and (len(txt) < 2 or re.fullmatch(
|
|
939
1311
|
r'(campo|field|input|texto|text|dato|value|entrada|box|caja)[\s\d]*', lowered)):
|
|
940
1312
|
self.vague_labels.append(f'"{txt[:30]}"')
|
|
1313
|
+
# texto del label POR SU for: el «*» del required puede vivir aquí
|
|
1314
|
+
if self._label_for_stack:
|
|
1315
|
+
_lfor = self._label_for_stack.pop()
|
|
1316
|
+
if _lfor and txt:
|
|
1317
|
+
self._label_text_for[_lfor] = txt
|
|
941
1318
|
if self._labels_stack and not self._labels_stack.pop():
|
|
942
1319
|
self.orphan_labels += 1
|
|
943
1320
|
elif tag == 'fieldset':
|
|
@@ -945,6 +1322,13 @@ class _Auditor(HTMLParser):
|
|
|
945
1322
|
elif tag == 'form':
|
|
946
1323
|
if self._financial_form and not self._confirm_form:
|
|
947
1324
|
self.financial_no_confirm += 1
|
|
1325
|
+
# 3.3.8 Accessible Authentication: SOLO en proceso de autenticación
|
|
1326
|
+
# (form con password o acción de login) — un captcha en un form de
|
|
1327
|
+
# contacto no es un fallo de 3.3.8
|
|
1328
|
+
if self._form_auth:
|
|
1329
|
+
self.captchas.extend(self._form_captchas)
|
|
1330
|
+
self._form_captchas = []
|
|
1331
|
+
self._form_auth = False
|
|
948
1332
|
elif tag == 'nav':
|
|
949
1333
|
self._in_nav = max(0, self._in_nav - 1)
|
|
950
1334
|
elif tag == 'li':
|
|
@@ -955,13 +1339,29 @@ class _Auditor(HTMLParser):
|
|
|
955
1339
|
self._close_control(tag)
|
|
956
1340
|
elif tag == 'video':
|
|
957
1341
|
self._in_video = False
|
|
1342
|
+
if self._video_caps_stack:
|
|
1343
|
+
_vattrs, _vcaps, _vdesc = self._video_caps_stack.pop()
|
|
1344
|
+
if not _vcaps:
|
|
1345
|
+
self.videos_no_caps_elems.append(_vattrs)
|
|
1346
|
+
if not _vdesc:
|
|
1347
|
+
self.videos_no_desc_elems.append(_vattrs)
|
|
958
1348
|
elif tag == 'table':
|
|
959
|
-
if self.
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
1349
|
+
if self._table_stack and _closed_attrs is not None:
|
|
1350
|
+
_th_saved, _tattrs, _suspect, _data = self._table_stack[-1]
|
|
1351
|
+
# IDENTIDAD: solo decide la entrada cuya tabla se CIERRA (el
|
|
1352
|
+
# </table> de una presentation/template NUNCA apilada resbala
|
|
1353
|
+
# sin tocar la pila — antes popeaba la entrada de la externa)
|
|
1354
|
+
if _closed_attrs is _tattrs:
|
|
1355
|
+
self._table_stack.pop()
|
|
1356
|
+
if self._th_in_table:
|
|
1357
|
+
self.tables_with_th += 1
|
|
1358
|
+
elif _data or not _suspect:
|
|
1359
|
+
self.tables_no_th_elems.append(_tattrs)
|
|
1360
|
+
else:
|
|
1361
|
+
# maquetación por heurística: fuera del cómputo
|
|
1362
|
+
self.tables -= 1
|
|
1363
|
+
self._th_in_table = _th_saved
|
|
1364
|
+
self._in_table = bool(self._table_stack)
|
|
965
1365
|
elif tag == 'th':
|
|
966
1366
|
pass
|
|
967
1367
|
elif self._heading_level and tag == getattr(self, '_heading_tag', None):
|
|
@@ -969,7 +1369,8 @@ class _Auditor(HTMLParser):
|
|
|
969
1369
|
# aria-label tras strip, nombres de imgs internas)
|
|
970
1370
|
self.headings_raw.append((self._heading_level, dict(self._heading_attrs or {}),
|
|
971
1371
|
' '.join(self._heading_text).strip(),
|
|
972
|
-
getattr(self, '_heading_hidden', False)
|
|
1372
|
+
getattr(self, '_heading_hidden', False),
|
|
1373
|
+
getattr(self, '_heading_route', None)))
|
|
973
1374
|
self._heading_level = None
|
|
974
1375
|
|
|
975
1376
|
_RE_CHAR_KEY = re.compile(r'key(?:Code)?\s*===?\s*["\']([a-zA-Z0-9])["\']', re.S)
|
|
@@ -1012,26 +1413,49 @@ class _Auditor(HTMLParser):
|
|
|
1012
1413
|
self.lang_parts_invalid.append(_mark)
|
|
1013
1414
|
return
|
|
1014
1415
|
|
|
1015
|
-
_RE_RULE = re.compile(r'
|
|
1416
|
+
_RE_RULE = re.compile(r'([^{}]+)\{([^}]*)\}')
|
|
1016
1417
|
_RE_HIDDEN_STYLE = re.compile(r'clip-path|display\s*:\s*none|visibility\s*:\s*hidden'
|
|
1017
1418
|
r'|height\s*:\s*1px|width\s*:\s*1px|opacity\s*:\s*0')
|
|
1419
|
+
# subconjunto ESTRICTO para focuseabilidad: solo lo que saca del tab
|
|
1420
|
+
_RE_RULE_DISPLAY = re.compile(r'display\s*:\s*none|visibility\s*:\s*hidden')
|
|
1018
1421
|
|
|
1019
1422
|
def _hidden_class_style(self):
|
|
1020
1423
|
"""¿Algún ancestro abierto del control tiene una clase que el
|
|
1021
1424
|
<style> de la página declara como oculta (clip-path, position
|
|
1022
1425
|
absolute + 1px, display none, visibility hidden)? Las reglas se
|
|
1023
1426
|
cachean: reparsear TODO el css por nodo de texto era cuadrático."""
|
|
1427
|
+
return self._class_hides('hidden')
|
|
1428
|
+
|
|
1429
|
+
def _focus_hidden_class(self):
|
|
1430
|
+
"""Clase que saca el elemento del TAB (display:none/visibility:hidden
|
|
1431
|
+
por <style>) — MÁS ESTRICTA que _hidden_class_style: un
|
|
1432
|
+
.visually-hidden (clip/1px) SIGUE enfocable (el skip link vive ahí)."""
|
|
1433
|
+
return self._class_hides('focus')
|
|
1434
|
+
|
|
1435
|
+
def _class_hides(self, mode):
|
|
1436
|
+
"""¿Una clase abierta (del control o de un ancestro) la declara el
|
|
1437
|
+
<style> como oculta? Los SETS de clases-ocultas se computan UNA VEZ
|
|
1438
|
+
por <style> (no por elemento: reglas×profundidad×elementos era
|
|
1439
|
+
cuadrático — 2.15 s en deep-800×413-reglas, ahora lineal)."""
|
|
1024
1440
|
if self._styles_text is not self._styles_cached_src:
|
|
1025
1441
|
self._styles_cached_src = self._styles_text
|
|
1026
|
-
|
|
1442
|
+
# selectores agrupados (.a, .b {…}): cada clase del grupo cuenta
|
|
1443
|
+
self._style_rules = [
|
|
1444
|
+
(cls.lstrip('. '), body)
|
|
1445
|
+
for sel, body in self._RE_RULE.findall(self._styles_text)
|
|
1446
|
+
for cls in sel.split(',')]
|
|
1447
|
+
self._hidden_cls_set = {_s for _s, _b in self._style_rules
|
|
1448
|
+
if self._RE_HIDDEN_STYLE.search(_b)}
|
|
1449
|
+
self._nohiding_cls_set = {_s for _s, _b in self._style_rules
|
|
1450
|
+
if self._RE_RULE_DISPLAY.search(_b)}
|
|
1451
|
+
_set = self._hidden_cls_set if mode == 'hidden' else self._nohiding_cls_set
|
|
1452
|
+
if not _set:
|
|
1453
|
+
return False
|
|
1027
1454
|
_open_classes = [c.get('attrs', {}).get('class') for c in self._ctrl]
|
|
1028
|
-
|
|
1029
|
-
_open_classes.append(self._el_stack[-1][1].get('class'))
|
|
1455
|
+
_open_classes += (_fr[1].get('class') for _fr in self._el_stack)
|
|
1030
1456
|
for _cls in filter(None, _open_classes):
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
if _nom == _selector and self._RE_HIDDEN_STYLE.search(_body):
|
|
1034
|
-
return True
|
|
1457
|
+
if _set.intersection(_cls.split()):
|
|
1458
|
+
return True
|
|
1035
1459
|
return False
|
|
1036
1460
|
|
|
1037
1461
|
def handle_data(self, data):
|
|
@@ -1044,10 +1468,14 @@ class _Auditor(HTMLParser):
|
|
|
1044
1468
|
# lista por id + join único post-parse: la concatenación por
|
|
1045
1469
|
# nodo era cuadrática en páginas con wrappers id grandes
|
|
1046
1470
|
self._id_text_parts.setdefault(_id, []).append(data)
|
|
1471
|
+
if self._in_template:
|
|
1472
|
+
return # contenido INERTE: ni prosa visible, ni lang, ni nombres
|
|
1047
1473
|
if data.strip() and not in_code and not self._in_title:
|
|
1048
1474
|
self._visible_text.append(data) # prosa visible: ni JS, ni CSS, ni título
|
|
1049
1475
|
if self._in_title:
|
|
1050
1476
|
self._title_buf.append(data)
|
|
1477
|
+
elif self._in_svg_title:
|
|
1478
|
+
self._svg_title_buf.append(data)
|
|
1051
1479
|
elif getattr(self, '_in_script', False):
|
|
1052
1480
|
self.handle_script_wait(data)
|
|
1053
1481
|
elif getattr(self, '_in_style', False):
|
|
@@ -1103,11 +1531,13 @@ def normalize_report(report):
|
|
|
1103
1531
|
if not isinstance(report, dict):
|
|
1104
1532
|
return report
|
|
1105
1533
|
findings = report.get('findings')
|
|
1106
|
-
if not findings:
|
|
1534
|
+
if not isinstance(findings, list):
|
|
1535
|
+
if findings:
|
|
1536
|
+
return dict(report, findings=[]) # dict/str/… hostil: sin hallazgos
|
|
1107
1537
|
return report
|
|
1108
1538
|
out = dict(report)
|
|
1109
1539
|
out['findings'] = [dict(h, signal=normalize_signal(h.get('signal', '')))
|
|
1110
|
-
for h in findings]
|
|
1540
|
+
for h in findings if isinstance(h, dict)]
|
|
1111
1541
|
return out
|
|
1112
1542
|
|
|
1113
1543
|
|
|
@@ -1169,19 +1599,32 @@ def _not_measured(lang='en'):
|
|
|
1169
1599
|
} for c in sorted(RENDERED_ONLY)]
|
|
1170
1600
|
|
|
1171
1601
|
|
|
1172
|
-
def audit_html(html_text, url='(html)', lang='en'):
|
|
1602
|
+
def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
1173
1603
|
"""Analiza una cadena HTML y devuelve el informe de hallazgos (es/en)."""
|
|
1174
1604
|
p = _Auditor()
|
|
1175
1605
|
try:
|
|
1176
1606
|
p.feed(html_text[:MAX_HTML])
|
|
1177
1607
|
p.close()
|
|
1178
1608
|
except Exception as e: # noqa: BLE001
|
|
1179
|
-
|
|
1609
|
+
# un atributo hostil NO puede tirar la auditoría de 3 MB de página
|
|
1610
|
+
# válida: el mensaje viaja por el catálogo (es/en), como todo lo visible
|
|
1611
|
+
return {'error': _t(lang, 'err_unparseable').format(e=str(e)[:120])}
|
|
1180
1612
|
|
|
1181
|
-
# 1.3.1: grupos de radio (name compartido, ≥2) sin fieldset
|
|
1613
|
+
# 1.3.1: grupos de radio (name compartido, ≥2) sin fieldset NI grupo ARIA
|
|
1614
|
+
# con nombre (role=group/radiogroup + aria-label: la otra técnica de H71)
|
|
1182
1615
|
for nm, count in p._radio_group.items():
|
|
1183
|
-
if count >= 2 and not p._radio_in_fieldset.get(nm, False)
|
|
1616
|
+
if count >= 2 and not p._radio_in_fieldset.get(nm, False) \
|
|
1617
|
+
and not p._radio_in_group.get(nm, False):
|
|
1184
1618
|
p.missing_fieldsets += 1
|
|
1619
|
+
# 3.3.2: required sin indicación — la marca («*», «obligatorio») puede
|
|
1620
|
+
# vivir en el TEXTO del <label for> que el parser vio después del campo
|
|
1621
|
+
for tag, a in p._required_pend:
|
|
1622
|
+
ph = (a.get('placeholder') or '').lower()
|
|
1623
|
+
title_ = (a.get('title') or '').lower()
|
|
1624
|
+
_lbl = p._label_text_for.get(a.get('id') or '', '').lower()
|
|
1625
|
+
if not re.search(r'\*|requerid|obligator|required|necesari|precisa',
|
|
1626
|
+
ph + title_ + _lbl):
|
|
1627
|
+
p.required_no_indication.append(f'{tag}[name={a.get("name","?")}]')
|
|
1185
1628
|
|
|
1186
1629
|
# id→texto resuelto de una vez (partes acumuladas en streaming)
|
|
1187
1630
|
for _id, _parts in p._id_text_parts.items():
|
|
@@ -1189,9 +1632,16 @@ def audit_html(html_text, url='(html)', lang='en'):
|
|
|
1189
1632
|
|
|
1190
1633
|
# centinela off-screen: decidir con los scripts YA completos (el <script>
|
|
1191
1634
|
# llega después del link en el documento) — sin id o sin wiring = fallo
|
|
1192
|
-
for _tag, _tid in p._ahf_deferred:
|
|
1635
|
+
for _tag, _tattrs, _tid in p._ahf_deferred:
|
|
1193
1636
|
if not _tid or _tid not in p._scripts_text:
|
|
1194
1637
|
p.aria_hidden_focusable.append(_tag)
|
|
1638
|
+
p.aria_hidden_focusable_elems.append(_tattrs)
|
|
1639
|
+
# candidatos stray-click que nunca cerraron (HTML truncado): sin
|
|
1640
|
+
# interactivo dentro registrado, cuentan igual — el documento está roto
|
|
1641
|
+
for _sp in p._stray_pend:
|
|
1642
|
+
if not _sp[3]:
|
|
1643
|
+
p.stray_clicks.append(_sp[0])
|
|
1644
|
+
p.stray_click_elems.append(_sp[1])
|
|
1195
1645
|
|
|
1196
1646
|
# ── decisiones de nombre POST-parse ─────────────────────────────────────
|
|
1197
1647
|
# Los ids de un aria-labelledby pueden declararse DESPUÉS del elemento que
|
|
@@ -1209,7 +1659,7 @@ def audit_html(html_text, url='(html)', lang='en'):
|
|
|
1209
1659
|
# PERO un img presentacional ENFOCABLE (tabindex ≥ 0) sigue necesitando
|
|
1210
1660
|
# nombre: sigue en la navegación por tab (ACT 23a2a8)
|
|
1211
1661
|
_ti = (a.get('tabindex') or '').strip()
|
|
1212
|
-
_enfocable_img = _ti.
|
|
1662
|
+
_enfocable_img = _ti.isdecimal() and int(_ti) >= 0
|
|
1213
1663
|
if hidden or ((a.get('role') or '').strip().lower() in ('presentation', 'none')
|
|
1214
1664
|
and not _enfocable_img):
|
|
1215
1665
|
continue
|
|
@@ -1218,14 +1668,71 @@ def audit_html(html_text, url='(html)', lang='en'):
|
|
|
1218
1668
|
if 'alt' in a and (a['alt'] or '') == '':
|
|
1219
1669
|
continue
|
|
1220
1670
|
lb, al, ti = _name_sources(a)
|
|
1221
|
-
|
|
1671
|
+
# <svg role=img> con <title> hijo: el título ES su nombre (accname)
|
|
1672
|
+
# — la vía recomendada por el W3C para gráficos accesibles
|
|
1673
|
+
_svgt = p._svg_titles.get(id(a), '')
|
|
1674
|
+
if not (al or lb or ti or _svgt):
|
|
1222
1675
|
p.imgs_no_alt.append((a.get('src') or a.get('aria-label') or '(role=img)')[:100])
|
|
1676
|
+
p.imgs_no_alt_elems.append(a)
|
|
1677
|
+
|
|
1678
|
+
# 1.1.1: alt PRESENTE pero basura — filenames, palabras genéricas o
|
|
1679
|
+
# marcadores que PASAN el chequeo de presencia (axe image-alt incluido)
|
|
1680
|
+
# y aun así no dicen nada. Filtro, no veredicto: media, con ejemplos y
|
|
1681
|
+
# rutas. alt="" no entra (decorativo legítimo); sin alt lo juzga arriba.
|
|
1682
|
+
_alt_bad = []
|
|
1683
|
+
_alt_seen = {}
|
|
1684
|
+
for a, hidden in p.imgs_all:
|
|
1685
|
+
if hidden or (a.get('role') or '').strip().lower() in ('presentation', 'none'):
|
|
1686
|
+
continue
|
|
1687
|
+
_altv = ' '.join((a.get('alt') or '').split())
|
|
1688
|
+
if not _altv:
|
|
1689
|
+
continue
|
|
1690
|
+
_low = _altv.casefold()
|
|
1691
|
+
_reason = ''
|
|
1692
|
+
if _ALT_EXT_RX.search(_low):
|
|
1693
|
+
_reason = 'filename'
|
|
1694
|
+
elif _ALT_DUMP_RX.match(_low):
|
|
1695
|
+
_reason = 'filename'
|
|
1696
|
+
elif _low in _ALT_GENERIC:
|
|
1697
|
+
_reason = 'generic'
|
|
1698
|
+
elif len(_low.replace('.', '').strip()) <= 2:
|
|
1699
|
+
_reason = 'placeholder'
|
|
1700
|
+
if _reason:
|
|
1701
|
+
_alt_bad.append((_reason, _altv, a))
|
|
1702
|
+
else:
|
|
1703
|
+
_alt_seen.setdefault(_low, []).append(a)
|
|
1704
|
+
# duplicación en masa: el MISMO alt no vacío en ≥4 imágenes casi siempre
|
|
1705
|
+
# es una icon-list que debía ser alt=""
|
|
1706
|
+
for _low, _elems in _alt_seen.items():
|
|
1707
|
+
if len(_elems) >= 4:
|
|
1708
|
+
_alt_bad.append(('repeated', _elems[0].get('alt', _low), _elems[0]))
|
|
1709
|
+
_alt_pair_seen = set()
|
|
1710
|
+
_alt_bad_d = []
|
|
1711
|
+
for _reason, _altv, _a in _alt_bad:
|
|
1712
|
+
_key = (_reason, _altv.casefold())
|
|
1713
|
+
if _key in _alt_pair_seen:
|
|
1714
|
+
continue
|
|
1715
|
+
_alt_pair_seen.add(_key)
|
|
1716
|
+
_alt_bad_d.append((_reason, _altv, _a))
|
|
1717
|
+
p.alt_quality_bad = _alt_bad_d
|
|
1223
1718
|
for a, hidden in p.inputs_image:
|
|
1224
1719
|
if hidden:
|
|
1225
1720
|
continue
|
|
1226
1721
|
lb, al, ti = _name_sources(a)
|
|
1227
1722
|
if not ((a.get('alt') or '').strip() or al or lb or ti):
|
|
1228
1723
|
p.input_img_no_alt += 1
|
|
1724
|
+
for a, fallback, hidden in p.canvases:
|
|
1725
|
+
# canvas: la capa accesible suele inyectarla JS al renderizar el
|
|
1726
|
+
# gráfico — la señal estática es FILTRO (media); el pase rendered
|
|
1727
|
+
# juzga el nombre computado. Conservador: oculto/decorativo no acusa;
|
|
1728
|
+
# con texto de reserva no acusa (fallback content)
|
|
1729
|
+
if hidden or (a.get('role') or '').strip().lower() in ('presentation', 'none'):
|
|
1730
|
+
continue
|
|
1731
|
+
lb, al, ti = _name_sources(a)
|
|
1732
|
+
if al or lb or ti or fallback:
|
|
1733
|
+
continue
|
|
1734
|
+
p.canvas_no_layer.append(a)
|
|
1735
|
+
p.canvas_no_layer_elems.append(a)
|
|
1229
1736
|
for a, hidden in p.iframes_all:
|
|
1230
1737
|
# tabindex=-1 saca el iframe del orden de tab: la regla lo excluye;
|
|
1231
1738
|
# role=none/presentation le quita la semántica de iframe (ACT cae760)
|
|
@@ -1235,6 +1742,7 @@ def audit_html(html_text, url='(html)', lang='en'):
|
|
|
1235
1742
|
lb, al, ti = _name_sources(a)
|
|
1236
1743
|
if not ((a.get('title') or '').strip() or al or lb):
|
|
1237
1744
|
p.iframes_no_title.append((a.get('src') or '')[:100])
|
|
1745
|
+
p.iframes_no_title_elems.append(a)
|
|
1238
1746
|
for kind, a, text, img_attrs, hidden in p.controls_raw:
|
|
1239
1747
|
# input submit/reset/button llevan valor por defecto del navegador;
|
|
1240
1748
|
# disabled/hidden quedan fuera. El value de un <button> NO es su
|
|
@@ -1244,13 +1752,18 @@ def audit_html(html_text, url='(html)', lang='en'):
|
|
|
1244
1752
|
lb, al, ti = _name_sources(a)
|
|
1245
1753
|
_img_names = []
|
|
1246
1754
|
for ia in img_attrs:
|
|
1755
|
+
# el interior aria-hidden NO es nombre (accname: excluido del
|
|
1756
|
+
# name-from-content) — el icono decorativo junto al texto no miente
|
|
1757
|
+
if (ia.get('aria-hidden') or '').strip().lower() == 'true':
|
|
1758
|
+
_img_names.append('')
|
|
1759
|
+
continue
|
|
1247
1760
|
ilb, ial, iti = _name_sources(ia)
|
|
1248
1761
|
_img_names.append((ia.get('alt') or '').strip() or ial or ilb or iti)
|
|
1249
1762
|
if not (text.strip() or al or lb or ti
|
|
1250
1763
|
or ' '.join(x for x in _img_names if x).strip()
|
|
1251
1764
|
or (a.get('alt') or '').strip()):
|
|
1252
1765
|
p.controls_by_kind.setdefault(kind, []).append(a)
|
|
1253
|
-
for level, a, text, hidden in p.headings_raw:
|
|
1766
|
+
for level, a, text, hidden, _hroute in p.headings_raw:
|
|
1254
1767
|
if hidden:
|
|
1255
1768
|
continue
|
|
1256
1769
|
lb, al, _ti = _name_sources(a)
|
|
@@ -1262,7 +1775,11 @@ def audit_html(html_text, url='(html)', lang='en'):
|
|
|
1262
1775
|
if level == 1:
|
|
1263
1776
|
p.h1s += 1
|
|
1264
1777
|
lowered = heading_name.lower().strip()
|
|
1265
|
-
|
|
1778
|
+
# encabezado corto: solo SOSPECHOSO si no es un acrónimo/término
|
|
1779
|
+
# técnico conocido («FAQ», «API», «CSS»…) — len<4 en solitario
|
|
1780
|
+
# no prueba vaguedad
|
|
1781
|
+
_short_ok = heading_name.upper().replace(' ', '') in _SHORT_HEADINGS
|
|
1782
|
+
if (len(heading_name) < 4 and not _short_ok) or len(heading_name) > 120:
|
|
1266
1783
|
p.vague_headings.append(f'h{level} "{heading_name[:40]}"')
|
|
1267
1784
|
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):
|
|
1268
1785
|
p.vague_headings.append(f'h{level} "{heading_name[:40]}"')
|
|
@@ -1296,6 +1813,7 @@ def audit_html(html_text, url='(html)', lang='en'):
|
|
|
1296
1813
|
or _content_name)
|
|
1297
1814
|
if not (_has_real_name or _placeholder):
|
|
1298
1815
|
p.fields_no_label.append((kind or tag, (a.get('name') or '')[:60], a.get('id')))
|
|
1816
|
+
p.fields_no_label_elems.append(a)
|
|
1299
1817
|
for tag, a, en_label, hidden in p._placeholder_candidates:
|
|
1300
1818
|
# placeholder como ÚNICO nombre: revisión 3.3.2 (el accname del
|
|
1301
1819
|
# navegador lo cuenta, pero como etiqueta es débil — se declara)
|
|
@@ -1305,6 +1823,7 @@ def audit_html(html_text, url='(html)', lang='en'):
|
|
|
1305
1823
|
if not (lb or al or ti or en_label
|
|
1306
1824
|
or (a.get('id') and a['id'] in p._labels_for)):
|
|
1307
1825
|
p.placeholder_only.append(f'{tag}[placeholder="{(a.get("placeholder") or "")[:30]}"]')
|
|
1826
|
+
p.placeholder_only_elems.append(a)
|
|
1308
1827
|
|
|
1309
1828
|
findings = []
|
|
1310
1829
|
|
|
@@ -1312,28 +1831,58 @@ def audit_html(html_text, url='(html)', lang='en'):
|
|
|
1312
1831
|
h = {'severity': severity, 'criterion': _crit(lang, code), 'signal': key_msg,
|
|
1313
1832
|
'issue': _t(lang, key_msg, n=fmt.get('n')).format(**fmt)}
|
|
1314
1833
|
h['remediation'] = _t(lang, key_msg + '_rem').format(**fmt)
|
|
1834
|
+
paths = fmt.pop('paths', None)
|
|
1835
|
+
if paths:
|
|
1836
|
+
h['paths'] = paths[:5]
|
|
1315
1837
|
findings.append(h)
|
|
1316
1838
|
|
|
1317
1839
|
def add_ej(severity, code, key_msg, examples, **fmt):
|
|
1318
1840
|
add(severity, code, key_msg, **fmt)
|
|
1319
1841
|
findings[-1]['examples'] = examples[:5]
|
|
1320
1842
|
|
|
1843
|
+
if p.alt_quality_bad:
|
|
1844
|
+
_p_q = [p._elem_paths[id(_a)] for _r, _alt, _a in p.alt_quality_bad
|
|
1845
|
+
if id(_a) in p._elem_paths][:5]
|
|
1846
|
+
add_ej('medium', '1.1.1', 'alt_quality',
|
|
1847
|
+
[_alt[:40] for _r, _alt, _a in p.alt_quality_bad],
|
|
1848
|
+
n=len(p.alt_quality_bad), paths=_p_q)
|
|
1321
1849
|
if p.imgs_no_alt:
|
|
1322
|
-
|
|
1850
|
+
_p_img = [p._elem_paths[id(_a)] for _a in p.imgs_no_alt_elems
|
|
1851
|
+
if id(_a) in p._elem_paths][:5]
|
|
1852
|
+
add_ej('high', '1.1.1', 'img_no_alt', p.imgs_no_alt,
|
|
1853
|
+
n=len(p.imgs_no_alt), paths=_p_img)
|
|
1323
1854
|
if p.input_img_no_alt:
|
|
1324
1855
|
add('high', '1.1.1', 'input_img_alt', n=p.input_img_no_alt)
|
|
1856
|
+
if p.canvas_no_layer:
|
|
1857
|
+
_p_canvas = [p._elem_paths[id(_a)] for _a in p.canvas_no_layer_elems
|
|
1858
|
+
if id(_a) in p._elem_paths][:5]
|
|
1859
|
+
add_ej('medium', '1.1.1', 'canvas_no_accessible_layer', p.canvas_no_layer,
|
|
1860
|
+
n=len(p.canvas_no_layer), paths=_p_canvas)
|
|
1325
1861
|
for tag, controls in p.controls_by_kind.items():
|
|
1326
|
-
add('high', '4.1.2', 'ctrl_name', n=len(controls), tag=tag
|
|
1862
|
+
add('high', '4.1.2', 'ctrl_name', n=len(controls), tag=tag,
|
|
1863
|
+
paths=[p._elem_paths[id(_a)] for _a in controls
|
|
1864
|
+
if id(_a) in p._elem_paths][:5])
|
|
1327
1865
|
if p.aria_hidden_focusable:
|
|
1328
1866
|
add('high', '4.1.2', 'aria_hidden_focusable',
|
|
1329
|
-
n=len(p.aria_hidden_focusable), tag=p.aria_hidden_focusable[0]
|
|
1867
|
+
n=len(p.aria_hidden_focusable), tag=p.aria_hidden_focusable[0],
|
|
1868
|
+
paths=[p._elem_paths[id(_a)] for _a in p.aria_hidden_focusable_elems
|
|
1869
|
+
if id(_a) in p._elem_paths][:5])
|
|
1330
1870
|
if p.fields_no_label:
|
|
1331
1871
|
add_ej('high', '3.3.2', 'field_label',
|
|
1332
1872
|
[f'{t} name={n or "(no name)"}' for t, n, _i in p.fields_no_label],
|
|
1333
|
-
n=len(p.fields_no_label)
|
|
1873
|
+
n=len(p.fields_no_label),
|
|
1874
|
+
paths=[p._elem_paths[id(_a)] for _a in p.fields_no_label_elems
|
|
1875
|
+
if id(_a) in p._elem_paths][:5])
|
|
1334
1876
|
if p.stray_clicks:
|
|
1335
1877
|
add('high', '2.1.1', 'click_nonfocusable',
|
|
1336
|
-
n=len(p.stray_clicks), tag=p.stray_clicks[0]
|
|
1878
|
+
n=len(p.stray_clicks), tag=p.stray_clicks[0],
|
|
1879
|
+
paths=[p._elem_paths[id(_a)] for _a in p.stray_click_elems
|
|
1880
|
+
if id(_a) in p._elem_paths][:5])
|
|
1881
|
+
if p.role_no_tabindex:
|
|
1882
|
+
add_ej('low', '2.1.1', 'role_no_tabindex', p.role_no_tabindex,
|
|
1883
|
+
n=len(p.role_no_tabindex), example=', '.join(p.role_no_tabindex[:3]),
|
|
1884
|
+
paths=[p._elem_paths[id(_a)] for _a in p.role_no_tabindex_elems
|
|
1885
|
+
if id(_a) in p._elem_paths][:5])
|
|
1337
1886
|
if p.orphan_labels:
|
|
1338
1887
|
add('low', '3.3.2', 'label_orphan', n=p.orphan_labels)
|
|
1339
1888
|
if p._bad_list:
|
|
@@ -1343,7 +1892,8 @@ def audit_html(html_text, url='(html)', lang='en'):
|
|
|
1343
1892
|
# (idioma, título, bypass, encabezados) no aplican (ACT b5c3f8/3e12e1)
|
|
1344
1893
|
pass
|
|
1345
1894
|
elif not p.lang:
|
|
1346
|
-
add('medium', '3.1.1', 'lang_missing'
|
|
1895
|
+
add('medium', '3.1.1', 'lang_missing',
|
|
1896
|
+
paths=[path_segment('html', 1)])
|
|
1347
1897
|
elif p.lang.lower().split('-')[0] not in _LANG_CODES:
|
|
1348
1898
|
add('medium', '3.1.1', 'lang_invalid', lang=p.lang)
|
|
1349
1899
|
elif p.lang_region_invalid:
|
|
@@ -1351,16 +1901,21 @@ def audit_html(html_text, url='(html)', lang='en'):
|
|
|
1351
1901
|
# el PRIMER <title> del documento decide (modelo ACT 2779a5)
|
|
1352
1902
|
p.title = p._titles_in_order[0] if p._titles_in_order else ''
|
|
1353
1903
|
t_clean = (p.title or '').strip().lower()
|
|
1354
|
-
if not t_clean:
|
|
1904
|
+
if not t_clean and p.root_tag not in ('svg', 'math'):
|
|
1355
1905
|
add('medium', '2.4.2', 'title_missing')
|
|
1356
1906
|
elif t_clean in ('untitled', 'documento', 'documento sin título', 'sin título',
|
|
1357
1907
|
'home', 'inicio', 'page 1', 'new page', 'página 1',
|
|
1358
1908
|
'untitled document', 'sin nombre', 'document'):
|
|
1359
1909
|
add('low', '2.4.2', 'title_generic', t=t_clean)
|
|
1360
1910
|
if p.iframes_no_title:
|
|
1361
|
-
add_ej('medium', '4.1.2', 'iframe_title', p.iframes_no_title,
|
|
1362
|
-
|
|
1363
|
-
|
|
1911
|
+
add_ej('medium', '4.1.2', 'iframe_title', p.iframes_no_title,
|
|
1912
|
+
n=len(p.iframes_no_title),
|
|
1913
|
+
paths=[p._elem_paths[id(_a)] for _a in p.iframes_no_title_elems
|
|
1914
|
+
if id(_a) in p._elem_paths][:5])
|
|
1915
|
+
if p.videos and p.videos_no_caps_elems:
|
|
1916
|
+
add('medium', '1.2.2', 'video_captions', n=len(p.videos_no_caps_elems),
|
|
1917
|
+
paths=[p._elem_paths[id(_a)] for _a in p.videos_no_caps_elems
|
|
1918
|
+
if id(_a) in p._elem_paths][:5])
|
|
1364
1919
|
if p.viewport:
|
|
1365
1920
|
# valores inválidos también blocksn (ACT b4f0c3): user-scalable ha de
|
|
1366
1921
|
# ser yes/true o numérico ≥ 1; maximum-scale numérico — si no parsea,
|
|
@@ -1373,7 +1928,9 @@ def audit_html(html_text, url='(html)', lang='en'):
|
|
|
1373
1928
|
except ValueError:
|
|
1374
1929
|
allows = v in ('yes', 'true')
|
|
1375
1930
|
if not allows:
|
|
1376
|
-
add('high', '1.4.4', 'zoom_no'
|
|
1931
|
+
add('high', '1.4.4', 'zoom_no',
|
|
1932
|
+
paths=([p._elem_paths[id(p._viewport_elem)]]
|
|
1933
|
+
if p._viewport_elem and id(p._viewport_elem) in p._elem_paths else None))
|
|
1377
1934
|
m_ms = re.search(r'maximum-scale\s*=\s*([\w.-]+)', p.viewport, re.I)
|
|
1378
1935
|
if m_ms:
|
|
1379
1936
|
_v_ms = m_ms.group(1)
|
|
@@ -1384,23 +1941,34 @@ def audit_html(html_text, url='(html)', lang='en'):
|
|
|
1384
1941
|
blocks = _v_ms.lower() not in ('device-width', 'device-height',
|
|
1385
1942
|
'initial-scale', 'width', 'height')
|
|
1386
1943
|
if blocks:
|
|
1387
|
-
|
|
1944
|
+
# mismo daño que user-scalable=no (bloquea el zoom del usuario):
|
|
1945
|
+
# misma severidad — ACT b4f0c3 no las distingue
|
|
1946
|
+
add('high', '1.4.4', 'zoom_max', v=_v_ms,
|
|
1947
|
+
paths=([p._elem_paths[id(p._viewport_elem)]]
|
|
1948
|
+
if p._viewport_elem and id(p._viewport_elem) in p._elem_paths else None))
|
|
1388
1949
|
# meta refresh (2.2.1/ACT bc659a): gana el PRIMER meta que parsea según
|
|
1389
1950
|
# los pasos del HTML (dígitos + ; o , o fin — un «0: url» con dos puntos
|
|
1390
1951
|
# NO parsea y se salta); 0 segundos = redirección inmediata y > 72000
|
|
1391
1952
|
# (20 h) quedan EXENTOS
|
|
1392
1953
|
_mr = None
|
|
1393
|
-
|
|
1954
|
+
_mr_elem = None
|
|
1955
|
+
for _idx_mr, _content in enumerate(p.meta_refreshes
|
|
1956
|
+
or ([p.meta_refresh] if p.meta_refresh else [])):
|
|
1394
1957
|
_m = re.match(r'\s*(\d+)\s*(?:[;,]|$)', _content or '')
|
|
1395
1958
|
if _m:
|
|
1396
1959
|
_mr = int(_m.group(1))
|
|
1960
|
+
_mr_elem = p._meta_refresh_elems[_idx_mr] if _idx_mr < len(p._meta_refresh_elems) else None
|
|
1397
1961
|
break
|
|
1398
1962
|
if _mr is not None and 0 < _mr <= 72000:
|
|
1399
|
-
add('medium', '2.2.1', 'meta_refresh', v=_mr
|
|
1963
|
+
add('medium', '2.2.1', 'meta_refresh', v=_mr,
|
|
1964
|
+
paths=([p._elem_paths[id(_mr_elem)]]
|
|
1965
|
+
if _mr_elem and id(_mr_elem) in p._elem_paths else None))
|
|
1400
1966
|
if p.positive_tabindices:
|
|
1401
1967
|
add_ej('medium', '2.4.3', 'tabindex_pos',
|
|
1402
1968
|
[f'{t}[tabindex={i}]' for t, i in p.positive_tabindices],
|
|
1403
|
-
n=len(p.positive_tabindices)
|
|
1969
|
+
n=len(p.positive_tabindices),
|
|
1970
|
+
paths=[p._elem_paths[id(_a)] for _a in p.positive_tabindex_elems
|
|
1971
|
+
if id(_a) in p._elem_paths][:5])
|
|
1404
1972
|
# un toggle cuenta como mecanismo de abatido SOLO si la función que
|
|
1405
1973
|
# invoca colapsa de verdad (su cuerpo, en el script de la página, toca
|
|
1406
1974
|
# `display`): mover off-screen o aria-hidden no colapsa el bloque (3e12e1)
|
|
@@ -1425,12 +1993,16 @@ def audit_html(html_text, url='(html)', lang='en'):
|
|
|
1425
1993
|
_nav_collapsible = not re.search(r'visib|aria', _nom) \
|
|
1426
1994
|
and bool(re.search(r'hide|hidden|collapse|display', _nom))
|
|
1427
1995
|
if p.root_tag not in ('svg', 'math') and not (p.hay_main or p.hay_skip or _nav_collapsible):
|
|
1428
|
-
|
|
1996
|
+
# revisión (best-practice al nivel de axe «bypass»): 2.4.1 aplica a
|
|
1997
|
+
# bloques REPETIDOS — en estático no se puede saber si se repiten
|
|
1998
|
+
add('low', '2.4.1', 'no_bypass')
|
|
1429
1999
|
|
|
1430
2000
|
levels = [n for n, _ in p.headings]
|
|
1431
2001
|
if levels:
|
|
1432
2002
|
if p.h1s == 0:
|
|
1433
|
-
|
|
2003
|
+
# best-practice (axe page-has-heading-one), no fallo 1.3.1: WCAG
|
|
2004
|
+
# no exige h1 — y en SPAs el h1 suele llegar del render del cliente
|
|
2005
|
+
add('low', '1.3.1', 'no_h1')
|
|
1434
2006
|
elif p.h1s > 1:
|
|
1435
2007
|
add('low', '1.3.1', 'multi_h1', n=p.h1s)
|
|
1436
2008
|
prev = 0
|
|
@@ -1442,16 +2014,22 @@ def audit_html(html_text, url='(html)', lang='en'):
|
|
|
1442
2014
|
if jumps:
|
|
1443
2015
|
add('low', '1.3.1', 'heading_skips', skips=', '.join(jumps[:5]))
|
|
1444
2016
|
elif p.root_tag not in ('svg', 'math'):
|
|
1445
|
-
add('
|
|
2017
|
+
add('low', '1.3.1', 'no_headings')
|
|
1446
2018
|
if p.empty_h:
|
|
1447
2019
|
add('low', '1.3.1', 'empty_heading', n=p.empty_h)
|
|
1448
2020
|
if p.tables and p.tables_with_th < p.tables:
|
|
1449
|
-
add('medium', '1.3.1', 'table_no_th', n=p.tables - p.tables_with_th
|
|
2021
|
+
add('medium', '1.3.1', 'table_no_th', n=p.tables - p.tables_with_th,
|
|
2022
|
+
paths=[p._elem_paths[id(_a)] for _a in p.tables_no_th_elems
|
|
2023
|
+
if id(_a) in p._elem_paths][:5])
|
|
1450
2024
|
if p.blank_no_warning:
|
|
1451
|
-
add('low', '3.2.5', 'blank_no_warning', n=p.blank_no_warning
|
|
2025
|
+
add('low', '3.2.5', 'blank_no_warning', n=p.blank_no_warning,
|
|
2026
|
+
paths=[p._elem_paths[id(_a)] for _a in p.blank_no_warning_elems
|
|
2027
|
+
if id(_a) in p._elem_paths][:5])
|
|
1452
2028
|
dups = sum(1 for _c, k in p.ids.items() if k > 1)
|
|
1453
2029
|
if dups:
|
|
1454
|
-
|
|
2030
|
+
add_ej('low', '4.1.2', 'dup_ids',
|
|
2031
|
+
[f'"{_c}" ×{_k}' for _c, _k in list(p.ids.items()) if _k > 1],
|
|
2032
|
+
n=dups)
|
|
1455
2033
|
|
|
1456
2034
|
# --- v3.1: validez ARIA, autocomplete, enlaces, landmarks, accesskey ---
|
|
1457
2035
|
broken_refs = [f'{attr}="#{ref}"' for attr, ref in p.aria_refs if ref not in p.ids]
|
|
@@ -1474,12 +2052,16 @@ def audit_html(html_text, url='(html)', lang='en'):
|
|
|
1474
2052
|
n=len(p.roles_without_state), example=', '.join(p.roles_without_state[:4]))
|
|
1475
2053
|
if p.missing_autocomplete:
|
|
1476
2054
|
add_ej('medium', '1.3.5', 'autocomplete', p.missing_autocomplete,
|
|
1477
|
-
n=len(p.missing_autocomplete), example=', '.join(p.missing_autocomplete[:4])
|
|
2055
|
+
n=len(p.missing_autocomplete), example=', '.join(p.missing_autocomplete[:4]),
|
|
2056
|
+
paths=[p._elem_paths[id(_a)] for _a in p.autocomplete_elems
|
|
2057
|
+
if id(_a) in p._elem_paths][:5])
|
|
1478
2058
|
if p.autocomplete_invalid:
|
|
1479
2059
|
add_ej('medium', '1.3.5', 'autocomplete_invalid', p.autocomplete_invalid,
|
|
1480
2060
|
n=len(p.autocomplete_invalid), example=', '.join(p.autocomplete_invalid[:4]))
|
|
1481
2061
|
if p.media_autoplay:
|
|
1482
|
-
add('medium', '1.4.2', 'video_autoplay', n=p.media_autoplay
|
|
2062
|
+
add('medium', '1.4.2', 'video_autoplay', n=p.media_autoplay,
|
|
2063
|
+
paths=[p._elem_paths[id(_a)] for _a in p.media_autoplay_elems
|
|
2064
|
+
if id(_a) in p._elem_paths][:5])
|
|
1483
2065
|
if p.label_no_name:
|
|
1484
2066
|
_ln = p.label_no_name[0]
|
|
1485
2067
|
add_ej('medium', '2.5.3', 'label_in_name',
|
|
@@ -1494,7 +2076,9 @@ def audit_html(html_text, url='(html)', lang='en'):
|
|
|
1494
2076
|
# forms deep-dive
|
|
1495
2077
|
if p.placeholder_only:
|
|
1496
2078
|
add_ej('high', '3.3.2', 'placeholder_only', p.placeholder_only,
|
|
1497
|
-
n=len(p.placeholder_only), example=', '.join(p.placeholder_only[:3])
|
|
2079
|
+
n=len(p.placeholder_only), example=', '.join(p.placeholder_only[:3]),
|
|
2080
|
+
paths=[p._elem_paths[id(_a)] for _a in p.placeholder_only_elems
|
|
2081
|
+
if id(_a) in p._elem_paths][:5])
|
|
1498
2082
|
if p.required_no_indication:
|
|
1499
2083
|
add_ej('low', '3.3.2', 'required_no_indication', p.required_no_indication,
|
|
1500
2084
|
n=len(p.required_no_indication), example=', '.join(p.required_no_indication[:3]))
|
|
@@ -1514,10 +2098,13 @@ def audit_html(html_text, url='(html)', lang='en'):
|
|
|
1514
2098
|
if p.drag_handlers:
|
|
1515
2099
|
add_ej('low', '2.5.7', 'drag_no_alt', p.drag_handlers,
|
|
1516
2100
|
n=len(p.drag_handlers), example=', '.join(p.drag_handlers[:3]))
|
|
1517
|
-
# 4.1.3:
|
|
1518
|
-
|
|
2101
|
+
# 4.1.3: señal de REVISIÓN y solo con evidencia fuerte de interactividad
|
|
2102
|
+
# propia (handlers de arrastre/clicks huérfanos/atajos) — un <script>
|
|
2103
|
+
# cualquiera (analytics, JSON-LD) o un campo sin label NO crean mensajes
|
|
2104
|
+
# de estado: 4.1.3 solo aplica cuando EXISTEN mensajes que anunciar
|
|
2105
|
+
dynamic = bool(p.stray_clicks or p.char_shortcuts or p.drag_handlers)
|
|
1519
2106
|
if dynamic and p.status_regions == 0:
|
|
1520
|
-
add('
|
|
2107
|
+
add('low', '4.1.3', 'no_status_regions')
|
|
1521
2108
|
if p.images_of_text:
|
|
1522
2109
|
add_ej('low', '1.4.5', 'images_of_text', p.images_of_text,
|
|
1523
2110
|
n=len(p.images_of_text), ej2='')
|
|
@@ -1537,8 +2124,10 @@ def audit_html(html_text, url='(html)', lang='en'):
|
|
|
1537
2124
|
if p.orientation_locks:
|
|
1538
2125
|
add_ej('low', '1.3.4', 'orientation_lock', p.orientation_locks,
|
|
1539
2126
|
n=len(p.orientation_locks), example=', '.join(p.orientation_locks[:2]))
|
|
1540
|
-
if p.videos and p.
|
|
1541
|
-
add('low', '1.2.3', 'audio_desc_missing', n=p.
|
|
2127
|
+
if p.videos and p.videos_no_desc_elems:
|
|
2128
|
+
add('low', '1.2.3', 'audio_desc_missing', n=len(p.videos_no_desc_elems),
|
|
2129
|
+
paths=[p._elem_paths[id(_a)] for _a in p.videos_no_desc_elems
|
|
2130
|
+
if id(_a) in p._elem_paths][:5])
|
|
1542
2131
|
if p.sensory:
|
|
1543
2132
|
add('low', '1.3.3', 'sensory_text', example='; '.join(p.sensory[:2])[:70])
|
|
1544
2133
|
lm_dups = [f'{lm} ×{t[1]}' for lm, t in p.landmarks.items()
|
|
@@ -1565,9 +2154,11 @@ def audit_html(html_text, url='(html)', lang='en'):
|
|
|
1565
2154
|
reading = _reading_level(' '.join(p._visible_text),
|
|
1566
2155
|
page_lang if page_lang in ('es', 'en') else lang)
|
|
1567
2156
|
|
|
2157
|
+
import hashlib as _hl
|
|
1568
2158
|
res = {
|
|
1569
2159
|
'mode': 'static',
|
|
1570
2160
|
'url': url,
|
|
2161
|
+
'source_sha256': _hl.sha256(html_text.encode('utf-8', 'replace')).hexdigest(),
|
|
1571
2162
|
'reading_level': reading,
|
|
1572
2163
|
'score': compute_score(findings),
|
|
1573
2164
|
'score_note': _t(lang, 'score_note'),
|
|
@@ -1577,6 +2168,27 @@ def audit_html(html_text, url='(html)', lang='en'):
|
|
|
1577
2168
|
'findings': findings,
|
|
1578
2169
|
'limits': _t(lang, 'limits'),
|
|
1579
2170
|
}
|
|
2171
|
+
# rasgos de aplicabilidad (evidencia positiva para a11yscope): cuentan
|
|
2172
|
+
# lo que el parser VIO, no lo que dejó de señalar. Va SIEMPRE (vacío es
|
|
2173
|
+
# evidencia: el parser corrió y no vio ninguno) — un informe sin bloque
|
|
2174
|
+
# es un informe viejo y a11yscope no propone nada sobre él.
|
|
2175
|
+
res['features'] = dict(sorted(p.features.items()))
|
|
2176
|
+
# --standard en301549: cláusula EN por hallazgo + bloque del estándar
|
|
2177
|
+
if standard == 'en301549':
|
|
2178
|
+
from . import a11yen301549 as _enstd
|
|
2179
|
+
_tgt = target or _enstd.target_for_mode('static')
|
|
2180
|
+
res['standard'] = _enstd.standard_block(_tgt, lang)
|
|
2181
|
+
for h in findings:
|
|
2182
|
+
_cl = _enstd.clause_for(h['criterion'].split(' ')[0], _tgt)
|
|
2183
|
+
if _cl:
|
|
2184
|
+
h['clause'] = _cl
|
|
2185
|
+
elif standard == 'rgaa':
|
|
2186
|
+
from . import a11yrgaa as _rg
|
|
2187
|
+
res['standard'] = _rg.standard_block(lang)
|
|
2188
|
+
for h in findings:
|
|
2189
|
+
_rgaa = _rg.rgaa_for_sc(h['criterion'].split(' ')[0])
|
|
2190
|
+
if _rgaa:
|
|
2191
|
+
h['rgaa'] = _rgaa
|
|
1580
2192
|
# overlays detectados: dato del informe (diligencia de compra), nunca un
|
|
1581
2193
|
# hallazgo — no hay criterio WCAG que anclar y el score no se toca
|
|
1582
2194
|
overlays, _seen = [], set()
|
|
@@ -1592,18 +2204,61 @@ def audit_html(html_text, url='(html)', lang='en'):
|
|
|
1592
2204
|
return res
|
|
1593
2205
|
|
|
1594
2206
|
|
|
2207
|
+
class _FetchError(ValueError):
|
|
2208
|
+
"""Error de descarga CON CLAVE de catálogo (es/en): el mensaje visible
|
|
2209
|
+
viaja por locales, no hardcodeado — invariante bilingüe del repo."""
|
|
2210
|
+
def __init__(self, key, **fmt):
|
|
2211
|
+
super().__init__(key)
|
|
2212
|
+
self.key, self.fmt = key, fmt
|
|
2213
|
+
|
|
2214
|
+
|
|
1595
2215
|
# ── redirect policy hook ───────────────────────────────────────────────────
|
|
1596
2216
|
# urlopen follows 3xx (up to 10 hops) to ANY host without asking: every hop
|
|
1597
|
-
# is a NEW destination nobody validated.
|
|
1598
|
-
#
|
|
1599
|
-
#
|
|
1600
|
-
|
|
2217
|
+
# is a NEW destination nobody validated. DEFAULT: every redirect hop is
|
|
2218
|
+
# resolved and rejected if it lands on a private network (loopback, RFC1918,
|
|
2219
|
+
# link-local incl. cloud metadata 169.254.169.254…) — the classic SSRF pivot
|
|
2220
|
+
# (public URL → internal hop). The URL the USER typed is explicit intent and
|
|
2221
|
+
# is never blocked; only implicit hops are. Callers can inject their own
|
|
2222
|
+
# validator (callable(url) -> bool) or pass True to allow everything.
|
|
2223
|
+
validate_redirect = None # inyectable: callable(url) -> bool
|
|
2224
|
+
|
|
2225
|
+
|
|
2226
|
+
def _redirect_to_private(url):
|
|
2227
|
+
"""True si la URL resuelve a una IP no pública (fail-closed)."""
|
|
2228
|
+
import ipaddress
|
|
2229
|
+
import socket
|
|
2230
|
+
from urllib.parse import urlsplit
|
|
2231
|
+
try:
|
|
2232
|
+
host = urlsplit(url).hostname or ''
|
|
2233
|
+
infos = socket.getaddrinfo(host, None)
|
|
2234
|
+
except (OSError, ValueError):
|
|
2235
|
+
return True # no resuelve: cerrar, no seguir
|
|
2236
|
+
for _fam, _ty, _pr, _ad, sa in infos:
|
|
2237
|
+
try:
|
|
2238
|
+
ip = ipaddress.ip_address(sa[0])
|
|
2239
|
+
except ValueError:
|
|
2240
|
+
return True
|
|
2241
|
+
if ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved \
|
|
2242
|
+
or ip.is_multicast or ip.is_unspecified:
|
|
2243
|
+
return True
|
|
2244
|
+
return False
|
|
1601
2245
|
|
|
1602
2246
|
|
|
1603
2247
|
class _CheckedRedirect(urllib.request.HTTPRedirectHandler):
|
|
1604
2248
|
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
1605
|
-
|
|
1606
|
-
|
|
2249
|
+
_guard = validate_redirect
|
|
2250
|
+
if _guard is None:
|
|
2251
|
+
# saltos que MANTIENEN el host que el usuario escribió conservan
|
|
2252
|
+
# su intent explícito (dev en localhost: /app→/app/, http→https):
|
|
2253
|
+
# solo los saltos a OTRO destino pasan el filtro de red privada
|
|
2254
|
+
from urllib.parse import urlsplit as _us
|
|
2255
|
+
try:
|
|
2256
|
+
_same = (_us(newurl).netloc.lower() == (req.host or '').lower())
|
|
2257
|
+
except Exception: # noqa: BLE001
|
|
2258
|
+
_same = False
|
|
2259
|
+
_guard = (lambda _u: _same or not _redirect_to_private(_u))
|
|
2260
|
+
if _guard is not True and not _guard(newurl):
|
|
2261
|
+
raise _FetchError('err_redirect_blocked', url=newurl[:96])
|
|
1607
2262
|
return super().redirect_request(req, fp, code, msg, headers, newurl)
|
|
1608
2263
|
|
|
1609
2264
|
|
|
@@ -1641,7 +2296,7 @@ def _fetch(url, timeout=30, truncate_at=None, accept_ct=()):
|
|
|
1641
2296
|
break
|
|
1642
2297
|
data += chunk
|
|
1643
2298
|
if len(data) > ceiling and truncate_at is None:
|
|
1644
|
-
raise
|
|
2299
|
+
raise _FetchError('err_too_big', mb=MAX_HTML // 1000000)
|
|
1645
2300
|
if (r.headers.get('Content-Encoding') or '').lower() == 'gzip' or data[:2] == b'\x1f\x8b':
|
|
1646
2301
|
import zlib
|
|
1647
2302
|
d = zlib.decompressobj(16 + zlib.MAX_WBITS)
|
|
@@ -1652,7 +2307,7 @@ def _fetch(url, timeout=30, truncate_at=None, accept_ct=()):
|
|
|
1652
2307
|
base = ctype.split(';')[0].strip()
|
|
1653
2308
|
extra_ok = any(base == p or base.startswith(p + '/') for p in accept_ct)
|
|
1654
2309
|
if ctype and not extra_ok and 'html' not in ctype and 'xml' not in ctype and base:
|
|
1655
|
-
raise
|
|
2310
|
+
raise _FetchError('err_not_html', ct=base)
|
|
1656
2311
|
# the HEADER charset wins over body sniffing (HTTP has priority over
|
|
1657
2312
|
# <meta>): a server declaring iso-8859-1 without a meta tag otherwise
|
|
1658
2313
|
# produces U+FFFD inside findings
|
|
@@ -1676,16 +2331,18 @@ _T_SCHEME = {
|
|
|
1676
2331
|
}
|
|
1677
2332
|
|
|
1678
2333
|
|
|
1679
|
-
def audit_url(url, timeout=30, lang='en'):
|
|
2334
|
+
def audit_url(url, timeout=30, lang='en', standard=None, target=None):
|
|
1680
2335
|
if url.split(':')[0].lower() not in ('http', 'https'):
|
|
1681
2336
|
return {'error': _T_SCHEME.get(lang, _T_SCHEME['es'])}
|
|
1682
2337
|
try:
|
|
1683
2338
|
html_text = _fetch(url, timeout=timeout)
|
|
2339
|
+
except _FetchError as e:
|
|
2340
|
+
return {'error': _t(lang, e.key).format(**e.fmt)}
|
|
1684
2341
|
except ValueError as e:
|
|
1685
2342
|
return {'error': str(e)}
|
|
1686
2343
|
except Exception as e: # noqa: BLE001
|
|
1687
2344
|
return {'error': _t(lang, 'fetch_error').format(e=e)}
|
|
1688
|
-
return audit_html(html_text, url, lang=lang)
|
|
2345
|
+
return audit_html(html_text, url, lang=lang, standard=standard, target=target)
|
|
1689
2346
|
|
|
1690
2347
|
|
|
1691
2348
|
_LOC = re.compile(r'<loc>\s*([^<\s]+)\s*</loc>', re.I)
|
|
@@ -1767,7 +2424,10 @@ def evaluate_site(parsers, lang='en'):
|
|
|
1767
2424
|
'issue': _t(lang, 'help_inconsistent').format(
|
|
1768
2425
|
example=f'{len(set(signatures_help))} variantes en {len(signatures_help)} páginas'),
|
|
1769
2426
|
'remediation': _t(lang, 'help_inconsistent_rem')})
|
|
1770
|
-
|
|
2427
|
+
# 2.4.5 exige múltiples formas de encontrar PÁGINAS: con una muestra de
|
|
2428
|
+
# una sola página no hay proceso multi-página que reclamarlo (FP en
|
|
2429
|
+
# sitios de una página — la excepción del propio criterio)
|
|
2430
|
+
if len(parsers) >= 2 and not any(p.has_search or p.has_sitemap for p in parsers):
|
|
1771
2431
|
out.append({'severity': 'medium', 'criterion': _crit(lang, '2.4.5'),
|
|
1772
2432
|
'signal': 'no_multiple_ways',
|
|
1773
2433
|
'issue': _t(lang, 'no_multiple_ways'),
|
|
@@ -1784,12 +2444,25 @@ def audit_site(url, max_pages=5, timeout=30, lang='en', from_sitemap=True,
|
|
|
1784
2444
|
deadline = (time.monotonic() + budget) if budget else None
|
|
1785
2445
|
try:
|
|
1786
2446
|
html_text = _fetch(url, timeout=timeout)
|
|
2447
|
+
except _FetchError as e:
|
|
2448
|
+
return {'error': _t(lang, e.key).format(**e.fmt)}
|
|
1787
2449
|
except ValueError as e:
|
|
1788
2450
|
return {'error': str(e)}
|
|
1789
2451
|
except Exception as e: # noqa: BLE001
|
|
1790
2452
|
return {'error': _t(lang, 'fetch_error').format(e=e)}
|
|
1791
|
-
|
|
1792
|
-
|
|
2453
|
+
# el parser jamás tira el crawl entero: una página hostil → informe de
|
|
2454
|
+
# error de ESA página y se sigue con la cola
|
|
2455
|
+
def _parse_page(html_txt, page_url):
|
|
2456
|
+
pg = _Auditor()
|
|
2457
|
+
try:
|
|
2458
|
+
pg.feed(html_txt[:MAX_HTML])
|
|
2459
|
+
pg.close()
|
|
2460
|
+
except Exception as e: # noqa: BLE001
|
|
2461
|
+
return pg, {'url': page_url, 'error': _t(lang, 'err_unparseable').format(e=str(e)[:120])}
|
|
2462
|
+
return pg, None
|
|
2463
|
+
p0, p0_err = _parse_page(html_text, url)
|
|
2464
|
+
if p0_err:
|
|
2465
|
+
return p0_err
|
|
1793
2466
|
reports = [audit_html(html_text, url, lang=lang)]
|
|
1794
2467
|
parsers = [p0]
|
|
1795
2468
|
seen = {url.split('#')[0].rstrip('/')}
|
|
@@ -1807,9 +2480,10 @@ def audit_site(url, max_pages=5, timeout=30, lang='en', from_sitemap=True,
|
|
|
1807
2480
|
html_pg = _fetch(next, timeout=timeout)
|
|
1808
2481
|
except Exception: # noqa: BLE001
|
|
1809
2482
|
continue
|
|
2483
|
+
pg, pg_err = _parse_page(html_pg, next)
|
|
2484
|
+
if pg_err is not None:
|
|
2485
|
+
continue # página rota: no cuenta, el crawl sigue
|
|
1810
2486
|
reports.append(audit_html(html_pg, next, lang=lang))
|
|
1811
|
-
pg = _Auditor()
|
|
1812
|
-
pg.feed(html_pg[:MAX_HTML]); pg.close()
|
|
1813
2487
|
parsers.append(pg)
|
|
1814
2488
|
if len(reports) < max_pages and not from_sitemap:
|
|
1815
2489
|
for new in _internal_links(html_pg, next, url):
|
|
@@ -1820,6 +2494,9 @@ def audit_site(url, max_pages=5, timeout=30, lang='en', from_sitemap=True,
|
|
|
1820
2494
|
for inf in reports[:1]:
|
|
1821
2495
|
inf.setdefault('findings', []).append(h)
|
|
1822
2496
|
inf['score'] = compute_score(inf['findings'])
|
|
2497
|
+
# el summary también: un score recalculado con summary viejo miente
|
|
2498
|
+
inf['summary'] = {s: sum(1 for f2 in inf['findings'] if f2['severity'] == s)
|
|
2499
|
+
for s in ('high', 'medium', 'low')}
|
|
1823
2500
|
scores = [pg['score'] for pg in reports if 'score' in pg]
|
|
1824
2501
|
findings_by_signal = {}
|
|
1825
2502
|
for pg in reports:
|
|
@@ -1910,6 +2587,33 @@ def audit_changed(base='HEAD', lang='en', cwd='.'):
|
|
|
1910
2587
|
}
|
|
1911
2588
|
|
|
1912
2589
|
|
|
2590
|
+
def _apply_standard(res, standard, target, lang):
|
|
2591
|
+
""" Enriquecimiento post-hoc EN 301 549 / RGAA (site crawl, --changed):
|
|
2592
|
+
añade bloque standard y cláusula/issue RGAA por hallazgo. standard=None →
|
|
2593
|
+
res intacto. Antes solo EN: con --standard rgaa y --pages>1 (o --changed)
|
|
2594
|
+
el estándar se descartaba EN SILENCIO."""
|
|
2595
|
+
if not isinstance(res, dict) or 'error' in res:
|
|
2596
|
+
return res
|
|
2597
|
+
if standard == 'en301549':
|
|
2598
|
+
from . import a11yen301549 as _enstd
|
|
2599
|
+
_tgt = target or _enstd.target_for_mode(res.get('mode', 'static'))
|
|
2600
|
+
res['standard'] = _enstd.standard_block(_tgt, lang)
|
|
2601
|
+
for _pg in res.get('reports', [res]):
|
|
2602
|
+
for h in _pg.get('findings', []):
|
|
2603
|
+
_cl = _enstd.clause_for(h.get('criterion'), _tgt)
|
|
2604
|
+
if _cl:
|
|
2605
|
+
h['clause'] = _cl
|
|
2606
|
+
elif standard == 'rgaa':
|
|
2607
|
+
from . import a11yrgaa as _rg
|
|
2608
|
+
res['standard'] = _rg.standard_block(lang)
|
|
2609
|
+
for _pg in res.get('reports', [res]):
|
|
2610
|
+
for h in _pg.get('findings', []):
|
|
2611
|
+
_rgaa = _rg.rgaa_for_sc((h.get('criterion') or '').split(' ')[0])
|
|
2612
|
+
if _rgaa:
|
|
2613
|
+
h['rgaa'] = _rgaa
|
|
2614
|
+
return res
|
|
2615
|
+
|
|
2616
|
+
|
|
1913
2617
|
def main(argv):
|
|
1914
2618
|
ap = argparse.ArgumentParser(description=__doc__)
|
|
1915
2619
|
g = ap.add_mutually_exclusive_group(required=True)
|
|
@@ -1924,25 +2628,38 @@ def main(argv):
|
|
|
1924
2628
|
help='crawl ligero mismo dominio (1 = solo la página)')
|
|
1925
2629
|
ap.add_argument('--no-sitemap', action='store_true',
|
|
1926
2630
|
help='descubre por enlaces, sin leer el sitemap')
|
|
2631
|
+
ap.add_argument('--standard', choices=['en301549', 'rgaa'], default=None,
|
|
2632
|
+
help='añade a cada hallazgo su cláusula EN 301 549 V4.1.1 '
|
|
2633
|
+
'(9.x web por defecto)')
|
|
2634
|
+
ap.add_argument('--target', choices=['web', 'documents', 'software'],
|
|
2635
|
+
default=None, help='target EN: web=9.x, documents=10.x, '
|
|
2636
|
+
'software=11.x (default: según el modo)')
|
|
1927
2637
|
a = ap.parse_args(argv)
|
|
1928
2638
|
if a.changed:
|
|
1929
2639
|
res = audit_changed(base=a.base, lang=a.lang)
|
|
1930
2640
|
if 'error' in res:
|
|
1931
2641
|
print(json.dumps(res))
|
|
1932
2642
|
return 1
|
|
2643
|
+
res = _apply_standard(res, a.standard, a.target, a.lang)
|
|
1933
2644
|
print(json.dumps(res, ensure_ascii=False, indent=1))
|
|
1934
2645
|
return 2 if res.get('blocking') else 0
|
|
1935
2646
|
if a.url:
|
|
1936
2647
|
try:
|
|
1937
2648
|
res = (audit_site(a.url, max_pages=a.pages, lang=a.lang,
|
|
1938
2649
|
from_sitemap=not a.no_sitemap)
|
|
1939
|
-
if a.pages > 1 else audit_url(a.url, lang=a.lang
|
|
2650
|
+
if a.pages > 1 else audit_url(a.url, lang=a.lang,
|
|
2651
|
+
standard=a.standard,
|
|
2652
|
+
target=a.target))
|
|
1940
2653
|
except Exception as e: # noqa: BLE001
|
|
1941
|
-
print(json.dumps({'error':
|
|
2654
|
+
print(json.dumps({'error': _t(a.lang, 'fetch_error').format(e=e)}))
|
|
1942
2655
|
return 1
|
|
1943
2656
|
else:
|
|
1944
2657
|
with open(a.file, encoding='utf-8', errors='replace') as f:
|
|
1945
|
-
res = audit_html(f.read(), a.file, lang=a.lang
|
|
2658
|
+
res = audit_html(f.read(), a.file, lang=a.lang,
|
|
2659
|
+
standard=a.standard, target=a.target)
|
|
2660
|
+
# site/changed no pasan por audit_html: enriquecer post-hoc para que
|
|
2661
|
+
# --standard nunca se descarte en silencio en NINGUNA ruta del CLI
|
|
2662
|
+
res = _apply_standard(res, a.standard, a.target, a.lang)
|
|
1946
2663
|
print(json.dumps(res, ensure_ascii=False, indent=1))
|
|
1947
2664
|
return 0
|
|
1948
2665
|
|