@kinti/a11y-toolkit 5.30.0 → 5.31.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.
@@ -873,12 +873,15 @@ class _Auditor(HTMLParser):
873
873
  self.help_hrefs.add(href.split('#')[0].rstrip('/'))
874
874
  if href and re.search(r'sitemap|site-map|mapa-del-sitio|mapa_web|mapaweb', href, re.I):
875
875
  self.has_sitemap = True
876
- # 2.4.5 vía adicional (4ª pasada): un índice/TOC o bloque de
877
- # relacionados SON formas de encontrar páginas
878
- if href and re.search(
879
- r'(?:^|[/\-_!.])(?:index|indice|indice-de-contenidos|contents|toc|related|relacionados|ver-tambien|see-also)(?:$|[/\-_!.])',
880
- href.split('#')[0].rstrip('/'), re.I):
881
- self.has_index = True
876
+ # 2.4.5 vía adicional (4ª pasada, afinada 7ª): un índice/TOC
877
+ # o bloque de relacionados SON formas de encontrar páginas —
878
+ # por SUBCADENA en el último segmento: los límites de palabra
879
+ # con puntuación dejaban fuera /blog/index.php, /articulos-relacionados
880
+ if href:
881
+ _seg = href.split('#')[0].rstrip('/').split('/')[-1].lower()
882
+ if re.search(r'index|ind[ií]ce|contents|\btoc\b|related|relacionad|ver-tambien|see-also|sobre-este|more-like|similares|etiquetas|tags\b|categorias|categories|archivo|archive',
883
+ _seg):
884
+ self.has_index = True
882
885
  elif tag == 'input':
883
886
  self._field_note()
884
887
  kind = (a.get('type') or 'text').lower()
@@ -1287,10 +1290,12 @@ class _Auditor(HTMLParser):
1287
1290
  _hrole = (a.get('role') or '').strip().lower()
1288
1291
  if _hrole in ('none', 'presentation') or self._in_template:
1289
1292
  pass
1290
- elif _hrole and _hrole != 'heading':
1291
- # CUALQUIER otro rol explícito SUSTITUYE al de heading (la
1292
- # primera regla de ARIA): h2 role=button desaparece de la
1293
- # navegación por encabezados del AT — se registra (1.3.1)
1293
+ elif _hrole and _hrole != 'heading' and _hrole in _ROLES_ARIA:
1294
+ # un rol VALIDO distinto de heading SUSTITUYE al de heading
1295
+ # (la primera regla de ARIA): h2 role=button desaparece de la
1296
+ # navegación por encabezados del AT — se registra (1.3.1).
1297
+ # (7a pasada) un rol DESCONOCIDO (role="bogus heading") el
1298
+ # navegador lo IGNORA y el h2 SIGUE siendo heading: sin aviso
1294
1299
  if not _hidden and len(self.heading_role_removed) < 12:
1295
1300
  _nm = (a.get('aria-label') or '').strip()[:24]
