@kinti/a11y-toolkit 5.26.0 → 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 +27 -4
- package/a11y_toolkit/a11yact.py +9 -1
- package/a11y_toolkit/a11yannotate.py +185 -0
- package/a11y_toolkit/a11yaudit.py +853 -193
- 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 +425 -95
- package/a11y_toolkit/a11yen301549.py +53 -1
- package/a11y_toolkit/a11yengines.py +157 -0
- package/a11y_toolkit/a11yevidence.py +81 -33
- package/a11y_toolkit/a11yfix.py +131 -52
- package/a11y_toolkit/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 +10 -3
- package/a11y_toolkit/a11ypatches.py +154 -0
- package/a11y_toolkit/a11ypatterns.py +344 -0
- package/a11y_toolkit/a11ypdf.py +109 -53
- package/a11y_toolkit/a11yrgaa.py +60 -0
- package/a11y_toolkit/a11yroute.py +34 -12
- package/a11y_toolkit/a11ysarif.py +45 -18
- package/a11y_toolkit/a11yscope.py +67 -15
- package/a11y_toolkit/a11yscroll.py +7 -5
- package/a11y_toolkit/a11ystatement.py +30 -6
- package/a11y_toolkit/a11ytrace.py +293 -0
- package/a11y_toolkit/a11yvalidate.py +21 -15
- package/a11y_toolkit/a11yvpat.py +34 -7
- package/a11y_toolkit/a11yvtt.py +22 -6
- package/a11y_toolkit/a11ywiz.py +121 -0
- package/a11y_toolkit/contrast.py +62 -24
- package/a11y_toolkit/locales/en.json +177 -20
- package/a11y_toolkit/locales/es.json +178 -21
- package/a11y_toolkit/rgaa.json +2661 -0
- package/a11y_toolkit/server.py +149 -50
- 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
|
|
@@ -296,10 +332,26 @@ class _Auditor(HTMLParser):
|
|
|
296
332
|
'form', 'input', 'select', 'textarea', 'table')
|
|
297
333
|
|
|
298
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
|
|
299
342
|
super().__init__(convert_charrefs=True)
|
|
300
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 = []
|
|
301
352
|
self.controls_by_kind = {} # tag → lista de atributos de controles sin nombre
|
|
302
353
|
self.fields_no_label = []
|
|
354
|
+
self.fields_no_label_elems = []
|
|
303
355
|
self.iframes_no_title = []
|
|
304
356
|
self.lang = None
|
|
305
357
|
self.lang_region_invalid = None
|
|
@@ -312,9 +364,12 @@ class _Auditor(HTMLParser):
|
|
|
312
364
|
self._heading_level = None
|
|
313
365
|
self._heading_text = []
|
|
314
366
|
self._visible_text = []
|
|
315
|
-
self._heading_text = []
|
|
316
367
|
self.positive_tabindices = []
|
|
368
|
+
self.positive_tabindex_elems = []
|
|
369
|
+
self.blank_no_warning_elems = [] # anchors _blank sin aviso (paths)
|
|
317
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)
|
|
318
373
|
self.elements = 0
|
|
319
374
|
# Pila de controles interactivos (a/button/summary) para recoger su
|
|
320
375
|
# texto interno, que es la fuente más habitual de nombre accesible.
|
|
@@ -325,16 +380,27 @@ class _Auditor(HTMLParser):
|
|
|
325
380
|
self.orphan_labels = 0
|
|
326
381
|
# Nuevas señales
|
|
327
382
|
self.aria_hidden_focusable = [] # tag de interactivos con aria-hidden
|
|
383
|
+
self.aria_hidden_focusable_elems = []
|
|
328
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 = []
|
|
329
390
|
self.meta_refresh = None
|
|
330
391
|
self.meta_refreshes = [] # todos los meta refresh: gana el 1º parseable (spec HTML)
|
|
331
392
|
self.saw_html = False
|
|
332
393
|
self.saw_body = False
|
|
333
394
|
self.root_tag = None
|
|
334
|
-
self._in_head = False
|
|
335
395
|
self._in_template = 0
|
|
336
396
|
self._title_buf = []
|
|
337
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>
|
|
338
404
|
# accname (ola de precisión ACT): visibilidad HEREDADA (aria-hidden con
|
|
339
405
|
# re-activación por false, attr hidden, display:none/visibility:hidden)
|
|
340
406
|
# y registro id→texto para resolver aria-labelledby a un salto — los ids
|
|
@@ -352,6 +418,8 @@ class _Auditor(HTMLParser):
|
|
|
352
418
|
self._styles_text = '' # contenido de <style>: clases ocultas y fuentes-icono
|
|
353
419
|
self._styles_cached_src = None
|
|
354
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)
|
|
355
423
|
self._icon_links = []
|
|
356
424
|
self._ahf_deferred = [] # (tag, id) off-screen: decidir post-parse con los scripts completos
|
|
357
425
|
self._el_stack = [] # (tag, attrs, [texto directo]) — texto propio del elemento
|
|
@@ -371,10 +439,16 @@ class _Auditor(HTMLParser):
|
|
|
371
439
|
self.videos = 0
|
|
372
440
|
self.videos_with_captions = 0
|
|
373
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 = []
|
|
374
446
|
self.tables = 0
|
|
375
447
|
self.tables_with_th = 0
|
|
376
448
|
self._in_table = False
|
|
377
449
|
self._th_in_table = False
|
|
450
|
+
self._table_stack = [] # (th_había, attrs) por <table> abierta
|
|
451
|
+
self.tables_no_th_elems = []
|
|
378
452
|
self.blank_no_warning = 0
|
|
379
453
|
self.blank_total = 0
|
|
380
454
|
self.hay_main = False
|
|
@@ -383,6 +457,8 @@ class _Auditor(HTMLParser):
|
|
|
383
457
|
self.empty_h = 0
|
|
384
458
|
self.ids = {}
|
|
385
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
|
|
386
462
|
# v3.1: validez ARIA, autocomplete, enlaces, landmarks, accesskey, autoplay
|
|
387
463
|
self.aria_refs = [] # (attr, id) referenciados por aria-labelledby/describedby
|
|
388
464
|
self.aria_values = [] # valores aria-* inválidos
|
|
@@ -395,6 +471,8 @@ class _Auditor(HTMLParser):
|
|
|
395
471
|
self.links = {} # nombre normalizado → set de hrefs
|
|
396
472
|
self.generics = 0
|
|
397
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)
|
|
398
476
|
self.media_autoplay = 0
|
|
399
477
|
self._list_depth = 0
|
|
400
478
|
self._li_depth = 0
|
|
@@ -402,8 +480,12 @@ class _Auditor(HTMLParser):
|
|
|
402
480
|
self.label_no_name = [] # (texto visible, aria-label) 2.5.3
|
|
403
481
|
self.lang_parts_invalid = [] # lang inválidos en elementos no-html
|
|
404
482
|
self.down_events = [] # onmousedown/ontouchstart/onpointerdown
|
|
405
|
-
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
|
|
406
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
|
|
407
489
|
self.nav_hrefs = set() # hrefs inside <nav> (site-level 3.2.3 signature)
|
|
408
490
|
self.help_hrefs = set() # help/contact links (site-level 3.2.6 signature)
|
|
409
491
|
self.images_of_text = []
|
|
@@ -417,12 +499,14 @@ class _Auditor(HTMLParser):
|
|
|
417
499
|
self.missing_fieldsets = 0 # 1.3.1: radio/check groups sin fieldset
|
|
418
500
|
self._radio_group = {}
|
|
419
501
|
self._radio_in_fieldset = {} # name → count (para detectar grupos)
|
|
502
|
+
self._radio_in_group = {} # name → dentro de role=group con nombre
|
|
420
503
|
self.vague_labels = [] # 2.4.6: label quality
|
|
421
504
|
self.financial_no_confirm = 0 # 3.3.4: financial form no confirm
|
|
422
505
|
self._financial_form = False
|
|
423
|
-
self._confirm_form = False #
|
|
506
|
+
self._confirm_form = False # 3.3.4: pista de confirmación en form financiero
|
|
424
507
|
self._in_nav = 0
|
|
425
508
|
self._in_fieldset = False
|
|
509
|
+
self._group_role_depth = 0 # <div role=group/radiogroup> abierto (con nombre)
|
|
426
510
|
self.has_search = False
|
|
427
511
|
self.has_sitemap = False
|
|
428
512
|
self.gestures = [] # touchmove/drag handlers (2.5.1)
|
|
@@ -431,7 +515,6 @@ class _Auditor(HTMLParser):
|
|
|
431
515
|
self.orientation_locks = [] # screen.orientation.lock / orientation MQ (1.3.4)
|
|
432
516
|
self.videos_descriptions = 0 # videos WITH descriptions track
|
|
433
517
|
self.sensory = [] # sensory-only instruction patterns (1.3.3)
|
|
434
|
-
self._skip_labels_pend = [] # labels declarados antes que su campo
|
|
435
518
|
|
|
436
519
|
def _close_control(self, tag):
|
|
437
520
|
if not self._ctrl:
|
|
@@ -464,7 +547,10 @@ class _Auditor(HTMLParser):
|
|
|
464
547
|
self._styles_text, re.I)) or bool(re.search(
|
|
465
548
|
r'fonts\.googleapis\.com/icon|/material-icons|font-?awesome|/icomoon',
|
|
466
549
|
' '.join(getattr(self, '_icon_links', [])), re.I))
|
|
467
|
-
|
|
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:
|
|
468
554
|
def _lin_words(txt):
|
|
469
555
|
txt = re.sub(r'\([^)]*\)', ' ', txt)
|
|
470
556
|
# la puntuación se ELIMINA sin partir palabras («11×3=33» →
|
|
@@ -484,14 +570,23 @@ class _Auditor(HTMLParser):
|
|
|
484
570
|
for i in range(len(_ap2) - len(_vp) + 1))
|
|
485
571
|
if _mismatch:
|
|
486
572
|
self.label_no_name.append((_vis[:40], _al[:60]))
|
|
487
|
-
if tag == 'a':
|
|
573
|
+
if tag == 'a' and not c.get('hidden'):
|
|
488
574
|
if (a.get('target') or '').lower() == '_blank':
|
|
489
575
|
self.blank_total += 1
|
|
576
|
+
_img_alts = ' '.join((ia.get('alt') or '')
|
|
577
|
+
for ia in c.get('img_attrs', []))
|
|
490
578
|
if not _BLANK_HINT.search(text) and not _BLANK_HINT.search(a.get('aria-label') or '') \
|
|
491
|
-
and not _BLANK_HINT.search(a.get('title') or '')
|
|
579
|
+
and not _BLANK_HINT.search(a.get('title') or '') \
|
|
580
|
+
and not _BLANK_HINT.search(_img_alts):
|
|
492
581
|
self.blank_no_warning += 1
|
|
493
|
-
|
|
494
|
-
|
|
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
|
|
495
590
|
name = (text or a.get('aria-label') or a.get('title') or '').strip()
|
|
496
591
|
href = (a.get('href') or '').strip()
|
|
497
592
|
if name and href:
|
|
@@ -505,9 +600,55 @@ class _Auditor(HTMLParser):
|
|
|
505
600
|
if self._labels_stack:
|
|
506
601
|
self._labels_stack[-1] = True
|
|
507
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
|
+
|
|
508
613
|
def handle_starttag(self, tag, attrs):
|
|
509
|
-
|
|
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
|
|
510
621
|
self.elements += 1
|
|
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, {}))
|
|
511
652
|
# rasgos estructurales para el scope de aplicabilidad (a11yscope):
|
|
512
653
|
# evidencia POSITIVA — cero <video> habilita proponer 1.2.x como no
|
|
513
654
|
# aplicable; la ausencia de señal jamás cuenta como ausencia de
|
|
@@ -517,7 +658,8 @@ class _Auditor(HTMLParser):
|
|
|
517
658
|
pass
|
|
518
659
|
else:
|
|
519
660
|
self.features[tag] = self.features.get(tag, 0) + 1
|
|
520
|
-
if a.get('id'):
|
|
661
|
+
if a.get('id') and not self._in_template:
|
|
662
|
+
# ids dentro de <template> no existen: ni dup_ids ni refs rotas
|
|
521
663
|
self.ids[a['id']] = self.ids.get(a['id'], 0) + 1
|
|
522
664
|
if self.root_tag is None:
|
|
523
665
|
self.root_tag = tag
|
|
@@ -534,6 +676,11 @@ class _Auditor(HTMLParser):
|
|
|
534
676
|
_hidden_aria = False
|
|
535
677
|
_hidden = _inh or 'hidden' in a or 'display:none' in _style \
|
|
536
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
|
|
537
684
|
if tag not in _VOID:
|
|
538
685
|
self._depth += 1
|
|
539
686
|
self._hidden_stack.append((_hidden, _hidden_aria))
|
|
@@ -550,10 +697,34 @@ class _Auditor(HTMLParser):
|
|
|
550
697
|
self._nav_ids.add(a['id'])
|
|
551
698
|
if a.get('onclick'):
|
|
552
699
|
self._toggle_onclicks.append(a['onclick'])
|
|
553
|
-
if tag == '
|
|
554
|
-
self._in_head = True
|
|
555
|
-
elif tag == 'template':
|
|
700
|
+
if tag == 'template':
|
|
556
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)
|
|
557
728
|
elif tag == 'html':
|
|
558
729
|
self.saw_html = True
|
|
559
730
|
self.lang = (a.get('lang') or '').strip()
|
|
@@ -563,11 +734,15 @@ class _Auditor(HTMLParser):
|
|
|
563
734
|
self.lang_region_invalid = self.lang
|
|
564
735
|
elif tag == 'body':
|
|
565
736
|
self.saw_body = True
|
|
566
|
-
elif tag == 'title' and not self._in_template:
|
|
737
|
+
elif tag == 'title' and not self._in_template and self._svg_depth == 0:
|
|
567
738
|
# TODOS los <title> se acumulan en orden de documento: decide el
|
|
568
739
|
# PRIMERO (modelo de ACT 2779a5: head vacío + body con texto falla;
|
|
569
|
-
# 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.
|
|
570
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 = []
|
|
571
746
|
elif tag == 'script':
|
|
572
747
|
self._in_script = True
|
|
573
748
|
if a.get('src'):
|
|
@@ -577,12 +752,18 @@ class _Auditor(HTMLParser):
|
|
|
577
752
|
elif tag == 'link':
|
|
578
753
|
if (a.get('rel') or '').lower() == 'stylesheet' and a.get('href'):
|
|
579
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
|
|
580
758
|
elif tag == 'meta':
|
|
581
|
-
if a.get('name'
|
|
582
|
-
|
|
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
|
|
583
763
|
elif (a.get('http-equiv') or '').lower() == 'refresh':
|
|
584
|
-
self.meta_refresh = a.get('content'
|
|
585
|
-
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)
|
|
586
767
|
elif tag == 'img':
|
|
587
768
|
# la decisión de nombre es POST-parse (nombre accesible = alt u
|
|
588
769
|
# otras fuentes; presentación/none y hiddens quedan fuera)
|
|
@@ -592,6 +773,10 @@ class _Auditor(HTMLParser):
|
|
|
592
773
|
# la imagen interna aporta SU nombre completo al control
|
|
593
774
|
# (alt, aria-label, title, labelledby — resuelto post-parse)
|
|
594
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)
|
|
595
780
|
if alt and not _hidden:
|
|
596
781
|
# el alt SE LEE: cuenta como texto bajo el lang de su
|
|
597
782
|
# contexto (de46e4 — una img con alt es contenido textual)
|
|
@@ -599,13 +784,16 @@ class _Auditor(HTMLParser):
|
|
|
599
784
|
if self._heading_level is not None and not _hidden \
|
|
600
785
|
and (a.get('role') or '').strip().lower() not in ('presentation', 'none'):
|
|
601
786
|
# nombre de la imagen (alt u otras fuentes) alimenta al
|
|
602
|
-
# 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
|
|
603
792
|
_nom_img = alt or (a.get('aria-label') or '').strip() \
|
|
604
793
|
or (a.get('title') or '').strip()
|
|
605
794
|
if _nom_img:
|
|
606
795
|
self._heading_text.append(_nom_img)
|
|
607
|
-
|
|
608
|
-
elif len(alt) > 120:
|
|
796
|
+
if len(alt) > 120:
|
|
609
797
|
self.images_of_text.append(f'alt de {len(alt)} caracteres')
|
|
610
798
|
elif tag == 'iframe':
|
|
611
799
|
self.iframes_all.append((a, _hidden))
|
|
@@ -630,6 +818,8 @@ class _Auditor(HTMLParser):
|
|
|
630
818
|
elif tag == 'input':
|
|
631
819
|
self._field_note()
|
|
632
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
|
|
633
823
|
if kind == 'image':
|
|
634
824
|
self.inputs_image.append((a, _hidden))
|
|
635
825
|
elif kind in ('submit', 'button', 'reset'):
|
|
@@ -639,18 +829,19 @@ class _Auditor(HTMLParser):
|
|
|
639
829
|
if kind == 'search' or re.search(r'search|busqueda|b[uú]squeda', (a.get('name') or '') + (a.get('id') or ''), re.I):
|
|
640
830
|
self.has_search = True
|
|
641
831
|
if kind in _FIELDS:
|
|
642
|
-
self.fields_raw.append((tag, kind, a, self.
|
|
832
|
+
self.fields_raw.append((tag, kind, a, self._wrap_labels(a), _hidden))
|
|
643
833
|
if 'autocomplete' not in a and kind != 'search' and (
|
|
644
834
|
kind in ('email', 'tel')
|
|
645
835
|
or _PERSONAL_DATA.search((a.get('name') or '') + ' ' + (a.get('id') or ''))):
|
|
646
836
|
self.missing_autocomplete.append(f'input type={kind} name={a.get("name") or "?"}'[:44])
|
|
837
|
+
self.autocomplete_elems.append(a)
|
|
647
838
|
if tag == 'input' and 'autocomplete' in a and 'disabled' not in a \
|
|
648
839
|
and (a.get('aria-disabled') or '').strip().lower() != 'true' and not _hidden:
|
|
649
840
|
# ABNF exacta de la regla ACT 73f2c2 (HTML autofill): [section-*]?
|
|
650
841
|
# [shipping|billing]? [home|work|mobile|fax|pager — solo si el
|
|
651
842
|
# siguiente es email/impp/tel/tel-*]? campo [webauthn]? — los
|
|
652
843
|
# campos disabled u hiddens quedan fuera (aplicabilidad)
|
|
653
|
-
_toks = (a['autocomplete'] or '').split()
|
|
844
|
+
_toks = [t.lower() for t in (a['autocomplete'] or '').split()]
|
|
654
845
|
_mal = None
|
|
655
846
|
if not (_toks == ['on'] or _toks == ['off']):
|
|
656
847
|
_i = 0
|
|
@@ -676,11 +867,12 @@ class _Auditor(HTMLParser):
|
|
|
676
867
|
f'{_mal} (input name={a.get("name") or "?"})'[:60])
|
|
677
868
|
elif tag in ('select', 'textarea'):
|
|
678
869
|
self._field_note()
|
|
679
|
-
self.fields_raw.append((tag, tag, a, self.
|
|
870
|
+
self.fields_raw.append((tag, tag, a, self._wrap_labels(a), _hidden))
|
|
680
871
|
elif tag == 'label':
|
|
681
872
|
self._label_depth += 1
|
|
682
873
|
self._label_text_current = []
|
|
683
874
|
self._labels_stack.append(False)
|
|
875
|
+
self._label_for_stack.append(a.get('for') or None)
|
|
684
876
|
if a.get('for'):
|
|
685
877
|
self._labels_for[a['for']] = self._labels_for.get(a['for'], 0) + 1
|
|
686
878
|
if self._labels_for[a['for']] > 1:
|
|
@@ -691,32 +883,77 @@ class _Auditor(HTMLParser):
|
|
|
691
883
|
elif tag == 'blink':
|
|
692
884
|
self.mobiles.append('<blink>')
|
|
693
885
|
elif tag == 'track':
|
|
694
|
-
kind
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
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
|
|
699
896
|
elif tag in ('video', 'audio'):
|
|
700
|
-
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
|
|
701
900
|
self.videos += 1
|
|
702
901
|
self._in_video = True
|
|
703
|
-
|
|
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:
|
|
704
908
|
self.media_autoplay += 1
|
|
909
|
+
self.media_autoplay_elems.append(a)
|
|
705
910
|
elif tag in ('ul', 'ol'):
|
|
706
911
|
self._list_depth += 1
|
|
707
912
|
elif tag == 'li':
|
|
708
913
|
self._li_depth += 1
|
|
709
914
|
elif tag == 'table':
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
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
|
|
713
939
|
elif tag == 'th':
|
|
714
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
|
|
715
945
|
elif tag == 'main' or (a.get('role') or '').lower() == 'main':
|
|
716
946
|
self.hay_main = True
|
|
947
|
+
if a.get('id'):
|
|
948
|
+
self._landmark_ids.add(a['id'])
|
|
717
949
|
elif tag not in _CONTROLS + ('input', 'select', 'textarea', 'label', 'option',
|
|
718
950
|
'video', 'audio', 'details', 'summary'):
|
|
719
|
-
_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
|
|
720
957
|
if _role_v in _ROLE_FIELDS and _role_v not in ('none', 'presentation'):
|
|
721
958
|
if a.get('id'):
|
|
722
959
|
self._role_field_ids.add(a['id'])
|
|
@@ -733,16 +970,35 @@ class _Auditor(HTMLParser):
|
|
|
733
970
|
'inner_img': False,
|
|
734
971
|
'img_attrs': [], 'hidden': _hidden, 'depth': self._depth,
|
|
735
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)
|
|
736
980
|
elif _role_v == 'img' and tag != 'img':
|
|
737
981
|
# div[role=img] con imagen de fondo: también necesita nombre (23a2a8)
|
|
738
982
|
self.imgs_all.append((a, _hidden))
|
|
739
|
-
if a.get('onclick') and not
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
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
|
|
746
1002
|
# v3.12: 2.2.2 inline looping animation
|
|
747
1003
|
style = a.get('style') or ''
|
|
748
1004
|
if 'animation' in style and 'infinite' in style:
|
|
@@ -755,25 +1011,28 @@ class _Auditor(HTMLParser):
|
|
|
755
1011
|
if tag == 'form':
|
|
756
1012
|
self._financial_form = False
|
|
757
1013
|
self._confirm_form = False
|
|
758
|
-
|
|
1014
|
+
self._form_captchas = []
|
|
1015
|
+
action = (a.get('action') or '').lower() + (a.get('id') or '').lower()
|
|
759
1016
|
if re.search(r'pay|purchase|checkout|buy|order|contract|legal|billing',
|
|
760
1017
|
action, re.I):
|
|
761
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
|
|
762
1022
|
if tag in ('input', 'textarea') and a.get('placeholder') \
|
|
763
1023
|
and not (a.get('aria-label') or a.get('aria-labelledby')):
|
|
764
1024
|
# candidato a placeholder-only: se confirma POST-parse (un
|
|
765
1025
|
# <label for> con su id le da nombre real y lo retira)
|
|
766
|
-
self._placeholder_candidates.append((tag, a, self.
|
|
1026
|
+
self._placeholder_candidates.append((tag, a, self._wrap_labels(a), _hidden))
|
|
767
1027
|
if a.get('required') is not None or 'required' in a or a.get('aria-required') == 'true':
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
self.required_no_indication.append(
|
|
772
|
-
f'{tag}[name={a.get("name","?")}]')
|
|
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))
|
|
773
1031
|
if tag == 'input' and a.get('type') == 'radio':
|
|
774
1032
|
nm = a.get('name') or '(no name)'
|
|
775
1033
|
self._radio_group[nm] = self._radio_group.get(nm, 0) + 1
|
|
776
1034
|
self._radio_in_fieldset[nm] = self._in_fieldset
|
|
1035
|
+
self._radio_in_group[nm] = self._group_role_depth > 0
|
|
777
1036
|
if tag == 'fieldset':
|
|
778
1037
|
self._in_fieldset = True
|
|
779
1038
|
if tag in ('button', 'input'):
|
|
@@ -783,15 +1042,18 @@ class _Auditor(HTMLParser):
|
|
|
783
1042
|
# checkbox de términos
|
|
784
1043
|
if tag == 'input' and a.get('type') == 'checkbox':
|
|
785
1044
|
nm = (a.get('name') or '').lower()
|
|
786
|
-
|
|
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):
|
|
787
1050
|
self._confirm_form = True
|
|
788
1051
|
if a.get('draggable') and (a.get('draggable') or '').lower() != 'false':
|
|
789
1052
|
if not a.get('onclick') and tag not in ('input', 'button'):
|
|
790
1053
|
self.drag_handlers.append(f'{tag}[draggable]')
|
|
791
1054
|
if a.get('aria-live') or (a.get('role') or '').lower() in ('status', 'alert', 'log'):
|
|
792
|
-
self.
|
|
793
|
-
|
|
794
|
-
self.char_shortcuts.append(f'{tag}[accesskey]')
|
|
1055
|
+
if not self._in_template:
|
|
1056
|
+
self.status_regions += 1
|
|
795
1057
|
# v3.12: 2.5.4 motion actuation handlers
|
|
796
1058
|
for _ma in ('ondeviceorientation', 'ondevicemotion'):
|
|
797
1059
|
if a.get(_ma):
|
|
@@ -800,19 +1062,22 @@ class _Auditor(HTMLParser):
|
|
|
800
1062
|
if tag == 'meta' and 'orientation' in (a.get('content') or '').lower() \
|
|
801
1063
|
and 'lock' in (a.get('content') or '').lower():
|
|
802
1064
|
self.orientation_locks.append('meta orientation lock')
|
|
803
|
-
# v3.9: 3.3.8 captcha
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
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 ():
|
|
812
1077
|
if a.get(_ar):
|
|
813
1078
|
for _ref in a[_ar].split():
|
|
814
1079
|
self.aria_refs.append((_ar, _ref))
|
|
815
|
-
for _ar, _val in a.items():
|
|
1080
|
+
for _ar, _val in a.items() if not self._in_template else ():
|
|
816
1081
|
if not _ar.startswith('aria-'):
|
|
817
1082
|
continue
|
|
818
1083
|
_val = (_val or '').strip().lower()
|
|
@@ -822,7 +1087,11 @@ class _Auditor(HTMLParser):
|
|
|
822
1087
|
and not (_val == 'mixed' and _ar in ('aria-pressed', 'aria-checked')) \
|
|
823
1088
|
and not (_val == 'undefined' and _ar in _ARIA_BOOL_UNDEFINED):
|
|
824
1089
|
self.aria_values.append({'attr': _ar, 'val': _val, 'type': 'bool'})
|
|
825
|
-
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
|
|
826
1095
|
self.aria_values.append({'attr': _ar, 'val': _val, 'type': 'int'})
|
|
827
1096
|
elif _ar in _ARIA_NUM:
|
|
828
1097
|
try:
|
|
@@ -839,7 +1108,7 @@ class _Auditor(HTMLParser):
|
|
|
839
1108
|
self.aria_values.append({'attr': _ar, 'val': _val,
|
|
840
1109
|
'type': 'tokens',
|
|
841
1110
|
'valid_tokens': '/'.join(sorted(v for v in _ARIA_TOKENS[_ar] if v))})
|
|
842
|
-
if a.get('role'):
|
|
1111
|
+
if a.get('role') and not self._in_template:
|
|
843
1112
|
# role admite LISTA de tokens separados por espacios (con
|
|
844
1113
|
# fallback): TODOS deben ser roles válidos, no solo el primero
|
|
845
1114
|
for role in a['role'].strip().lower().split():
|
|
@@ -851,35 +1120,47 @@ class _Auditor(HTMLParser):
|
|
|
851
1120
|
landmark_role = a.get('role', '').lower() if a.get('role') in (
|
|
852
1121
|
'banner', 'contentinfo', 'navigation', 'complementary', 'main', 'form', 'search', 'region') else None
|
|
853
1122
|
lm = tag if tag in ('header', 'footer', 'nav', 'aside', 'main', 'search') else landmark_role
|
|
854
|
-
if lm and not
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
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
|
|
863
1139
|
if self._list_depth > 0 and self._li_depth == 0 \
|
|
864
1140
|
and tag not in ('li', 'script', 'template', 'ul', 'ol'):
|
|
865
1141
|
self._bad_list += 1
|
|
866
1142
|
# 4.1.2/2.1.2: enfocable dentro de un subárbol aria-hidden=true — el
|
|
867
1143
|
# aria-hidden=false anidado NO exime (ACT 6cfa84). No es enfocable:
|
|
868
|
-
# hidden por CSS/hidden (fuera de la navegación por tab
|
|
869
|
-
#
|
|
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.
|
|
870
1147
|
_ti_raw = (a.get('tabindex') or '').strip()
|
|
871
1148
|
_ti_num = None
|
|
872
|
-
|
|
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 != '':
|
|
873
1154
|
_ti_num = int(_ti_raw)
|
|
874
1155
|
_css_hidden = 'hidden' in a or 'display:none' in _style or 'visibility:hidden' in _style \
|
|
875
|
-
or self._css_hidden_stack[-1]
|
|
1156
|
+
or self._css_hidden_stack[-1] or self._focus_hidden_class()
|
|
876
1157
|
_native = (tag in ('button', 'summary', 'select', 'textarea', 'iframe')
|
|
877
1158
|
or (tag in ('a', 'area') and (a.get('href') or '').strip())
|
|
878
1159
|
or (tag == 'input' and (a.get('type') or 'text').lower() != 'hidden')
|
|
879
1160
|
or (tag in ('video', 'audio') and 'controls' in a))
|
|
880
1161
|
_enfocable = ((_native and 'disabled' not in a)
|
|
881
1162
|
or (_ti_num is not None and _ti_num >= 0))
|
|
882
|
-
if _ti_num
|
|
1163
|
+
if (_ti_num is not None and _ti_num < 0) or _css_hidden:
|
|
883
1164
|
_enfocable = False
|
|
884
1165
|
# centinela de foco off-screen (patrón modal): un link fuera de vista
|
|
885
1166
|
# cuyo id aparece en los scripts (el wiring de focus) NO cuenta — la
|
|
@@ -887,59 +1168,136 @@ class _Auditor(HTMLParser):
|
|
|
887
1168
|
# llegar DESPUÉS del link: la decisión se difiere a post-parse
|
|
888
1169
|
if (_hidden_aria or self._ah_true_depth > 0) and _enfocable:
|
|
889
1170
|
if re.search(r'(top|left)\s*:\s*-\d{3,}', a.get('style') or '', re.I):
|
|
890
|
-
self._ahf_deferred.append((tag, a.get('id')))
|
|
1171
|
+
self._ahf_deferred.append((tag, a, a.get('id')))
|
|
891
1172
|
else:
|
|
892
1173
|
self.aria_hidden_focusable.append(tag)
|
|
1174
|
+
self.aria_hidden_focusable_elems.append(a)
|
|
893
1175
|
if tag == 'area' and (a.get('href') or '').strip():
|
|
894
1176
|
# <area> es void: sin pila de control — se registra directo (el
|
|
895
1177
|
# nombre le llega del alt)
|
|
896
1178
|
self.controls_raw.append(('area', a, '', [], _hidden))
|
|
897
1179
|
if tag in ('h1', 'h2', 'h3', 'h4', 'h5', 'h6'):
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
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
|
|
906
1201
|
self._heading_text = []
|
|
907
1202
|
self._heading_attrs = a
|
|
1203
|
+
self._heading_route = self._elem_paths.get(id(a))
|
|
908
1204
|
self._heading_hidden = _hidden
|
|
909
1205
|
self._heading_tag = tag
|
|
910
1206
|
ti = a.get('tabindex')
|
|
911
|
-
if ti and ti.
|
|
1207
|
+
if ti and ti.isdecimal() and int(ti) > 0 and not self._in_template:
|
|
912
1208
|
self.positive_tabindices.append((tag, int(ti)))
|
|
1209
|
+
self.positive_tabindex_elems.append(a)
|
|
913
1210
|
|
|
914
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
|
|
915
1222
|
if tag not in _VOID:
|
|
916
|
-
|
|
917
|
-
|
|
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
|
|
918
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)))
|
|
919
1248
|
if _eattrs.get('id') and _eattrs['id'] in self._role_field_ids:
|
|
920
1249
|
self._field_buffers[_eattrs['id']] = _ebuf
|
|
921
1250
|
elif (_eattrs.get('role') or '').strip().lower() in _ROLE_FIELDS:
|
|
922
1251
|
self._role_field_text.append((_eattrs, ' '.join(_ebuf).strip()))
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
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():
|
|
928
1266
|
self._ah_true_depth = max(0, self._ah_true_depth - 1)
|
|
1267
|
+
self._depth = max(0, self._depth - _nframes)
|
|
929
1268
|
self._open_ids = [(i, d) for (i, d) in self._open_ids if d <= self._depth]
|
|
930
1269
|
# controles cierran con SU etiqueta Y a SU profundidad — un <div>
|
|
931
1270
|
# anidado dentro de un div[role=button] no cierra el control (React)
|
|
932
1271
|
if self._ctrl and self._ctrl[-1]['tag'] == tag \
|
|
933
1272
|
and self._depth == self._ctrl[-1].get('depth', 0) - 1:
|
|
934
1273
|
self._close_control(tag)
|
|
935
|
-
if tag == '
|
|
936
|
-
self._in_head = False
|
|
937
|
-
elif tag == 'template':
|
|
1274
|
+
if tag == 'template':
|
|
938
1275
|
self._in_template = max(0, self._in_template - 1)
|
|
1276
|
+
if tag == 'svg':
|
|
1277
|
+
self._svg_depth = max(0, self._svg_depth - 1)
|
|
939
1278
|
if tag == 'title':
|
|
940
|
-
self.
|
|
941
|
-
|
|
942
|
-
|
|
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 = []
|
|
943
1301
|
elif tag == 'script':
|
|
944
1302
|
self._in_script = False
|
|
945
1303
|
elif tag == 'style':
|
|
@@ -952,6 +1310,11 @@ class _Auditor(HTMLParser):
|
|
|
952
1310
|
if txt and (len(txt) < 2 or re.fullmatch(
|
|
953
1311
|
r'(campo|field|input|texto|text|dato|value|entrada|box|caja)[\s\d]*', lowered)):
|
|
954
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
|
|
955
1318
|
if self._labels_stack and not self._labels_stack.pop():
|
|
956
1319
|
self.orphan_labels += 1
|
|
957
1320
|
elif tag == 'fieldset':
|
|
@@ -959,6 +1322,13 @@ class _Auditor(HTMLParser):
|
|
|
959
1322
|
elif tag == 'form':
|
|
960
1323
|
if self._financial_form and not self._confirm_form:
|
|
961
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
|
|
962
1332
|
elif tag == 'nav':
|
|
963
1333
|
self._in_nav = max(0, self._in_nav - 1)
|
|
964
1334
|
elif tag == 'li':
|
|
@@ -969,13 +1339,29 @@ class _Auditor(HTMLParser):
|
|
|
969
1339
|
self._close_control(tag)
|
|
970
1340
|
elif tag == 'video':
|
|
971
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)
|
|
972
1348
|
elif tag == 'table':
|
|
973
|
-
if self.
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
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)
|
|
979
1365
|
elif tag == 'th':
|
|
980
1366
|
pass
|
|
981
1367
|
elif self._heading_level and tag == getattr(self, '_heading_tag', None):
|
|
@@ -983,7 +1369,8 @@ class _Auditor(HTMLParser):
|
|
|
983
1369
|
# aria-label tras strip, nombres de imgs internas)
|
|
984
1370
|
self.headings_raw.append((self._heading_level, dict(self._heading_attrs or {}),
|
|
985
1371
|
' '.join(self._heading_text).strip(),
|
|
986
|
-
getattr(self, '_heading_hidden', False)
|
|
1372
|
+
getattr(self, '_heading_hidden', False),
|
|
1373
|
+
getattr(self, '_heading_route', None)))
|
|
987
1374
|
self._heading_level = None
|
|
988
1375
|
|
|
989
1376
|
_RE_CHAR_KEY = re.compile(r'key(?:Code)?\s*===?\s*["\']([a-zA-Z0-9])["\']', re.S)
|
|
@@ -1026,26 +1413,49 @@ class _Auditor(HTMLParser):
|
|
|
1026
1413
|
self.lang_parts_invalid.append(_mark)
|
|
1027
1414
|
return
|
|
1028
1415
|
|
|
1029
|
-
_RE_RULE = re.compile(r'
|
|
1416
|
+
_RE_RULE = re.compile(r'([^{}]+)\{([^}]*)\}')
|
|
1030
1417
|
_RE_HIDDEN_STYLE = re.compile(r'clip-path|display\s*:\s*none|visibility\s*:\s*hidden'
|
|
1031
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')
|
|
1032
1421
|
|
|
1033
1422
|
def _hidden_class_style(self):
|
|
1034
1423
|
"""¿Algún ancestro abierto del control tiene una clase que el
|
|
1035
1424
|
<style> de la página declara como oculta (clip-path, position
|
|
1036
1425
|
absolute + 1px, display none, visibility hidden)? Las reglas se
|
|
1037
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)."""
|
|
1038
1440
|
if self._styles_text is not self._styles_cached_src:
|
|
1039
1441
|
self._styles_cached_src = self._styles_text
|
|
1040
|
-
|
|
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
|
|
1041
1454
|
_open_classes = [c.get('attrs', {}).get('class') for c in self._ctrl]
|
|
1042
|
-
|
|
1043
|
-
_open_classes.append(self._el_stack[-1][1].get('class'))
|
|
1455
|
+
_open_classes += (_fr[1].get('class') for _fr in self._el_stack)
|
|
1044
1456
|
for _cls in filter(None, _open_classes):
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
if _nom == _selector and self._RE_HIDDEN_STYLE.search(_body):
|
|
1048
|
-
return True
|
|
1457
|
+
if _set.intersection(_cls.split()):
|
|
1458
|
+
return True
|
|
1049
1459
|
return False
|
|
1050
1460
|
|
|
1051
1461
|
def handle_data(self, data):
|
|
@@ -1058,10 +1468,14 @@ class _Auditor(HTMLParser):
|
|
|
1058
1468
|
# lista por id + join único post-parse: la concatenación por
|
|
1059
1469
|
# nodo era cuadrática en páginas con wrappers id grandes
|
|
1060
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
|
|
1061
1473
|
if data.strip() and not in_code and not self._in_title:
|
|
1062
1474
|
self._visible_text.append(data) # prosa visible: ni JS, ni CSS, ni título
|
|
1063
1475
|
if self._in_title:
|
|
1064
1476
|
self._title_buf.append(data)
|
|
1477
|
+
elif self._in_svg_title:
|
|
1478
|
+
self._svg_title_buf.append(data)
|
|
1065
1479
|
elif getattr(self, '_in_script', False):
|
|
1066
1480
|
self.handle_script_wait(data)
|
|
1067
1481
|
elif getattr(self, '_in_style', False):
|
|
@@ -1117,11 +1531,13 @@ def normalize_report(report):
|
|
|
1117
1531
|
if not isinstance(report, dict):
|
|
1118
1532
|
return report
|
|
1119
1533
|
findings = report.get('findings')
|
|
1120
|
-
if not findings:
|
|
1534
|
+
if not isinstance(findings, list):
|
|
1535
|
+
if findings:
|
|
1536
|
+
return dict(report, findings=[]) # dict/str/… hostil: sin hallazgos
|
|
1121
1537
|
return report
|
|
1122
1538
|
out = dict(report)
|
|
1123
1539
|
out['findings'] = [dict(h, signal=normalize_signal(h.get('signal', '')))
|
|
1124
|
-
for h in findings]
|
|
1540
|
+
for h in findings if isinstance(h, dict)]
|
|
1125
1541
|
return out
|
|
1126
1542
|
|
|
1127
1543
|
|
|
@@ -1190,12 +1606,25 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1190
1606
|
p.feed(html_text[:MAX_HTML])
|
|
1191
1607
|
p.close()
|
|
1192
1608
|
except Exception as e: # noqa: BLE001
|
|
1193
|
-
|
|
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])}
|
|
1194
1612
|
|
|
1195
|
-
# 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)
|
|
1196
1615
|
for nm, count in p._radio_group.items():
|
|
1197
|
-
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):
|
|
1198
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","?")}]')
|
|
1199
1628
|
|
|
1200
1629
|
# id→texto resuelto de una vez (partes acumuladas en streaming)
|
|
1201
1630
|
for _id, _parts in p._id_text_parts.items():
|
|
@@ -1203,9 +1632,16 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1203
1632
|
|
|
1204
1633
|
# centinela off-screen: decidir con los scripts YA completos (el <script>
|
|
1205
1634
|
# llega después del link en el documento) — sin id o sin wiring = fallo
|
|
1206
|
-
for _tag, _tid in p._ahf_deferred:
|
|
1635
|
+
for _tag, _tattrs, _tid in p._ahf_deferred:
|
|
1207
1636
|
if not _tid or _tid not in p._scripts_text:
|
|
1208
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])
|
|
1209
1645
|
|
|
1210
1646
|
# ── decisiones de nombre POST-parse ─────────────────────────────────────
|
|
1211
1647
|
# Los ids de un aria-labelledby pueden declararse DESPUÉS del elemento que
|
|
@@ -1223,7 +1659,7 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1223
1659
|
# PERO un img presentacional ENFOCABLE (tabindex ≥ 0) sigue necesitando
|
|
1224
1660
|
# nombre: sigue en la navegación por tab (ACT 23a2a8)
|
|
1225
1661
|
_ti = (a.get('tabindex') or '').strip()
|
|
1226
|
-
_enfocable_img = _ti.
|
|
1662
|
+
_enfocable_img = _ti.isdecimal() and int(_ti) >= 0
|
|
1227
1663
|
if hidden or ((a.get('role') or '').strip().lower() in ('presentation', 'none')
|
|
1228
1664
|
and not _enfocable_img):
|
|
1229
1665
|
continue
|
|
@@ -1232,14 +1668,71 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1232
1668
|
if 'alt' in a and (a['alt'] or '') == '':
|
|
1233
1669
|
continue
|
|
1234
1670
|
lb, al, ti = _name_sources(a)
|
|
1235
|
-
|
|
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):
|
|
1236
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
|
|
1237
1718
|
for a, hidden in p.inputs_image:
|
|
1238
1719
|
if hidden:
|
|
1239
1720
|
continue
|
|
1240
1721
|
lb, al, ti = _name_sources(a)
|
|
1241
1722
|
if not ((a.get('alt') or '').strip() or al or lb or ti):
|
|
1242
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)
|
|
1243
1736
|
for a, hidden in p.iframes_all:
|
|
1244
1737
|
# tabindex=-1 saca el iframe del orden de tab: la regla lo excluye;
|
|
1245
1738
|
# role=none/presentation le quita la semántica de iframe (ACT cae760)
|
|
@@ -1249,6 +1742,7 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1249
1742
|
lb, al, ti = _name_sources(a)
|
|
1250
1743
|
if not ((a.get('title') or '').strip() or al or lb):
|
|
1251
1744
|
p.iframes_no_title.append((a.get('src') or '')[:100])
|
|
1745
|
+
p.iframes_no_title_elems.append(a)
|
|
1252
1746
|
for kind, a, text, img_attrs, hidden in p.controls_raw:
|
|
1253
1747
|
# input submit/reset/button llevan valor por defecto del navegador;
|
|
1254
1748
|
# disabled/hidden quedan fuera. El value de un <button> NO es su
|
|
@@ -1258,13 +1752,18 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1258
1752
|
lb, al, ti = _name_sources(a)
|
|
1259
1753
|
_img_names = []
|
|
1260
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
|
|
1261
1760
|
ilb, ial, iti = _name_sources(ia)
|
|
1262
1761
|
_img_names.append((ia.get('alt') or '').strip() or ial or ilb or iti)
|
|
1263
1762
|
if not (text.strip() or al or lb or ti
|
|
1264
1763
|
or ' '.join(x for x in _img_names if x).strip()
|
|
1265
1764
|
or (a.get('alt') or '').strip()):
|
|
1266
1765
|
p.controls_by_kind.setdefault(kind, []).append(a)
|
|
1267
|
-
for level, a, text, hidden in p.headings_raw:
|
|
1766
|
+
for level, a, text, hidden, _hroute in p.headings_raw:
|
|
1268
1767
|
if hidden:
|
|
1269
1768
|
continue
|
|
1270
1769
|
lb, al, _ti = _name_sources(a)
|
|
@@ -1276,7 +1775,11 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1276
1775
|
if level == 1:
|
|
1277
1776
|
p.h1s += 1
|
|
1278
1777
|
lowered = heading_name.lower().strip()
|
|
1279
|
-
|
|
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:
|
|
1280
1783
|
p.vague_headings.append(f'h{level} "{heading_name[:40]}"')
|
|
1281
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):
|
|
1282
1785
|
p.vague_headings.append(f'h{level} "{heading_name[:40]}"')
|
|
@@ -1310,6 +1813,7 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1310
1813
|
or _content_name)
|
|
1311
1814
|
if not (_has_real_name or _placeholder):
|
|
1312
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)
|
|
1313
1817
|
for tag, a, en_label, hidden in p._placeholder_candidates:
|
|
1314
1818
|
# placeholder como ÚNICO nombre: revisión 3.3.2 (el accname del
|
|
1315
1819
|
# navegador lo cuenta, pero como etiqueta es débil — se declara)
|
|
@@ -1319,6 +1823,7 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1319
1823
|
if not (lb or al or ti or en_label
|
|
1320
1824
|
or (a.get('id') and a['id'] in p._labels_for)):
|
|
1321
1825
|
p.placeholder_only.append(f'{tag}[placeholder="{(a.get("placeholder") or "")[:30]}"]')
|
|
1826
|
+
p.placeholder_only_elems.append(a)
|
|
1322
1827
|
|
|
1323
1828
|
findings = []
|
|
1324
1829
|
|
|
@@ -1326,28 +1831,58 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1326
1831
|
h = {'severity': severity, 'criterion': _crit(lang, code), 'signal': key_msg,
|
|
1327
1832
|
'issue': _t(lang, key_msg, n=fmt.get('n')).format(**fmt)}
|
|
1328
1833
|
h['remediation'] = _t(lang, key_msg + '_rem').format(**fmt)
|
|
1834
|
+
paths = fmt.pop('paths', None)
|
|
1835
|
+
if paths:
|
|
1836
|
+
h['paths'] = paths[:5]
|
|
1329
1837
|
findings.append(h)
|
|
1330
1838
|
|
|
1331
1839
|
def add_ej(severity, code, key_msg, examples, **fmt):
|
|
1332
1840
|
add(severity, code, key_msg, **fmt)
|
|
1333
1841
|
findings[-1]['examples'] = examples[:5]
|
|
1334
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)
|
|
1335
1849
|
if p.imgs_no_alt:
|
|
1336
|
-
|
|
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)
|
|
1337
1854
|
if p.input_img_no_alt:
|
|
1338
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)
|
|
1339
1861
|
for tag, controls in p.controls_by_kind.items():
|
|
1340
|
-
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])
|
|
1341
1865
|
if p.aria_hidden_focusable:
|
|
1342
1866
|
add('high', '4.1.2', 'aria_hidden_focusable',
|
|
1343
|
-
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])
|
|
1344
1870
|
if p.fields_no_label:
|
|
1345
1871
|
add_ej('high', '3.3.2', 'field_label',
|
|
1346
1872
|
[f'{t} name={n or "(no name)"}' for t, n, _i in p.fields_no_label],
|
|
1347
|
-
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])
|
|
1348
1876
|
if p.stray_clicks:
|
|
1349
1877
|
add('high', '2.1.1', 'click_nonfocusable',
|
|
1350
|
-
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])
|
|
1351
1886
|
if p.orphan_labels:
|
|
1352
1887
|
add('low', '3.3.2', 'label_orphan', n=p.orphan_labels)
|
|
1353
1888
|
if p._bad_list:
|
|
@@ -1357,7 +1892,8 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1357
1892
|
# (idioma, título, bypass, encabezados) no aplican (ACT b5c3f8/3e12e1)
|
|
1358
1893
|
pass
|
|
1359
1894
|
elif not p.lang:
|
|
1360
|
-
add('medium', '3.1.1', 'lang_missing'
|
|
1895
|
+
add('medium', '3.1.1', 'lang_missing',
|
|
1896
|
+
paths=[path_segment('html', 1)])
|
|
1361
1897
|
elif p.lang.lower().split('-')[0] not in _LANG_CODES:
|
|
1362
1898
|
add('medium', '3.1.1', 'lang_invalid', lang=p.lang)
|
|
1363
1899
|
elif p.lang_region_invalid:
|
|
@@ -1365,16 +1901,21 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1365
1901
|
# el PRIMER <title> del documento decide (modelo ACT 2779a5)
|
|
1366
1902
|
p.title = p._titles_in_order[0] if p._titles_in_order else ''
|
|
1367
1903
|
t_clean = (p.title or '').strip().lower()
|
|
1368
|
-
if not t_clean:
|
|
1904
|
+
if not t_clean and p.root_tag not in ('svg', 'math'):
|
|
1369
1905
|
add('medium', '2.4.2', 'title_missing')
|
|
1370
1906
|
elif t_clean in ('untitled', 'documento', 'documento sin título', 'sin título',
|
|
1371
1907
|
'home', 'inicio', 'page 1', 'new page', 'página 1',
|
|
1372
1908
|
'untitled document', 'sin nombre', 'document'):
|
|
1373
1909
|
add('low', '2.4.2', 'title_generic', t=t_clean)
|
|
1374
1910
|
if p.iframes_no_title:
|
|
1375
|
-
add_ej('medium', '4.1.2', 'iframe_title', p.iframes_no_title,
|
|
1376
|
-
|
|
1377
|
-
|
|
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])
|
|
1378
1919
|
if p.viewport:
|
|
1379
1920
|
# valores inválidos también blocksn (ACT b4f0c3): user-scalable ha de
|
|
1380
1921
|
# ser yes/true o numérico ≥ 1; maximum-scale numérico — si no parsea,
|
|
@@ -1387,7 +1928,9 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1387
1928
|
except ValueError:
|
|
1388
1929
|
allows = v in ('yes', 'true')
|
|
1389
1930
|
if not allows:
|
|
1390
|
-
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))
|
|
1391
1934
|
m_ms = re.search(r'maximum-scale\s*=\s*([\w.-]+)', p.viewport, re.I)
|
|
1392
1935
|
if m_ms:
|
|
1393
1936
|
_v_ms = m_ms.group(1)
|
|
@@ -1398,23 +1941,34 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1398
1941
|
blocks = _v_ms.lower() not in ('device-width', 'device-height',
|
|
1399
1942
|
'initial-scale', 'width', 'height')
|
|
1400
1943
|
if blocks:
|
|
1401
|
-
|
|
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))
|
|
1402
1949
|
# meta refresh (2.2.1/ACT bc659a): gana el PRIMER meta que parsea según
|
|
1403
1950
|
# los pasos del HTML (dígitos + ; o , o fin — un «0: url» con dos puntos
|
|
1404
1951
|
# NO parsea y se salta); 0 segundos = redirección inmediata y > 72000
|
|
1405
1952
|
# (20 h) quedan EXENTOS
|
|
1406
1953
|
_mr = None
|
|
1407
|
-
|
|
1954
|
+
_mr_elem = None
|
|
1955
|
+
for _idx_mr, _content in enumerate(p.meta_refreshes
|
|
1956
|
+
or ([p.meta_refresh] if p.meta_refresh else [])):
|
|
1408
1957
|
_m = re.match(r'\s*(\d+)\s*(?:[;,]|$)', _content or '')
|
|
1409
1958
|
if _m:
|
|
1410
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
|
|
1411
1961
|
break
|
|
1412
1962
|
if _mr is not None and 0 < _mr <= 72000:
|
|
1413
|
-
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))
|
|
1414
1966
|
if p.positive_tabindices:
|
|
1415
1967
|
add_ej('medium', '2.4.3', 'tabindex_pos',
|
|
1416
1968
|
[f'{t}[tabindex={i}]' for t, i in p.positive_tabindices],
|
|
1417
|
-
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])
|
|
1418
1972
|
# un toggle cuenta como mecanismo de abatido SOLO si la función que
|
|
1419
1973
|
# invoca colapsa de verdad (su cuerpo, en el script de la página, toca
|
|
1420
1974
|
# `display`): mover off-screen o aria-hidden no colapsa el bloque (3e12e1)
|
|
@@ -1439,12 +1993,16 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1439
1993
|
_nav_collapsible = not re.search(r'visib|aria', _nom) \
|
|
1440
1994
|
and bool(re.search(r'hide|hidden|collapse|display', _nom))
|
|
1441
1995
|
if p.root_tag not in ('svg', 'math') and not (p.hay_main or p.hay_skip or _nav_collapsible):
|
|
1442
|
-
|
|
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')
|
|
1443
1999
|
|
|
1444
2000
|
levels = [n for n, _ in p.headings]
|
|
1445
2001
|
if levels:
|
|
1446
2002
|
if p.h1s == 0:
|
|
1447
|
-
|
|
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')
|
|
1448
2006
|
elif p.h1s > 1:
|
|
1449
2007
|
add('low', '1.3.1', 'multi_h1', n=p.h1s)
|
|
1450
2008
|
prev = 0
|
|
@@ -1456,16 +2014,22 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1456
2014
|
if jumps:
|
|
1457
2015
|
add('low', '1.3.1', 'heading_skips', skips=', '.join(jumps[:5]))
|
|
1458
2016
|
elif p.root_tag not in ('svg', 'math'):
|
|
1459
|
-
add('
|
|
2017
|
+
add('low', '1.3.1', 'no_headings')
|
|
1460
2018
|
if p.empty_h:
|
|
1461
2019
|
add('low', '1.3.1', 'empty_heading', n=p.empty_h)
|
|
1462
2020
|
if p.tables and p.tables_with_th < p.tables:
|
|
1463
|
-
add('medium', '1.3.1', 'table_no_th', n=p.tables - p.tables_with_th
|
|
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])
|
|
1464
2024
|
if p.blank_no_warning:
|
|
1465
|
-
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])
|
|
1466
2028
|
dups = sum(1 for _c, k in p.ids.items() if k > 1)
|
|
1467
2029
|
if dups:
|
|
1468
|
-
|
|
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)
|
|
1469
2033
|
|
|
1470
2034
|
# --- v3.1: validez ARIA, autocomplete, enlaces, landmarks, accesskey ---
|
|
1471
2035
|
broken_refs = [f'{attr}="#{ref}"' for attr, ref in p.aria_refs if ref not in p.ids]
|
|
@@ -1488,12 +2052,16 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1488
2052
|
n=len(p.roles_without_state), example=', '.join(p.roles_without_state[:4]))
|
|
1489
2053
|
if p.missing_autocomplete:
|
|
1490
2054
|
add_ej('medium', '1.3.5', 'autocomplete', p.missing_autocomplete,
|
|
1491
|
-
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])
|
|
1492
2058
|
if p.autocomplete_invalid:
|
|
1493
2059
|
add_ej('medium', '1.3.5', 'autocomplete_invalid', p.autocomplete_invalid,
|
|
1494
2060
|
n=len(p.autocomplete_invalid), example=', '.join(p.autocomplete_invalid[:4]))
|
|
1495
2061
|
if p.media_autoplay:
|
|
1496
|
-
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])
|
|
1497
2065
|
if p.label_no_name:
|
|
1498
2066
|
_ln = p.label_no_name[0]
|
|
1499
2067
|
add_ej('medium', '2.5.3', 'label_in_name',
|
|
@@ -1508,7 +2076,9 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1508
2076
|
# forms deep-dive
|
|
1509
2077
|
if p.placeholder_only:
|
|
1510
2078
|
add_ej('high', '3.3.2', 'placeholder_only', p.placeholder_only,
|
|
1511
|
-
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])
|
|
1512
2082
|
if p.required_no_indication:
|
|
1513
2083
|
add_ej('low', '3.3.2', 'required_no_indication', p.required_no_indication,
|
|
1514
2084
|
n=len(p.required_no_indication), example=', '.join(p.required_no_indication[:3]))
|
|
@@ -1528,10 +2098,13 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1528
2098
|
if p.drag_handlers:
|
|
1529
2099
|
add_ej('low', '2.5.7', 'drag_no_alt', p.drag_handlers,
|
|
1530
2100
|
n=len(p.drag_handlers), example=', '.join(p.drag_handlers[:3]))
|
|
1531
|
-
# 4.1.3:
|
|
1532
|
-
|
|
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)
|
|
1533
2106
|
if dynamic and p.status_regions == 0:
|
|
1534
|
-
add('
|
|
2107
|
+
add('low', '4.1.3', 'no_status_regions')
|
|
1535
2108
|
if p.images_of_text:
|
|
1536
2109
|
add_ej('low', '1.4.5', 'images_of_text', p.images_of_text,
|
|
1537
2110
|
n=len(p.images_of_text), ej2='')
|
|
@@ -1551,8 +2124,10 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1551
2124
|
if p.orientation_locks:
|
|
1552
2125
|
add_ej('low', '1.3.4', 'orientation_lock', p.orientation_locks,
|
|
1553
2126
|
n=len(p.orientation_locks), example=', '.join(p.orientation_locks[:2]))
|
|
1554
|
-
if p.videos and p.
|
|
1555
|
-
add('low', '1.2.3', 'audio_desc_missing', n=p.
|
|
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])
|
|
1556
2131
|
if p.sensory:
|
|
1557
2132
|
add('low', '1.3.3', 'sensory_text', example='; '.join(p.sensory[:2])[:70])
|
|
1558
2133
|
lm_dups = [f'{lm} ×{t[1]}' for lm, t in p.landmarks.items()
|
|
@@ -1579,9 +2154,11 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1579
2154
|
reading = _reading_level(' '.join(p._visible_text),
|
|
1580
2155
|
page_lang if page_lang in ('es', 'en') else lang)
|
|
1581
2156
|
|
|
2157
|
+
import hashlib as _hl
|
|
1582
2158
|
res = {
|
|
1583
2159
|
'mode': 'static',
|
|
1584
2160
|
'url': url,
|
|
2161
|
+
'source_sha256': _hl.sha256(html_text.encode('utf-8', 'replace')).hexdigest(),
|
|
1585
2162
|
'reading_level': reading,
|
|
1586
2163
|
'score': compute_score(findings),
|
|
1587
2164
|
'score_note': _t(lang, 'score_note'),
|
|
@@ -1605,6 +2182,13 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1605
2182
|
_cl = _enstd.clause_for(h['criterion'].split(' ')[0], _tgt)
|
|
1606
2183
|
if _cl:
|
|
1607
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
|
|
1608
2192
|
# overlays detectados: dato del informe (diligencia de compra), nunca un
|
|
1609
2193
|
# hallazgo — no hay criterio WCAG que anclar y el score no se toca
|
|
1610
2194
|
overlays, _seen = [], set()
|
|
@@ -1620,18 +2204,61 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
1620
2204
|
return res
|
|
1621
2205
|
|
|
1622
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
|
+
|
|
1623
2215
|
# ── redirect policy hook ───────────────────────────────────────────────────
|
|
1624
2216
|
# urlopen follows 3xx (up to 10 hops) to ANY host without asking: every hop
|
|
1625
|
-
# is a NEW destination nobody validated.
|
|
1626
|
-
#
|
|
1627
|
-
#
|
|
1628
|
-
|
|
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
|
|
1629
2245
|
|
|
1630
2246
|
|
|
1631
2247
|
class _CheckedRedirect(urllib.request.HTTPRedirectHandler):
|
|
1632
2248
|
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
1633
|
-
|
|
1634
|
-
|
|
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])
|
|
1635
2262
|
return super().redirect_request(req, fp, code, msg, headers, newurl)
|
|
1636
2263
|
|
|
1637
2264
|
|
|
@@ -1669,7 +2296,7 @@ def _fetch(url, timeout=30, truncate_at=None, accept_ct=()):
|
|
|
1669
2296
|
break
|
|
1670
2297
|
data += chunk
|
|
1671
2298
|
if len(data) > ceiling and truncate_at is None:
|
|
1672
|
-
raise
|
|
2299
|
+
raise _FetchError('err_too_big', mb=MAX_HTML // 1000000)
|
|
1673
2300
|
if (r.headers.get('Content-Encoding') or '').lower() == 'gzip' or data[:2] == b'\x1f\x8b':
|
|
1674
2301
|
import zlib
|
|
1675
2302
|
d = zlib.decompressobj(16 + zlib.MAX_WBITS)
|
|
@@ -1680,7 +2307,7 @@ def _fetch(url, timeout=30, truncate_at=None, accept_ct=()):
|
|
|
1680
2307
|
base = ctype.split(';')[0].strip()
|
|
1681
2308
|
extra_ok = any(base == p or base.startswith(p + '/') for p in accept_ct)
|
|
1682
2309
|
if ctype and not extra_ok and 'html' not in ctype and 'xml' not in ctype and base:
|
|
1683
|
-
raise
|
|
2310
|
+
raise _FetchError('err_not_html', ct=base)
|
|
1684
2311
|
# the HEADER charset wins over body sniffing (HTTP has priority over
|
|
1685
2312
|
# <meta>): a server declaring iso-8859-1 without a meta tag otherwise
|
|
1686
2313
|
# produces U+FFFD inside findings
|
|
@@ -1709,6 +2336,8 @@ def audit_url(url, timeout=30, lang='en', standard=None, target=None):
|
|
|
1709
2336
|
return {'error': _T_SCHEME.get(lang, _T_SCHEME['es'])}
|
|
1710
2337
|
try:
|
|
1711
2338
|
html_text = _fetch(url, timeout=timeout)
|
|
2339
|
+
except _FetchError as e:
|
|
2340
|
+
return {'error': _t(lang, e.key).format(**e.fmt)}
|
|
1712
2341
|
except ValueError as e:
|
|
1713
2342
|
return {'error': str(e)}
|
|
1714
2343
|
except Exception as e: # noqa: BLE001
|
|
@@ -1795,7 +2424,10 @@ def evaluate_site(parsers, lang='en'):
|
|
|
1795
2424
|
'issue': _t(lang, 'help_inconsistent').format(
|
|
1796
2425
|
example=f'{len(set(signatures_help))} variantes en {len(signatures_help)} páginas'),
|
|
1797
2426
|
'remediation': _t(lang, 'help_inconsistent_rem')})
|
|
1798
|
-
|
|
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):
|
|
1799
2431
|
out.append({'severity': 'medium', 'criterion': _crit(lang, '2.4.5'),
|
|
1800
2432
|
'signal': 'no_multiple_ways',
|
|
1801
2433
|
'issue': _t(lang, 'no_multiple_ways'),
|
|
@@ -1812,12 +2444,25 @@ def audit_site(url, max_pages=5, timeout=30, lang='en', from_sitemap=True,
|
|
|
1812
2444
|
deadline = (time.monotonic() + budget) if budget else None
|
|
1813
2445
|
try:
|
|
1814
2446
|
html_text = _fetch(url, timeout=timeout)
|
|
2447
|
+
except _FetchError as e:
|
|
2448
|
+
return {'error': _t(lang, e.key).format(**e.fmt)}
|
|
1815
2449
|
except ValueError as e:
|
|
1816
2450
|
return {'error': str(e)}
|
|
1817
2451
|
except Exception as e: # noqa: BLE001
|
|
1818
2452
|
return {'error': _t(lang, 'fetch_error').format(e=e)}
|
|
1819
|
-
|
|
1820
|
-
|
|
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
|
|
1821
2466
|
reports = [audit_html(html_text, url, lang=lang)]
|
|
1822
2467
|
parsers = [p0]
|
|
1823
2468
|
seen = {url.split('#')[0].rstrip('/')}
|
|
@@ -1835,9 +2480,10 @@ def audit_site(url, max_pages=5, timeout=30, lang='en', from_sitemap=True,
|
|
|
1835
2480
|
html_pg = _fetch(next, timeout=timeout)
|
|
1836
2481
|
except Exception: # noqa: BLE001
|
|
1837
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
|
|
1838
2486
|
reports.append(audit_html(html_pg, next, lang=lang))
|
|
1839
|
-
pg = _Auditor()
|
|
1840
|
-
pg.feed(html_pg[:MAX_HTML]); pg.close()
|
|
1841
2487
|
parsers.append(pg)
|
|
1842
2488
|
if len(reports) < max_pages and not from_sitemap:
|
|
1843
2489
|
for new in _internal_links(html_pg, next, url):
|
|
@@ -1848,6 +2494,9 @@ def audit_site(url, max_pages=5, timeout=30, lang='en', from_sitemap=True,
|
|
|
1848
2494
|
for inf in reports[:1]:
|
|
1849
2495
|
inf.setdefault('findings', []).append(h)
|
|
1850
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')}
|
|
1851
2500
|
scores = [pg['score'] for pg in reports if 'score' in pg]
|
|
1852
2501
|
findings_by_signal = {}
|
|
1853
2502
|
for pg in reports:
|
|
@@ -1939,18 +2588,29 @@ def audit_changed(base='HEAD', lang='en', cwd='.'):
|
|
|
1939
2588
|
|
|
1940
2589
|
|
|
1941
2590
|
def _apply_standard(res, standard, target, lang):
|
|
1942
|
-
""" Enriquecimiento post-hoc EN 301 549 (site crawl, --changed):
|
|
1943
|
-
bloque standard y cláusula por hallazgo. standard=None →
|
|
1944
|
-
|
|
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:
|
|
1945
2596
|
return res
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
|
|
1950
|
-
for
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
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
|
|
1954
2614
|
return res
|
|
1955
2615
|
|
|
1956
2616
|
|
|
@@ -1968,7 +2628,7 @@ def main(argv):
|
|
|
1968
2628
|
help='crawl ligero mismo dominio (1 = solo la página)')
|
|
1969
2629
|
ap.add_argument('--no-sitemap', action='store_true',
|
|
1970
2630
|
help='descubre por enlaces, sin leer el sitemap')
|
|
1971
|
-
ap.add_argument('--standard', choices=['en301549'], default=None,
|
|
2631
|
+
ap.add_argument('--standard', choices=['en301549', 'rgaa'], default=None,
|
|
1972
2632
|
help='añade a cada hallazgo su cláusula EN 301 549 V4.1.1 '
|
|
1973
2633
|
'(9.x web por defecto)')
|
|
1974
2634
|
ap.add_argument('--target', choices=['web', 'documents', 'software'],
|
|
@@ -1991,7 +2651,7 @@ def main(argv):
|
|
|
1991
2651
|
standard=a.standard,
|
|
1992
2652
|
target=a.target))
|
|
1993
2653
|
except Exception as e: # noqa: BLE001
|
|
1994
|
-
print(json.dumps({'error':
|
|
2654
|
+
print(json.dumps({'error': _t(a.lang, 'fetch_error').format(e=e)}))
|
|
1995
2655
|
return 1
|
|
1996
2656
|
else:
|
|
1997
2657
|
with open(a.file, encoding='utf-8', errors='replace') as f:
|