@kinti/a11y-toolkit 5.32.0 → 5.33.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.
@@ -22,6 +22,7 @@ import os
22
22
  import re
23
23
  import sys
24
24
  import urllib.request
25
+ from urllib.parse import unquote
25
26
  from html.parser import HTMLParser
26
27
  from . import a11yi18n
27
28
 
@@ -426,6 +427,38 @@ _OVERLAY_WIDGETS = (
426
427
  _SKIP_TEXT = re.compile(
427
428
  r'skip|jump to|saltar|ir al contenido|ir para o conte[uú]do|passer au contenu', re.I)
428
429
 
430
+ # 3.2.1: un select[autofocus] solo cambia el contexto si lleva un script que
431
+ # lo haga. Eventos que dispara quien aterrizó en el control sin elegirlo (el
432
+ # foco llega solo al cargar; después, la primera tecla o el cambio de opción) y
433
+ # llamadas que cambian el contexto: navegación, ventana nueva, envío, foco.
434
+ _FOCUS_EVENTS = ('onfocus', 'onchange', 'oninput', 'onkeydown', 'onkeyup', 'onkeypress')
435
+ _CTX_CHANGE = re.compile(
436
+ r'\blocation\s*=(?!=)|\blocation\.href\b|\blocation\.(?:replace|assign|reload)\s*\('
437
+ r'|\bwindow\.open\s*\(|\.submit\s*\(|\.focus\s*\(', re.I)
438
+
439
+ # contexto requerido por rol (ARIA 1.2; la misma tabla que la regla
440
+ # aria-required-parent del motor de referencia). El ancestro vale por rol
441
+ # explícito o por la etiqueta implícita de ese rol. `group` nunca es destino:
442
+ # vale como paso intermedio y entonces hace falta el contexto DEL grupo (un
443
+ # treeitem en un group solo está bien si el group vive en un tree o en otro
444
+ # treeitem del mismo tipo).
445
+ _ROLE_PARENTS = {
446
+ 'listitem': ('list',),
447
+ 'menuitem': ('group', 'menu', 'menubar'),
448
+ 'menuitemcheckbox': ('group', 'menu', 'menubar'),
449
+ 'menuitemradio': ('group', 'menu', 'menubar'),
450
+ 'option': ('group', 'listbox'),
451
+ 'tab': ('tablist',),
452
+ 'treeitem': ('group', 'tree'),
453
+ }
454
+ _IMPLICIT_PARENT = {'list': ('ul', 'ol'), 'menu': ('menu',)}
455
+ # roles para los que, dentro de un group, un ancestro del MISMO rol cierra el
456
+ # contexto (un treeitem carpeta agrupa sus hijos en un group)
457
+ _OWN_GROUP_ROLE = {'treeitem'}
458
+ # saltos de aria-owns que se siguen en cadena antes de cortar (un dueño que a
459
+ # su vez es owned por otro): corta también los ciclos A owns B owns A
460
+ _OWN_DEPTH = 8
461
+
429
462
  # encabezados cortos legítimos (acrónimos y términos técnicos): «FAQ», «API»…
430
463
  _SHORT_HEADINGS = {'FAQ', 'API', 'CSS', 'SVG', 'APP', 'MAP', 'EN', 'DE', 'ES', 'PT', 'FR',
431
464
  'IT', 'UI', 'UX', 'ID', 'TV', 'HR', 'PR', 'AI', 'PC', 'OK', '3D',
@@ -589,12 +622,28 @@ class _Auditor(HTMLParser):
589
622
  self.autocomplete_mismatch = []
590
623
  self.heading_role_removed = [] # h1-h6 con rol que sustituye al de heading
591
624
  self.text_spacing_important = [] # 1.4.12: spacing !important inline (ACT 24afc2/78fd32/9e45ec)
592
- self.a_no_href = [] # 2.1.1: <a> sin href usado como control (batida B1-a)
593
- self.nested_main = [] # 1.3.1: main anidado en seccionante (B1-b)
594
- self.fake_lists = [] # 1.3.1: lista falsa con viñetas y <br> (B1-c)
595
- self.alert_polite = [] # 4.1.2: role=alert gritando en aria-live=polite (B1-d)
625
+ self.a_no_href = [] # 2.1.1: <a> sin href usado como control
626
+ self.nested_main = [] # 1.3.1: main anidado en seccionante
627
+ self.fake_lists = [] # 1.3.1: lista falsa con viñetas y <br>
628
+ self.alert_polite = [] # 4.1.2: role=alert gritando en aria-live=polite
596
629
  self.headers_bad = [] # 1.3.1: headers= apuntando fuera de tabla o a no-th (ACT d0f69e/a25f45)
597
630
  self.lang_xml_mismatch = [] # 3.1.2: lang y xml:lang discrepando (ACT 5b7ae0)
631
+ self.nested_interactive = [] # 4.1.2: interactivo DENTRO de interactivo
632
+ self.select_auto_focus = [] # 3.2.1: select[autofocus] + script de cambio de contexto
633
+ self.select_auto_focus_elems = []
634
+ self.skip_broken = [] # 2.4.1: skip/fragmento a id inexistente (F89)
635
+ self.skip_broken_elems = []
636
+ self.role_orphans = [] # 1.3.1: rol sin su padre requerido (ACT ff89c9)
637
+ self.role_orphan_elems = []
638
+ self._skip_hrefs = [] # (fragmento, attrs) de enlaces de salto (vocabulario ya filtrado)
639
+ self._name_anchors = set() # <a name="…">: destino de fragmento legítimo
640
+ self._role_ctx_pending = [] # (attrs, rol, ancestros DOM) a resolver post-parse
641
+ self._owned_by = {} # id → attrs del elemento que lo declara en aria-owns
642
+ self._owner_ancestors = {} # id(attrs) → ancestros DOM del dueño (aria-owns)
643
+ self.invoker_bad = [] # 4.1.2: commandfor sin destino o tipo erróneo
644
+ self.aria_level_gt6 = [] # 1.3.1: aria-level>6 (los lectores lo degradan)
645
+ self._invokers = [] # (idref, command) pendientes de validar
646
+ self._id_tag = {} # id → (tag, popover?) para validar invokers
598
647
  self._p_bullets = None # contador de viñetas del <p> abierto
599
648
  self._p_brs = 0
600
649
  self.links = {} # nombre normalizado → set de hrefs
@@ -685,13 +734,24 @@ class _Auditor(HTMLParser):
685
734
  _lb_ids = (a.get('aria-labelledby') or '').split()
686
735
  if _vis and (_al or _lb_ids) and len(self.label_in_name_raw) < 30:
687
736
  self.label_in_name_raw.append((_vis[:80], _al[:120], _lb_ids[:6], a))
737
+ # enlaces de salto: el vocabulario se decide AQUÍ, con el texto ya
738
+ # completo: el límite solo corta entre saltos, nunca delante de ellos
739
+ # (antes se recogían los 12 primeros enlaces internos y un salto que
740
+ # venía detrás de 12 notas al pie quedaba fuera sin ser examinado)
741
+ if tag == 'a' and text:
742
+ _skip_href = (a.get('href') or '').strip()
743
+ if _skip_href.startswith('#') and len(_skip_href) > 1 \
744
+ and _SKIP_TEXT.search(text) and len(self._skip_hrefs) < 12:
745
+ self._skip_hrefs.append((_skip_href[1:], a))
688
746
  if tag == 'a' and not c.get('hidden'):
689
747
  if (a.get('target') or '').lower() == '_blank':
690
748
  self.blank_total += 1
691
749
  _img_alts = ' '.join((ia.get('alt') or '')
692
750
  for ia in c.get('img_attrs', []))
751
+ # title NO cuenta como aviso: quien navega solo con teclado
752
+ # jamás lo ve (hover-only). Salvan: texto visible, aria-label
753
+ # (el lector lo anuncia) y el alt de una imagen interna
693
754
  if not _BLANK_HINT.search(text) and not _BLANK_HINT.search(a.get('aria-label') or '') \
694
- and not _BLANK_HINT.search(a.get('title') or '') \
695
755
  and not _BLANK_HINT.search(_img_alts):
696
756
  self.blank_no_warning += 1
697
757
  self.blank_no_warning_elems.append(a)
@@ -769,6 +829,7 @@ class _Auditor(HTMLParser):
769
829
  if a.get('id') and not self._in_template:
770
830
  # ids dentro de <template> no existen: ni dup_ids ni refs rotas
771
831
  self.ids[a['id']] = self.ids.get(a['id'], 0) + 1
832
+ self._id_tag[a['id']] = (tag, 'popover' in a)
772
833
  if self.root_tag is None:
773
834
  self.root_tag = tag
774
835
  # visibilidad heredada para accname y enfocabilidad: aria-hidden se
@@ -963,7 +1024,7 @@ class _Auditor(HTMLParser):
963
1024
  _tok_ac = (a.get('autocomplete') or '').strip().lower()
964
1025
  _covered = bool(_tok_ac) and _tok_ac not in ('off', 'on')
965
1026
  if (not _covered) and kind != 'search' and not _recipient and (
966
- kind in ('email', 'tel')
1027
+ kind in ('email', 'tel', 'password')
967
1028
  or _PERSONAL_DATA.search((a.get('name') or '') + ' ' + (a.get('id') or ''))):
968
1029
  self.missing_autocomplete.append(f'input type={kind} name={a.get("name") or "?"}'[:44])
969
1030
  self.autocomplete_elems.append(a)
@@ -1333,7 +1394,7 @@ class _Auditor(HTMLParser):
1333
1394
  # nombre le llega del alt)
1334
1395
  self.controls_raw.append(('area', a, '', [], _hidden))
1335
1396
  if tag == 'main' and not self._in_template:
1336
- # B1-b (batida 18-nov): main es top-level por definición — anidado
1397
+ # main es top-level por definición: anidado
1337
1398
  # en section/aside/nav/article/main/header/footer no es ni landmark
1338
1399
  # válido ni estructura honesta (1.3.1)
1339
1400
  # [-1] es el PROPIO main (ya apilado cuando corre este chequeo):
@@ -1368,6 +1429,9 @@ class _Auditor(HTMLParser):
1368
1429
  _alv = re.match(r'\d+', str(a.get('aria-level') or ''))
1369
1430
  if _alv:
1370
1431
  self._heading_level = int(_alv.group())
1432
+ if int(_alv.group()) > 6 and len(self.aria_level_gt6) < 6:
1433
+ self.aria_level_gt6.append(
1434
+ f'{tag} aria-level="{_alv.group()}"')
1371
1435
  self._heading_text = []
1372
1436
  self._heading_attrs = a
1373
1437
  self._heading_hidden = _hidden
@@ -1378,13 +1442,76 @@ class _Auditor(HTMLParser):
1378
1442
  # basura JAMÁS tira el parse (int guardado)
1379
1443
  _alv = re.match(r'\d+', str(a.get('aria-level') or ''))
1380
1444
  self._heading_level = int(_alv.group()) if _alv else 2
1445
+ if _alv and int(_alv.group()) > 6 and len(self.aria_level_gt6) < 6:
1446
+ self.aria_level_gt6.append(
1447
+ f'[role=heading] aria-level="{_alv.group()}"')
1381
1448
  self._heading_text = []
1382
1449
  self._heading_attrs = a
1383
1450
  self._heading_hidden = _hidden
1384
1451
  self._heading_tag = tag
1385
- # ── batida 18-nov, día 2 ──
1452
+ # select[autofocus] (3.2.1): el control recibe el foco al cargar, pero
1453
+ # el atributo SOLO no cambia nada (medido en Chromium 147 sin interfaz:
1454
+ # foco en el control, opción inicial intacta). Es hallazgo cuando
1455
+ # además lleva un script de cambio de contexto en un evento que dispara
1456
+ # quien aterrizó allí sin elegirlo (el foco, un cambio de opción, una tecla)
1457
+ if tag == 'select' and 'autofocus' in a and not self._in_template \
1458
+ and not _hidden:
1459
+ for _ev in _FOCUS_EVENTS:
1460
+ _code = a.get(_ev) or ''
1461
+ if _code and _CTX_CHANGE.search(_code) \
1462
+ and len(self.select_auto_focus) < 5:
1463
+ self.select_auto_focus.append(f'select[autofocus][{_ev}="{_code[:40]}"]')
1464
+ self.select_auto_focus_elems.append(a)
1465
+ break
1466
+ # roles con contexto requerido (ARIA 1.2 §5.2.7: el elemento debe
1467
+ # estar contenido en, o ser owned por, un elemento del rol de contexto;
1468
+ # ACT ff89c9). SOLO roles EXPLÍCITOS (el li implícito fuera de lista es
1469
+ # otra familia, muy FP). Aquí solo se REGISTRA: el veredicto es
1470
+ # post-parse porque el dueño por aria-owns puede venir después.
1471
+ _rv = (a.get('role') or '').strip().lower()
1472
+ if _rv in _ROLE_PARENTS and not self._in_template and not _hidden \
1473
+ and len(self._role_ctx_pending) < 400:
1474
+ self._role_ctx_pending.append(
1475
+ (a, _rv, [(_t, _fa) for _t, _fa, _ in self._el_stack if _fa is not a]))
1476
+ if a.get('aria-owns') and len(self._owner_ancestors) < 400:
1477
+ self._owner_ancestors[id(a)] = \
1478
+ [(tag, a)] + [(_t, _fa) for _t, _fa, _ in self._el_stack if _fa is not a]
1479
+ for _owned_id in str(a['aria-owns']).split():
1480
+ self._owned_by.setdefault(_owned_id, a)
1481
+ # destino clásico de fragmento: <a name="…"> también resuelve #…
1482
+ if tag == 'a' and a.get('name'):
1483
+ self._name_anchors.add(a['name'])
1484
+ # interactivo dentro de interactivo (4.1.2): el modelo de contenido lo
1485
+ # prohíbe; el AT anuncia mal el interno y el externo pierde su límite.
1486
+ # Ancestros por el ÁRBOL REAL (_el_stack), no por _ctrl (malformados).
1487
+ # Exento a>a puro: todos los navegadores lo reparan a hermanos.
1488
+ _INTER_HOST = ('a', 'button', 'summary', 'select', 'textarea')
1489
+ if tag in _INTER_HOST or (tag == 'input' and (a.get('type') or 'text')
1490
+ not in ('hidden', 'submit', 'button', 'reset', 'image')) \
1491
+ or (a.get('role') or '').strip().lower() in ('button', 'link'):
1492
+ if len(self.nested_interactive) < 6:
1493
+ for _anc_tag, _anc_a, _ in reversed(self._el_stack):
1494
+ if _anc_a is a:
1495
+ continue # el propio elemento ya viaja en la pila
1496
+ _anc_inter = _anc_tag in _INTER_HOST
1497
+ if _anc_tag == 'a':
1498
+ if not (_anc_a.get('href') or '').strip():
1499
+ _anc_inter = False # ancla sin href: no interactiva
1500
+ elif tag == 'a' and not (_anc_a.get('role') or a.get('role')):
1501
+ _anc_inter = False # a>a puro: reparado a hermanos
1502
+ if _anc_inter:
1503
+ self.nested_interactive.append(f'<{tag}> dentro de <{_anc_tag}>')
1504
+ break
1505
+ # invoker commands (4.1.2): commandfor ha de resolver Y el comando casar
1506
+ # con el tipo de destino (show-modal/close → dialog; show/hide/toggle →
1507
+ # popover). Se valida POST-parse (el destino puede venir después)
1508
+ if tag == 'button' and a.get('commandfor'):
1509
+ if len(self._invokers) < 8:
1510
+ self._invokers.append(((a.get('commandfor') or '').strip(),
1511
+ (a.get('command') or '').strip().lower()))
1512
+ # ── patrones de estructura y de estado ──
1386
1513
  if not self._in_template:
1387
- # B1-a: <a> SIN href con vida de control (2.1.1): tabindex>=0,
1514
+ # <a> SIN href con vida de control (2.1.1): tabindex>=0,
1388
1515
  # onclick o rol interactivo. Sin href NO es enlace: el AT no lo
1389
1516
  # anuncia como tal aunque sea enfocable y le echen un click.
1390
1517
  # Exento: tabindex=-1 (ancla objetivo legítima) y <a> puro con id
@@ -1397,7 +1524,7 @@ class _Auditor(HTMLParser):
1397
1524
  if _viva and len(self.a_no_href) < 12:
1398
1525
  _tx = ' '.join(self._ctrl[-1]['text']).strip()[:20] if self._ctrl else ''
1399
1526
  self.a_no_href.append('<a>' + (f' "{_tx}"' if _tx else ''))
1400
- # B1-d: role=alert ES assertive en sí mismo (ARIA): un aria-live
1527
+ # role=alert ES assertive en sí mismo (ARIA): un aria-live
1401
1528
  # polite encima lo contradice (4.1.2, estado que no es el que dice)
1402
1529
  _role_low = (a.get('role') or '').strip().lower()
1403
1530
  _live = (a.get('aria-live') or '').strip().lower()
@@ -1542,8 +1669,8 @@ class _Auditor(HTMLParser):
1542
1669
  elif tag == 'nav':
1543
1670
  self._in_nav = max(0, self._in_nav - 1)
1544
1671
  elif tag == 'p':
1545
- # B1-c: lista falsa = ≥2 viñetas tipográficas + separadores <br>
1546
- # en un párrafo fuera de listas reales (batida 18-nov, htmhell 30)
1672
+ # lista falsa = ≥2 viñetas tipográficas + separadores <br>
1673
+ # en un párrafo fuera de listas reales
1547
1674
  if self._p_bullets is not None and self._p_bullets >= 2 \
1548
1675
  and self._p_brs >= 1 and self._list_depth == 0 \
1549
1676
  and len(self.fake_lists) < 8:
@@ -1607,6 +1734,47 @@ class _Auditor(HTMLParser):
1607
1734
  index = self._elem_paths.get(id(attrs))
1608
1735
  return self._paths.format(index) if index is not None else None
1609
1736
 
1737
+ def _context_satisfied(self, role, chain, need=None, _depth=0):
1738
+ """¿La cadena de ancestros (del más cercano al más lejano) da a `role`
1739
+ su contexto requerido? El ancestro vale por rol explícito o por etiqueta
1740
+ implícita (ul/ol = list). Un `group` aceptado como paso obliga a
1741
+ seguir: el grupo necesita su propio contexto. Y cualquier elemento de
1742
+ la cadena puede estar owned por aria-owns: su dueño hace entonces de
1743
+ ancestro (ARIA 1.2: «contained inside (or owned by)»), también en
1744
+ cadena (un listbox que posee un group que posee la option)."""
1745
+ if need is None:
1746
+ need = _ROLE_PARENTS[role]
1747
+ for anc_tag, anc_a in chain:
1748
+ anc_role = (anc_a.get('role') or '').strip().lower()
1749
+ if anc_role in ('presentation', 'none'):
1750
+ continue # transparente en el árbol de accesibilidad
1751
+
1752
+ def _is(required):
1753
+ return anc_role == required or (
1754
+ not anc_role and anc_tag in _IMPLICIT_PARENT.get(required, ()))
1755
+ if 'group' in need and _is('group'):
1756
+ need = tuple(r for r in need if r != 'group') + (
1757
+ (role,) if role in _OWN_GROUP_ROLE else ())
1758
+ elif any(_is(r) for r in need):
1759
+ return True
1760
+ # este elemento está owned: se reintenta con su dueño de ancestro
1761
+ # (la cadena del dueño empieza por él) y lo que falte hasta aquí
1762
+ if _depth < _OWN_DEPTH:
1763
+ owner = self._owned_by.get(anc_a.get('id') or '')
1764
+ if owner is not None and self._context_satisfied(
1765
+ role, self._owner_ancestors[id(owner)], need, _depth + 1):
1766
+ return True
1767
+ return False
1768
+
1769
+ def _role_context_satisfied(self, attrs, role, chain):
1770
+ """Contexto por DOM o, si el DOM no basta, por aria-owns: el elemento
1771
+ está declarado en el aria-owns de otro, y su dueño hace de ancestro."""
1772
+ owner = self._owned_by.get(attrs.get('id') or '')
1773
+ if owner is not None and \
1774
+ self._context_satisfied(role, self._owner_ancestors[id(owner)]):
1775
+ return True
1776
+ return self._context_satisfied(role, chain)
1777
+
1610
1778
  _RE_CHAR_KEY = re.compile(r'key(?:Code)?\s*===?\s*["\']([a-zA-Z0-9])["\']', re.S)
1611
1779
 
1612
1780
  def handle_script_wait(self, data):
@@ -1741,7 +1909,7 @@ class _Auditor(HTMLParser):
1741
1909
  m = _SENSORIAL.search(re.sub(r'«[^»]*»|“[^”]*”|"[^"]*"', ' ', data))
1742
1910
  if m and len(self.sensory) < 6:
1743
1911
  self.sensory.append(m.group(0).strip()[:60])
1744
- # B1-c: viñetas tipográficas en prosa = lista falsa (umbral ≥2;
1912
+ # viñetas tipográficas en prosa = lista falsa (umbral ≥2;
1745
1913
  # un solo guion de cita o de lista de definición NO es lista)
1746
1914
  if self._p_bullets is not None:
1747
1915
  self._p_bullets += len(re.findall(
@@ -2269,6 +2437,63 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
2269
2437
  if p.lang_xml_mismatch:
2270
2438
  add_ej('low', '3.1.2', 'lang_xml_mismatch', p.lang_xml_mismatch,
2271
2439
  n=len(p.lang_xml_mismatch), example=', '.join(p.lang_xml_mismatch[:4]))
2440
+ if p.nested_interactive:
2441
+ add_ej('medium', '4.1.2', 'nested_interactive', p.nested_interactive,
2442
+ n=len(p.nested_interactive), example=', '.join(p.nested_interactive[:4]))
2443
+ if p.aria_level_gt6:
2444
+ add_ej('low', '1.3.1', 'aria_level_gt6', p.aria_level_gt6,
2445
+ n=len(p.aria_level_gt6), example=', '.join(p.aria_level_gt6[:4]))
2446
+ # invokers: validación POST-parse contra el registro de ids (el destino
2447
+ # puede declararse después del botón)
2448
+ for _ref, _cmd in p._invokers:
2449
+ _dst = p._id_tag.get(_ref)
2450
+ if _dst is None:
2451
+ if len(p.invoker_bad) < 8:
2452
+ p.invoker_bad.append(f'commandfor="{_ref[:20]}" sin destino')
2453
+ elif _cmd in ('show-modal', 'close') and _dst[0] != 'dialog':
2454
+ if len(p.invoker_bad) < 8:
2455
+ p.invoker_bad.append(
2456
+ f'command="{_cmd}" sobre <{_dst[0]}> (exige <dialog>)')
2457
+ elif _cmd in ('show-popover', 'hide-popover', 'toggle-popover') \
2458
+ and not _dst[1]:
2459
+ if len(p.invoker_bad) < 8:
2460
+ p.invoker_bad.append(
2461
+ f'command="{_cmd}" sobre <{_dst[0]}> sin atributo popover')
2462
+ if p.invoker_bad:
2463
+ add_ej('medium', '4.1.2', 'invoker_command_bad', p.invoker_bad,
2464
+ n=len(p.invoker_bad), example=', '.join(p.invoker_bad[:4]))
2465
+ # select[autofocus] (3.2.1): solo los que llevan script de cambio de
2466
+ # contexto; el atributo solo no cambia nada y no es hallazgo
2467
+ if p.select_auto_focus:
2468
+ add_ej('medium', '3.2.1', 'select_auto_focus', p.select_auto_focus,
2469
+ n=len(p.select_auto_focus), example=', '.join(p.select_auto_focus[:4]),
2470
+ paths=p._finding_paths(p.select_auto_focus_elems))
2471
+ # contexto requerido por rol: se resuelve aquí porque el dueño por
2472
+ # aria-owns puede declararse después que el elemento que salva
2473
+ for _a, _rv, _chain in p._role_ctx_pending:
2474
+ if not p._role_context_satisfied(_a, _rv, _chain) and len(p.role_orphans) < 8:
2475
+ p.role_orphans.append(f'role="{_rv}": {"/".join(_ROLE_PARENTS[_rv])}')
2476
+ p.role_orphan_elems.append(_a)
2477
+ if p.role_orphans:
2478
+ add_ej('medium', '1.3.1', 'role_orphan', p.role_orphans,
2479
+ n=len(p.role_orphans), example=', '.join(p.role_orphans[:4]),
2480
+ paths=p._finding_paths(p.role_orphan_elems))
2481
+ # skips (F89): SOLO enlaces con vocabulario de salto (patrón 3e12e1) cuyo
2482
+ # destino no existe. Una nota al pie rota es otro aviso (y menor): el
2483
+ # mecanismo de bypass ROTO es lo que deja a quien navega atrapado en la
2484
+ # repetitive nav (2.4.1 medium). El navegador decodifica el fragmento
2485
+ # antes de buscar el id (#secci%C3%B3n llega a id="sección") y también
2486
+ # resuelve el destino clásico <a name="…"> (medido en Chromium 147).
2487
+ for _ref, _a in p._skip_hrefs:
2488
+ _target = unquote(_ref)
2489
+ if _target and _target not in p.ids and _target not in p._name_anchors \
2490
+ and len(p.skip_broken) < 8:
2491
+ p.skip_broken.append(f'#{_ref[:24]}')
2492
+ p.skip_broken_elems.append(_a)
2493
+ if p.skip_broken:
2494
+ add_ej('medium', '2.4.1', 'skip_broken', p.skip_broken,
2495
+ n=len(p.skip_broken), example=', '.join(p.skip_broken[:4]),
2496
+ paths=p._finding_paths(p.skip_broken_elems))
2272
2497
  if p.headers_bad:
2273
2498
  examples = [f'headers="{token[:20]}"' for token, _ in p.headers_bad[:5]]
2274
2499
  add_ej('medium', '1.3.1', 'headers_attr_bad', examples,
@@ -2498,6 +2723,39 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
2498
2723
  if overlays:
2499
2724
  res['overlay_widgets'] = overlays
2500
2725
  res['overlay_widgets_note'] = _t(lang, 'overlay_widgets_note')
2726
+
2727
+ # enlace a la declaración de accesibilidad: requisito LEGAL europeo
2728
+ # (Directiva 2016/2102 art. 7 y RD 1112/2018) que nuestras auditorías de
2729
+ # conformidad deben poder verificar, pero NINGÚN criterio WCAG lo dicta —
2730
+ # sale como dato de informe (presente con su href / ausente), jamás
2731
+ # hallazgo. Vocabulario es/en/pt/fr/de/nl/sv/fi/da en ambos órdenes.
2732
+ _stmt = re.compile(
2733
+ r'toegankelijkheidsverklaring|tillg[aä]nglighetsredog[oö]relse|'
2734
+ r'saavutettavuusseloste|'
2735
+ r'(declaraci[oó]n|statement|erkl[aä]rung|declara[cç][aã]o|verklaring|'
2736
+ r'redog[oö]relse|seloste|erkl[eæ]ring)[^a-z0-9]{0,4}'
2737
+ r'(?:(?:de|da|do|di|della|du|of|zur|zum)\s+)?[^a-z0-9]{0,4}'
2738
+ r'(accesibilidad|accessibility|barrierefreiheit|acessibilidade|'
2739
+ r'accesibilidade|toegankelijkheid|tillg[aä]nglighet|saavutettavuus|'
2740
+ r'dostupnost)|'
2741
+ r'(accesibilidad|accessibility|barrierefreiheit|acessibilidade|'
2742
+ r'accesibilidade|toegankelijkheid|tillg[aä]nglighet|saavutettavuus)'
2743
+ r'[^a-z0-9]{0,4}(?:(?:de|da|do|di|della|du|of|zur|zum)\s+)?[^a-z0-9]{0,4}'
2744
+ r'(declaraci[oó]n|statement|erkl[aä]rung|declara[cç][aã]o|verklaring|'
2745
+ r'redog[oö]relse|seloste|erkl[eæ]ring)', re.I)
2746
+ _stmt_links = []
2747
+ for _tag, _a, _txt, _imgs, _hidden in p.controls_raw:
2748
+ if len(_stmt_links) >= 3:
2749
+ break
2750
+ _href = (_a.get('href') or '').strip()
2751
+ _img_alts = ' '.join((ia.get('alt') or '') for ia in (_imgs or []))
2752
+ _full = ' '.join(x for x in (_txt, _img_alts) if x).strip()
2753
+ if _href and not _hidden and _stmt.search(_full or ''):
2754
+ _stmt_links.append({'text': _full[:60], 'href': _href[:120]})
2755
+ res['accessibility_statement'] = {'found': bool(_stmt_links),
2756
+ 'links': _stmt_links}
2757
+ if not _stmt_links:
2758
+ res['accessibility_statement_note'] = _t(lang, 'statement_note')
2501
2759
  return res
2502
2760
 
2503
2761
 
@@ -886,7 +886,7 @@ MODES_BY_CRITERION = {
886
886
  '2.4.7': ('rendered', 'journey'),
887
887
  '2.4.11': ('rendered',),
888
888
  '2.5.8': ('rendered',),
889
- '3.2.1': ('keyboard',),
889
+ '3.2.1': ('keyboard', 'site', 'static'),
890
890
  '3.2.2': ('keyboard',),
891
891
  '3.3.1': ('forms', 'journey'),
892
892
  '3.3.3': ('forms', 'journey'),
@@ -988,6 +988,18 @@ _SIGNAL_CRIT = {
988
988
  'alert_polite': '4.1.2',
989
989
  'headers_attr_bad': '1.3.1',
990
990
  'lang_xml_mismatch': '3.1.2',
991
+ 'nested_interactive': '4.1.2',
992
+ 'invoker_command_bad': '4.1.2',
993
+ 'aria_level_gt6': '1.3.1',
994
+ 'select_auto_focus': '3.2.1',
995
+ 'role_orphan': '1.3.1',
996
+ 'skip_broken': '2.4.1',
997
+ 'docx_fake_list': '1.3.1',
998
+ 'docx_heading_skips': '1.3.1',
999
+ 'docx_generic_link': '2.4.4',
1000
+ 'pdf_table_no_header': '1.3.1',
1001
+ 'pdf_no_heading_tags': '1.3.1',
1002
+ 'pdfua_contradiction': '1.3.1',
991
1003
  'label_in_name': '2.5.3',
992
1004
  'label_orphan': '3.3.2',
993
1005
  'label_vague': '2.4.6',
@@ -32,13 +32,47 @@ _MAX_MEMBER_BYTES = 40 * 1024 * 1024
32
32
  _CRIT = {
33
33
  'docx_no_alt': ('1.1.1', 'high'), 'docx_fake_headings': ('1.3.1', 'medium'),
34
34
  'docx_no_lang': ('3.1.1', 'medium'), 'docx_table_no_header': ('1.3.1', 'low'),
35
+ 'docx_fake_list': ('1.3.1', 'medium'), 'docx_heading_skips': ('1.3.1', 'low'),
36
+ 'docx_generic_link': ('2.4.4', 'medium'),
35
37
  }
36
38
 
39
+ # texto genérico de enlace (2.4.4): la misma familia del HTML, en la voz de
40
+ # los documentos (es/en); cuenta como genérico SOLO repetido (2+), un
41
+ # «descargar» solitario puede ser específico en contexto
42
+ _GENERIC_LINK = {
43
+ 'aquí', 'aquí.', 'pincha aquí', 'pulsa aquí', 'haz clic aquí', 'click here',
44
+ 'here', 'read more', 'leer más', 'más', 'ver más', 'more', 'download',
45
+ 'descargar', 'este enlace', 'this link', 'enlace', 'link', 'detalles',
46
+ 'details', 'más información', 'more information',
47
+ }
48
+ _BULLET = '•●▪◦‣·'
49
+
37
50
 
38
51
  def _t(lang, key):
39
52
  return T.get(lang, T['en'])[key]
40
53
 
41
54
 
55
+ class _OverCap(Exception):
56
+ """Un miembro del ZIP declara más bytes de los que la ingesta admite."""
57
+
58
+
59
+ def _capped_read(z, member):
60
+ """Texto de un miembro del ZIP (None si no existe). El techo de
61
+ descompresión por miembro vive AQUÍ, en la única puerta de lectura del
62
+ cribado: file_size es el declarado del directorio central, el estándar
63
+ contra bombas ZIP de los descompresores serios. Toda lectura pasa por
64
+ esta función (document.xml y styles.xml lo hacían por una comprobación
65
+ previa; la de document.xml.rels la eludía)."""
66
+ try:
67
+ info = z.getinfo(member)
68
+ except KeyError:
69
+ return None
70
+ if info.file_size > _MAX_MEMBER_BYTES:
71
+ raise _OverCap(f'{member} declares {info.file_size} bytes '
72
+ f'(>{_MAX_MEMBER_BYTES}): over the intake cap')
73
+ return z.read(member).decode('utf-8', errors='replace')
74
+
75
+
42
76
  def docx_screen(path, lang='en'):
43
77
  """Cribado de accesibilidad de un .docx (solo stdlib: zipfile + regex XML)."""
44
78
  try:
@@ -47,20 +81,15 @@ def docx_screen(path, lang='en'):
47
81
  return {'error': f'no es un .docx legible: {e}'}
48
82
  if 'word/document.xml' not in z.namelist():
49
83
  return {'error': 'ZIP without word/document.xml (is this really a .docx?)'}
84
+ try:
85
+ return _screen_zip(z, lang, path)
86
+ except _OverCap as e:
87
+ # contenido NO confiable: la ingesta no descomprime sin límite
88
+ return {'error': str(e)}
50
89
 
51
- # techo de descompresión por miembro (revisión externa 2026-11-22): la
52
- # ingesta de contenido NO confiable no puede descomprimir sin límite —
53
- # file_size es el declarado del directorio central, el estándar contra
54
- # bombas ZIP de los descompresores serios
55
- for member in ('word/document.xml', 'word/styles.xml'):
56
- try:
57
- if z.getinfo(member).file_size > _MAX_MEMBER_BYTES:
58
- return {'error': f'{member} declares {z.getinfo(member).file_size} bytes '
59
- f'(>{_MAX_MEMBER_BYTES}): over the intake cap'}
60
- except KeyError:
61
- pass
62
90
 
63
- body = z.read('word/document.xml').decode('utf-8', errors='replace')
91
+ def _screen_zip(z, lang, path):
92
+ body = _capped_read(z, 'word/document.xml')
64
93
 
65
94
  findings = []
66
95
 
@@ -83,12 +112,10 @@ def docx_screen(path, lang='en'):
83
112
 
84
113
  # idioma: w:lang en styles.xml (default del documento)
85
114
  language = None
86
- try:
87
- styles = z.read('word/styles.xml').decode('utf-8', errors='replace')
115
+ styles = _capped_read(z, 'word/styles.xml')
116
+ if styles is not None:
88
117
  m = re.search(r'<w:lang[^>]*w:val="([^"]+)"', styles)
89
118
  language = m.group(1) if m else None
90
- except KeyError:
91
- pass
92
119
  if not language:
93
120
  add('docx_no_lang')
94
121
 
@@ -126,6 +153,113 @@ def docx_screen(path, lang='en'):
126
153
  'issue': _t(lang, 'docx_fake_headings').format(n=fake),
127
154
  'remediation': _t(lang, 'docx_fake_headings_rem')})
128
155
 
156
+ # ── listas falsas: párrafos con viñetas/números TIPOGRAFIADOS en vez de
157
+ # lista de Word (sin w:numPr). Umbral anti-FP: 2+ párrafos CONSECUTIVOS
158
+ # con glifo de viñeta, o 3+ consecutivos numerados con incremento +1
159
+ # (los «1. Enero» de las fechas no incrementan y quedan fuera).
160
+ _doc_paragraphs = re.findall(r'<w:p\b.*?</w:p>|<w:p\b[^>]*/>', body, re.S)
161
+ def _ptext(p):
162
+ return ''.join(re.findall(r'<w:t[^>]*>([^<]*)</w:t>', p)).strip()
163
+ fake_list_groups, _run = 0, []
164
+ def _flush():
165
+ nonlocal _run, fake_list_groups
166
+ n_bul = sum(1 for t in _run if t[0] == 'b')
167
+ if n_bul >= 2:
168
+ fake_list_groups += 1
169
+ elif len(_run) >= 3:
170
+ nums = [t[1] for t in _run if t[0] == 'n']
171
+ if len(nums) == len(_run):
172
+ ok = all(nums[i+1] == nums[i] + 1 for i in range(len(nums)-1))
173
+ if ok and nums[0] in (0, 1):
174
+ fake_list_groups += 1
175
+ _run = []
176
+ for p in _doc_paragraphs:
177
+ if '<w:numPr' in p:
178
+ _flush(); continue
179
+ t = _ptext(p)
180
+ if not t:
181
+ _flush(); continue
182
+ if t[0] in _BULLET:
183
+ _run.append(('b', None)); continue
184
+ m = re.match(r'^(\d{1,3})[.)]\s+\S', t)
185
+ if m:
186
+ _run.append(('n', int(m.group(1)))); continue
187
+ _flush()
188
+ _flush()
189
+ if fake_list_groups:
190
+ findings.append({'severity': 'medium', 'criterion': '1.3.1 (DOCX)',
191
+ 'signal': 'docx_fake_list',
192
+ 'issue': _t(lang, 'docx_fake_list').format(n=fake_list_groups),
193
+ 'remediation': _t(lang, 'docx_fake_list_rem')})
194
+
195
+ # ── saltos de nivel de encabezado: Heading1 → Heading3 aplana la
196
+ # navegación. Niveles por pStyle directo (HeadingN) O por styles.xml
197
+ # (los Word localizados escriben styleIds numéricos cuyo NOMBRE es
198
+ # «heading N» / «Encabezado N» / «Título N»)
199
+ _style_heads = {}
200
+ sx = _capped_read(z, 'word/styles.xml') or ''
201
+ for m in re.finditer(
202
+ r'<w:style [^>]*w:styleId="([^"]+)"[^>]*>.*?'
203
+ r'<w:name w:val="([^"]*)"', sx, re.S):
204
+ mn = re.match(r'(?i)^(?:heading|encabezado|t[ií]tulo|'
205
+ r'berschrift|titre)\s*([1-9])$', m.group(2).strip())
206
+ if mn:
207
+ _style_heads[m.group(1)] = int(mn.group(1))
208
+ levels = []
209
+ for p in _doc_paragraphs:
210
+ ms = re.search(r'<w:pStyle w:val="([^"]+)"', p)
211
+ if not ms:
212
+ continue
213
+ sid = ms.group(1)
214
+ if re.match(r'(?i)^TOC\d|Sumario|TDC', sid):
215
+ continue
216
+ md = re.match(r'(?i)^Heading([1-9])$', sid)
217
+ if md:
218
+ levels.append(int(md.group(1)))
219
+ elif sid in _style_heads:
220
+ levels.append(_style_heads[sid])
221
+ skips = sum(1 for i in range(1, len(levels))
222
+ if levels[i] > levels[i-1] + 1)
223
+ if levels and skips:
224
+ findings.append({'severity': 'low', 'criterion': '1.3.1 (DOCX)',
225
+ 'signal': 'docx_heading_skips',
226
+ 'issue': _t(lang, 'docx_heading_skips').format(n=skips),
227
+ 'remediation': _t(lang, 'docx_heading_skips_rem')})
228
+
229
+ # ── enlaces genéricos: «pincha aquí» (repetido), la URL cruda como
230
+ # texto, o el mismo genérico apuntando a destinos distintos. Relaciones
231
+ # desde word/_rels/document.xml.rels
232
+ rels = {}
233
+ rx = _capped_read(z, 'word/_rels/document.xml.rels') or ''
234
+ for m in re.finditer(r'<Relationship [^>]*Id="([^"]+)"[^>]*Target="([^"]+)"', rx):
235
+ rels[m.group(1)] = m.group(2)
236
+ gen_counts, gen_multi, raw_url, img_links_noalt = {}, 0, 0, 0
237
+ for hl in re.findall(r'<w:hyperlink\b.*?</w:hyperlink>', body, re.S):
238
+ txt = ''.join(re.findall(r'<w:t[^>]*>([^<]*)</w:t>', hl)).strip()
239
+ target = ''
240
+ mr = re.search(r'r:id="([^"]+)"', hl)
241
+ if mr:
242
+ target = rels.get(mr.group(1), '')
243
+ low = txt.lower().rstrip('.…: ')
244
+ if txt and target and txt.replace(' ', '') in target:
245
+ raw_url += 1
246
+ elif low in _GENERIC_LINK:
247
+ if gen_counts.get(low, (0, set()))[0] >= 1:
248
+ gen_multi += 1
249
+ n0, t0 = gen_counts.get(low, (0, set()))
250
+ gen_counts[low] = (n0 + 1, t0 | {target})
251
+ # enlace solo-imagen sin alt (el docPr dentro del hyperlink sin descr)
252
+ if '<w:drawing' in hl or '<a:blip' in hl:
253
+ for dp in re.findall(r'<wp:docPr\b[^>]*>', hl):
254
+ if 'descr=' not in dp or re.search(r'descr="\s*"', dp):
255
+ img_links_noalt += 1
256
+ generic_n = gen_multi + raw_url + img_links_noalt
257
+ if generic_n:
258
+ findings.append({'severity': 'medium', 'criterion': '2.4.4 (DOCX)',
259
+ 'signal': 'docx_generic_link',
260
+ 'issue': _t(lang, 'docx_generic_link').format(n=generic_n),
261
+ 'remediation': _t(lang, 'docx_generic_link_rem')})
262
+
129
263
  order = {'high': 0, 'medium': 1, 'low': 2}
130
264
  findings.sort(key=lambda h: order[h['severity']])
131
265
 
@@ -137,6 +271,7 @@ def docx_screen(path, lang='en'):
137
271
  'mode': 'docx', 'file': str(path).rsplit('/', 1)[-1],
138
272
  'language': language, 'images': len(docprs),
139
273
  'tables': n_tables, 'tables_without_header': tables_missing,
274
+ 'heading_levels': levels,
140
275
  'score': compute_score(findings),
141
276
  'findings': findings,
142
277
  'summary': {s2: sum(1 for h in findings if h['severity'] == s2)