1296
1301
  self.heading_role_removed.append(
@@ -2675,14 +2680,19 @@ def audit_site(url, max_pages=5, timeout=30, lang='en', from_sitemap=True,
2675
2680
  max_pages = max(1, min(20, int(max_pages)))
2676
2681
  import time
2677
2682
  deadline = (time.monotonic() + budget) if budget else None
2683
+ # (7ª pasada) la PRIMERA página también contra su URL FINAL: /deep2 que
2684
+ # redirige a /deep reportaba bajo /deep2 y sus enlaces relativos se
2685
+ # resolvían contra la ruta PEDIDA — el camino equivocado
2686
+ _m0 = {}
2678
2687
  try:
2679
- html_text = _fetch(url, timeout=timeout)
2688
+ html_text = _fetch(url, timeout=timeout, _meta=_m0)
2680
2689
  except _FetchError as e:
2681
2690
  return {'error': _t(lang, e.key).format(**e.fmt)}
2682
2691
  except ValueError as e:
2683
2692
  return {'error': str(e)}
2684
2693
  except Exception as e: # noqa: BLE001
2685
2694
  return {'error': _t(lang, 'fetch_error').format(e=e)}
2695
+ entry_final = ((_m0.get('final_url') or url).split('#')[0]).rstrip('/')
2686
2696
  # el parser jamás tira el crawl entero: una página hostil → informe de
2687
2697
  # error de ESA página y se sigue con la cola
2688
2698
  def _parse_page(html_txt, page_url):
@@ -2693,15 +2703,15 @@ def audit_site(url, max_pages=5, timeout=30, lang='en', from_sitemap=True,
2693
2703
  except Exception as e: # noqa: BLE001
2694
2704
  return pg, {'url': page_url, 'error': _t(lang, 'err_unparseable').format(e=str(e)[:120])}
2695
2705
  return pg, None
2696
- p0, p0_err = _parse_page(html_text, url)
2706
+ p0, p0_err = _parse_page(html_text, entry_final)
2697
2707
  if p0_err:
2698
2708
  return p0_err
2699
- reports = [audit_html(html_text, url, lang=lang)]
2709
+ reports = [audit_html(html_text, entry_final, lang=lang)]
2700
2710
  parsers = [p0]
2701
- seen = {url.split('#')[0].rstrip('/')}
2702
- # discovery: sitemap first (WCAG-EM's own enumeration), links as fallback
2711
+ seen = {url.split('#')[0].rstrip('/'), entry_final}
2712
+ # discovery: sitemap first (WCAG-EM's enumeration), links as fallback
2703
2713
  urls_sm = _urls_sitemap(url, timeout=timeout) if from_sitemap else []
2704
- queue = urls_sm or _internal_links(html_text, url, url)
2714
+ queue = urls_sm or _internal_links(html_text, entry_final, url)
2705
2715
  while queue and len(reports) < max_pages:
2706
2716
  if deadline is not None and time.monotonic() >= deadline:
2707
2717
  break # budget exhausted: partial, not eternal
@@ -308,6 +308,11 @@ def evaluate(submission, directory='corpus', submission_name='submission'):
308
308
  additional.append({'case_id': cid, 'additional_criteria': extra})
309
309
  n_mut = sum(1 for c in entries.values() if c['kind'] == 'mutant')
310
310
  n_pla = len(entries) - n_mut
311
+ # (7a pasada) lo que decide es la ENTREGA, no el corpus: omitir los
312
+ # placebos del submission dejaba n_pla>0 (vienen del directorio) y la
313
+ # evaluacion se declaraba completa con un claim de FP infalsable
314
+ pla_scored = sum(1 for cid, c in entries.items()
315
+ if c['kind'] == 'placebo' and cid in by_id)
311
316
  out = {
312
317
  'format': EVAL_FORMAT,
313
318
  'submission_name': submission_name,
@@ -321,7 +326,8 @@ def evaluate(submission, directory='corpus', submission_name='submission'):
321
326
  **({'incomplete': True,
322
327
  'incomplete_reason': 'no control (placebo) pages in the submission: '
323
328
  'the false-positive claim cannot be evaluated'}
324
- if n_pla == 0 else {'incomplete': False}),
329
+ if pla_scored == 0 else {'incomplete': False}),
330
+ 'control_pages_scored': pla_scored,
325
331
  'additional_findings_on_mutants': {'count': len(additional),
326
332
  'note': 'reported, not scored: only '
327
333
  'placebo flags are false '
@@ -660,6 +660,9 @@ _JS = r'''(maxEj) => {
660
660
  }
661
661
  for (const r of roots) {
662
662
  for (const el of r.querySelectorAll('[aria-hidden="true"]')) {
663
+ // (7a pasada) inert saca el subarbol de la interaccion: un boton
664
+ // dentro de inert aria-hidden NO es enfocable aunque el atributo siga
665
+ if (el.closest('[inert]')) continue;
663
666
  if (el.matches(INTER)) {
664
667
  if (el.getAttribute('tabindex') !== '-1') out.ariaHidden.push(path(el));
665
668
  } else if ([...(el.querySelectorAll(INTER) || [])]
@@ -1361,6 +1364,15 @@ _JS_SPACING = r'''() => {
1361
1364
  const modes = [s.overflow, s.overflowY, s.overflowX];
1362
1365
  if (modes.includes('hidden') || modes.includes('clip')) {
1363
1366
  const rb = n.getBoundingClientRect(), re = el.getBoundingClientRect();
1367
+ if (n === el) {
1368
+ // (7a pasada) el elemento recortado por SU PROPIA caja (clip no
1369
+ // crea contenedor de scroll: scrollHeight no sirve): un Range
1370
+ // mide el TEXTO real — comparar la caja consigo misma daba falso
1371
+ const rg = document.createRange();
1372
+ rg.selectNodeContents(el);
1373
+ const rt = rg.getBoundingClientRect();
1374
+ return rt.bottom > rb.bottom + 3 || rt.right > rb.right + 3;
1375
+ }
1364
1376
  if (re.bottom > rb.bottom + 3 || re.right > rb.right + 3) return true;
1365
1377
  return false; // ancestro recortante y el elemento dentro: no clip
1366
1378
  }
@@ -1668,9 +1680,13 @@ def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, br
1668
1680
  _advisory = sel.evaluate(
1669
1681
  'el => { const db = el.getAttribute("aria-describedby");'
1670
1682
  ' if (!db) return false;'
1683
+ ' const AVISO = /naviga|ir[áa]s|ir a|go(es)? to|take(s)? you|'
1684
+ 'p[áa]gina|page|redirect|redirig|cambiar[áa]|change|jump|salta|'
1685
+ 'send|llevar|abrir|open|visit|visita/i;'
1671
1686
  ' return db.split(/\\s+/).some(id => {'
1672
1687
  ' const r = document.getElementById(id);'
1673
- ' return r && (r.innerText || "").trim(); }); }')
1688
+ ' const t = r ? (r.innerText || "").trim() : "";'
1689
+ ' return t && AVISO.test(t); }); }')
1674
1690
  _name = (sel.get_attribute('aria-label')
1675
1691
  or sel.get_attribute('id') or 'select')[:40]
1676
1692
  try:
@@ -2143,16 +2159,15 @@ def audit_dom_url(url, timeout=45, lang='en', auth_state=None, browser='auto', c
2143
2159
  finally:
2144
2160
  close_page()
2145
2161
  _merge_iframes(data)
2146
- report_out = audit_dom(data, url, lang=lang, color_scheme=color_scheme)
2147
- # verdad de navegación (revisión externa, 4ª pasada): un 404 con HTML
2148
- # puntuaba 100 como si fuera la página pedida — el informe declara el
2149
- # estado HTTP y la URL FINAL para que el consumidor distinga
2150
- final_url = page_url_final or url
2162
+ # (7ª pasada) el informe ES de la página final: url=/signin cuando
2163
+ # /account redirigió — antes conservaba /account y solo añadía la nota
2164
+ final_url = (page_url_final or url).split('#')[0]
2165
+ report_out = audit_dom(data, final_url, lang=lang, color_scheme=color_scheme)
2151
2166
  try:
2152
2167
  _st = _resp.status if _resp is not None else None
2153
2168
  except Exception: # noqa: BLE001 — respuesta ya consumida
2154
2169
  _st = None
2155
- if final_url.split('#')[0] != url.split('#')[0]:
2170
+ if final_url != url.split('#')[0]:
2156
2171
  report_out['requested_url'] = url
2157
2172
  report_out['redirect_note'] = (
2158
2173
  'la URL pedida redirigió: el informe es de la página FINAL'
@@ -2161,12 +2176,18 @@ def audit_dom_url(url, timeout=45, lang='en', auth_state=None, browser='auto', c
2161
2176
  if _st:
2162
2177
  report_out['http_status'] = _st
2163
2178
  if _st >= 400:
2164
- report_out['http_error_note'] = (
2165
- f'la página respondió HTTP {_st}: esto es una respuesta de '
2166
- 'error, no la página pedida'
2167
- if lang == 'es' else
2168
- f'the page answered HTTP {_st}: this is an error response, '
2169
- 'not the requested page')
2179
+ # (7ª pasada) el falso verde HTTP: la nota informaba pero budget,
2180
+ # evidencia y CI seguían aceptando el resultado. Error explícito
2181
+ # machine-readable — las capas de arriba lo rechazan por contrato
2182
+ report_out['error'] = (
2183
+ f'HTTP {_st}: this is an error response, not the requested '
2184
+ 'page — the content was still audited and is in this report, '
2185
+ 'but no gate should pass on it'
2186
+ if lang == 'en' else
2187
+ f'HTTP {_st}: respuesta de error, no la página pedida — el '
2188
+ 'contenido se auditó igualmente y va en este informe, pero '
2189
+ 'ningún gate debe pasar con esto')
2190
+ report_out['http_error_note'] = report_out['error']
2170
2191
  return report_out
2171
2192
 
2172
2193
 
@@ -2375,7 +2396,7 @@ def contrast_walk(url, max_walk=400, max_sample=24, dark=False,
2375
2396
  _verdicts(entries)
2376
2397
  return entries, skipped, unparsed
2377
2398
 
2378
- def _summarize(entries, skipped):
2399
+ def _summarize(entries, skipped, unparsed_n=0):
2379
2400
  fails = [e for e in entries if e['verdict'] == 'fail']
2380
2401
  worst = min((e for e in entries if e['ratio'] is not None),
2381
2402
  key=lambda e: e['ratio'], default=None)
@@ -2385,7 +2406,7 @@ def contrast_walk(url, max_walk=400, max_sample=24, dark=False,
2385
2406
  'fails_4_5_normal_text': sum(1 for e in fails if e['threshold'] >= 4.5),
2386
2407
  'fails_3_0_large_text': sum(1 for e in fails if e['threshold'] < 4.5),
2387
2408
  'translucent_text_skipped': skipped,
2388
- 'unparsed_colors': unparsed + (locals().get('_unp_d') or 0),
2409
+ 'unparsed_colors': unparsed_n,
2389
2410
  'pixel_sampled': sum(1 for e in entries if e['pixel_sampled']),
2390
2411
  'worst_ratio': worst['ratio'] if worst else None,
2391
2412
  'worst_element': worst['path'] if worst else None}
@@ -2409,7 +2430,7 @@ def contrast_walk(url, max_walk=400, max_sample=24, dark=False,
2409
2430
  report = {'mode': 'contrast-walk', 'url': url, 'scheme': 'light',
2410
2431
  'checked': len(entries),
2411
2432
  'elements': entries,
2412
- 'summary': _summarize(entries, skipped)}
2433
+ 'summary': _summarize(entries, skipped, unparsed)}
2413
2434
 
2414
2435
  # suggestions for the worst flat-background fails (pixel zones have no
2415
2436
  # single background to suggest against — honest skip)
@@ -2425,7 +2446,7 @@ def contrast_walk(url, max_walk=400, max_sample=24, dark=False,
2425
2446
  entries_d, skipped_d, _unp_d = _run('dark')
2426
2447
  report['dark'] = {'scheme': 'dark', 'checked': len(entries_d),
2427
2448
  'elements': entries_d,
2428
- 'summary': _summarize(entries_d, skipped_d)}
2449
+ 'summary': _summarize(entries_d, skipped_d, _unp_d)}
2429
2450
  light_fails = {e['path'] for e in entries if e['verdict'] == 'fail'}
2430
2451
  dark_fails = {e['path'] for e in entries_d if e['verdict'] == 'fail'}
2431
2452
  report['dark_delta'] = {
@@ -84,11 +84,17 @@ def _test_dialogs(page, findings, lang, cap=3):
84
84
  n = min(loc.count(), cap)
85
85
  _inside_js = ('(dlg) => { const a = document.activeElement;'
86
86
  ' return dlg === a || dlg.contains(a); }')
87
+ # (7a pasada) TODOS los handles ANTES de tocar nada: cerrar el primer
88
+ # dialogo cambiaba los indices de la lista visible y el segundo quedaba
89
+ # SIN PROBAR
90
+ handles = []
87
91
  for i in range(n):
88
92
  try:
89
- d = loc.nth(i).element_handle()
93
+ h = loc.nth(i).element_handle()
90
94
  except Exception: # noqa: BLE001
91
- continue
95
+ h = None
96
+ handles.append(h)
97
+ for d in handles:
92
98
  if d is None:
93
99
  continue
94
100
  try:
@@ -45,8 +45,38 @@ _STREAM_CAP = 20_000_000 # 20 MB por stream descomprimido
45
45
  _STREAM_BUDGET = 120_000_000 # 120 MB en total entre todos los streams
46
46
 
47
47
 
48
+ def _decode_filters(chunk, filters_declared):
49
+ """(7a pasada) interpreta los /Filter DECLARADOS en el diccionario del
50
+ stream: FlateDecode (zlib), ASCII85Decode (base64.a85decode, adobe) y
51
+ la CADENA ASCII85->Flate que Poppler produce — antes solo se probaba
52
+ Flate a ciegas y el contenido sin comprimir o tras ASCII85 se perdía.
53
+ Sin /Filter: los bytes van tal cual (PDF legítimo)."""
54
+ import base64
55
+ for f in filters_declared:
56
+ f = f.strip().lstrip(b'/') # el findall captura SIN la barra inicial
57
+ if f == b'FlateDecode':
58
+ try:
59
+ d = zlib.decompressobj()
60
+ chunk = d.decompress(chunk, _STREAM_CAP)
61
+ except Exception: # noqa: BLE001
62
+ return None
63
+ elif f == b'ASCII85Decode':
64
+ try:
65
+ c = chunk.strip()
66
+ if c.endswith(b'~>'):
67
+ c = c[:-2]
68
+ chunk = base64.a85decode(c)
69
+ except Exception: # noqa: BLE001
70
+ return None
71
+ # RunLength, LZW, DCT...: fuera de stdlib — el stream se declara
72
+ # no convertible y se cuenta como tal, jamás como texto medible
73
+ else:
74
+ return None
75
+ return chunk
76
+
77
+
48
78
  def _uncompressed_streams(data, limit=60):
49
- """Los streams FlateDecode, descomprimidos (zlib es stdlib) — ahí viven
79
+ """Los streams decodificados SEGUN SUS /Filter declarados — ahí viven
50
80
  el XMP, el contenido y buena parte de la estructura."""
51
81
  out, total = [], 0
52
82
  for m in re.finditer(rb'stream\r?\n', data):
@@ -57,10 +87,16 @@ def _uncompressed_streams(data, limit=60):
57
87
  if end == -1:
58
88
  continue
59
89
  chunk = data[start:end].rstrip(b'\r\n')
60
- try:
61
- d = zlib.decompressobj()
62
- dec = d.decompress(chunk, _STREAM_CAP) # bomba: techo por stream
63
- except Exception: # noqa: BLE001
90
+ # diccionario ANTES del stream: manda el /Filter del dict INMEDIATO
91
+ # (el ÚLTIMO del head — la ventana puede traer dicts de objetos
92
+ # vecinos y aplicar Flate DOS veces mataba streams perfectos)
93
+ head = data[max(0, m.start() - 800):m.start()]
94
+ filters_declared = []
95
+ mu = re.findall(rb'/Filter\s*(\[[^\]]*\]|/\w+)', head)
96
+ if mu:
97
+ filters_declared = re.findall(rb'/\w+', mu[-1])
98
+ dec = _decode_filters(chunk, filters_declared) if filters_declared else chunk
99
+ if dec is None:
64
100
  continue
65
101
  out.append(dec)
66
102
  total += len(dec)
@@ -97,7 +97,7 @@ try:
97
97
  except ImportError:
98
98
  ARIALIVE_JS = None # repo checkout: read the file
99
99
 
100
- VERSION = '5.30.0'
100
+ VERSION = '5.31.0'
101
101
 
102
102
  # Params renombrados a inglés en 5.11.0; se aceptan los nombres previos.
103
103
  PARAM_ALIASES = {
@@ -209,6 +209,10 @@ TOOLS = [
209
209
  'focus indicator heuristic (2.4.7), plus rendered versions of the '
210
210
  'static checks (alt, accessible names, labels, headings, lang/title, '
211
211
  'tabindex, aria-hidden, captions, tables). Findings include remediation. '
212
+ 'HTTP contract: the report carries http_status, its url is the FINAL '
213
+ 'page after redirects (requested_url keeps the original), and a 4xx/5xx '
214
+ 'response is returned as an error — the audited content still rides '
215
+ 'along, but no CI gate can pass on an error response. '
212
216
  'Requires playwright: pip install playwright && playwright install '
213
217
  'chromium.'),
214
218
  'inputSchema': {'type': 'object', 'properties': {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kinti/a11y-toolkit",
3
- "version": "5.30.0",
3
+ "version": "5.31.0",
4
4
  "mcpName": "io.github.kinti/a11y-toolkit",
5
5
  "description": "Zero-dependency WCAG 2.2 accessibility engine (37 MCP tools + CLI): audits, contrast fixing, SHA-256-sealed evidence packs, SARIF, EARL/ACT, CI ratchet. Self-contained: the pure-stdlib Python engine ships inside and runs via python3 \u2014 no downloads, no installs.",
6
6
  "license": "MIT",