@kinti/a11y-toolkit 5.29.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.
@@ -75,7 +75,20 @@ def init(audit):
75
75
 
76
76
  def compare(budget, audit, today=None):
77
77
  """Presupuesto vs informe actual → veredicto ok/bloqueado con el detalle."""
78
- pages = audit.get('reports') if 'reports' in audit else [audit]
78
+ # un informe FALLIDO no es evidencia de nada (revisión externa 2026-11-22:
79
+ # con {'error': …} current quedaba vacío, TODO el baseline salía
80
+ # «resolved» y el gate día verde). Sin páginas usables → error; las
81
+ # sub-páginas fallidas de un crawl se excluyen y se declaran.
82
+ if not isinstance(audit, dict) or audit.get('error'):
83
+ return {'error': 'the audit report failed (error field) — a failed run '
84
+ 'is not evidence that findings were fixed'}
85
+ pages = audit.get('reports') if isinstance(audit.get('reports'), list) else [audit]
86
+ failed = [pg.get('url') for pg in pages
87
+ if isinstance(pg, dict) and pg.get('error')]
88
+ pages = [pg for pg in pages if not (isinstance(pg, dict) and pg.get('error'))]
89
+ if not pages:
90
+ return {'error': f'all {len(failed)} pages of the report failed — '
91
+ 'nothing to compare'}
79
92
  base = {normalize_signal(s) for s in budget.get('signals', [])}
80
93
  blocking = set(budget.get('blocking', ['high', 'medium']))
81
94
  current = {}
@@ -98,6 +111,7 @@ def compare(budget, audit, today=None):
98
111
  'new': new,
99
112
  'new_blocking': new_blocking,
100
113
  'resolved': resolved,
114
+ **({'pages_failed': failed} if failed else {}),
101
115
  'summary': {
102
116
  'baseline': len(base),
103
117
  'current': len(current),
@@ -258,6 +272,12 @@ def main(argv):
258
272
  from .a11yaudit import audit_url
259
273
  report = audit_url(a.url)
260
274
  verdict = compare(budget, report)
275
+ if 'error' in verdict:
276
+ # informe fallido/malformado: error de EJECUCIÓN (exit 1), jamás un
277
+ # verde — el gate presupuestario no puede declarar resuelto lo que no
278
+ # llegó a mirar
279
+ print(json.dumps(verdict, ensure_ascii=False, indent=1))
280
+ return 1
261
281
  print(json.dumps(verdict, ensure_ascii=False, indent=1))
262
282
  return 0 if verdict['ok'] else 2
263
283
 
@@ -308,7 +308,12 @@ 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
- return {
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)
316
+ out = {
312
317
  'format': EVAL_FORMAT,
313
318
  'submission_name': submission_name,
314
319
  'mutants': n_mut, 'killed': len(killed),
@@ -316,6 +321,13 @@ def evaluate(submission, directory='corpus', submission_name='submission'):
316
321
  'missed_detail': missed,
317
322
  'control_pages': n_pla,
318
323
  'false_positives': fps,
324
+ # (4ª pasada) sin páginas control, «cero falsos positivos» es
325
+ # infalsable — la evaluación se declara incompleta, no limpia
326
+ **({'incomplete': True,
327
+ 'incomplete_reason': 'no control (placebo) pages in the submission: '
328
+ 'the false-positive claim cannot be evaluated'}
329
+ if pla_scored == 0 else {'incomplete': False}),
330
+ 'control_pages_scored': pla_scored,
319
331
  'additional_findings_on_mutants': {'count': len(additional),
320
332
  'note': 'reported, not scored: only '
321
333
  'placebo flags are false '
@@ -327,6 +339,7 @@ def evaluate(submission, directory='corpus', submission_name='submission'):
327
339
  'cases_without_submission': [cid for cid in sorted(entries)
328
340
  if cid not in by_id][:10],
329
341
  }
342
+ return out
330
343
 
331
344
 
332
345
  def reference(directory='corpus'):
@@ -826,6 +826,76 @@ RENDERED_ONLY = frozenset({
826
826
  '3.3.1', '3.3.3', '4.1.3',
827
827
  })
828
828
 
829
+ # Criterio A/AA → modos de informe capaces de emitirle señal. El pack de
830
+ # evidencia deriva not-run/not-flagged de AQUÍ: «not-flagged» solo cuando la
831
+ # muestra incluye un informe ACEPTADO (sin 'error') de un modo que puede
832
+ # emitir la señal del criterio — la revisión externa (2026-11-22) cazó el pack
833
+ # declarando 34 criterios not-flagged con CERO informes, y un informe dom
834
+ # limpiando 2.1.2/3.3.1/3.3.3 que solo prueban a11y_keyboard/a11y_forms.
835
+ # Modos: static = a11y_audit_url/html (audit_dom re-ejecuta ese repertorio
836
+ # sobre el DOM vivo, por eso 'rendered' acompaña donde corresponde); site =
837
+ # audit --pages (crawl: señales a nivel de sitio); rendered = a11y_audit_dom;
838
+ # el resto, la herramienta especializada de cada familia. journey_* cubre lo
839
+ # que el veredicto de trayecto puede testimoniar. vtt/pdf/docx quedan fuera:
840
+ # son otros targets (documentos), no muestras web.
841
+ # El test de invariantes re-deriva esta tabla de los puntos de emisión.
842
+ MODES_BY_CRITERION = {
843
+ # señales estáticas que audit_dom re-ejecuta sobre el DOM vivo
844
+ '1.1.1': ('static', 'site', 'rendered'),
845
+ '1.2.2': ('static', 'site', 'rendered'),
846
+ '1.3.1': ('static', 'site', 'rendered', 'scroll', 'journey'),
847
+ '1.4.4': ('static', 'site', 'rendered', 'journey'),
848
+ '2.2.1': ('static', 'site', 'rendered', 'journey'),
849
+ '2.4.1': ('static', 'site', 'rendered', 'keyboard', 'journey'),
850
+ '2.4.2': ('static', 'site', 'rendered'),
851
+ '2.4.3': ('static', 'site', 'rendered', 'scroll', 'journey'),
852
+ '3.1.1': ('static', 'site', 'rendered'),
853
+ '3.3.2': ('static', 'site', 'rendered', 'journey'),
854
+ '4.1.2': ('static', 'site', 'rendered', 'journey'),
855
+ # señales SOLO estáticas (audit_dom no las re-emite)
856
+ '1.2.3': ('static', 'site'),
857
+ '1.3.3': ('static', 'site'),
858
+ '1.3.4': ('static', 'site'),
859
+ '1.3.5': ('static', 'site'),
860
+ '1.4.2': ('static', 'site'),
861
+ '1.4.5': ('static', 'site'),
862
+ '2.1.1': ('static', 'site', 'journey'),
863
+ '2.1.4': ('static', 'site'),
864
+ '2.4.4': ('static', 'site', 'journey'),
865
+ '2.4.6': ('static', 'site', 'journey'),
866
+ '2.5.1': ('static', 'site'),
867
+ '2.5.2': ('static', 'site'),
868
+ '2.5.3': ('static', 'site'),
869
+ '2.5.4': ('static', 'site'),
870
+ '2.5.7': ('static', 'site', 'journey'),
871
+ '3.1.2': ('static', 'site'),
872
+ '3.3.4': ('static', 'site'),
873
+ '3.3.8': ('static', 'site'),
874
+ '4.1.3': ('static', 'site', 'scroll', 'journey'),
875
+ # 1.4.12: !important inline (static) + clipping real (rendered)
876
+ '1.4.12': ('static', 'site', 'rendered'),
877
+ # 2.2.2: marquee/anim estáticas + motion_moving (rendered) + pasadas propias
878
+ '2.2.2': ('static', 'site', 'rendered', 'reduced-motion', 'scroll'),
879
+ # señales de modo exclusivo — un informe dom NO las limpia
880
+ '1.3.2': ('rendered',),
881
+ '1.4.1': ('rendered',),
882
+ '1.4.3': ('rendered', 'forced-colors'),
883
+ '1.4.10': ('reflow', 'journey'),
884
+ '1.4.13': ('hover', 'journey'),
885
+ '2.1.2': ('keyboard', 'journey'),
886
+ '2.4.7': ('rendered', 'journey'),
887
+ '2.4.11': ('rendered',),
888
+ '2.5.8': ('rendered',),
889
+ '3.2.1': ('keyboard',),
890
+ '3.2.2': ('keyboard',),
891
+ '3.3.1': ('forms', 'journey'),
892
+ '3.3.3': ('forms', 'journey'),
893
+ # señales a nivel de sitio (solo el crawl las ve)
894
+ '2.4.5': ('site',),
895
+ '3.2.3': ('site',),
896
+ '3.2.6': ('site',),
897
+ }
898
+
829
899
 
830
900
 
831
901
  # Señal del motor → criterio WCAG que alimenta. Derivado empíricamente de los
@@ -872,10 +942,12 @@ _SIGNAL_CRIT = {
872
942
  'focus_navigates': '3.2.1',
873
943
  'focus_not_focusable': '2.4.7',
874
944
  'focus_obscured': '2.4.11',
945
+ 'focus_static_indicator': '2.4.7',
875
946
  'forced_colors_svg': '1.4.3',
876
947
  'form_error_missing': '3.3.1',
877
948
  'form_error_no_suggestion': '3.3.3',
878
949
  'form_navigated': '3.3.1',
950
+ 'form_untestable': '3.3.1',
879
951
  'generic_link': '2.4.4',
880
952
  'gesture_no_click': '2.5.1',
881
953
  'heading_quality': '2.4.6',
@@ -60,14 +60,20 @@ _LAUNCHERS = {
60
60
 
61
61
 
62
62
  # firma estable del elemento enfocado — la MISMA doctrina de claves que el
63
- # snapshot (#id o tag:nombre:href); compartida con a11ytrace
63
+ # snapshot (#id o tag:nombre:href); compartida con a11ytrace.
64
+ # PRIVACIDAD (revisión externa 2026-11-22): JAMÁS el value de campos
65
+ # editables — input.value llevaba al JSON exportado (snapshot/trace/engines)
66
+ # lo que la persona hubiera tecleado, contraseñas incluidas. Solo inputs-botón
67
+ # (submit/button/reset), cuyo value es el rótulo estático de la página — la
68
+ # misma regla que ya seguía el COLLECTOR.
64
69
  FOCUS_KEY_JS = r'''() => {
65
70
  const el = document.activeElement;
66
71
  if (!el || el === document.body) return null;
67
72
  const link = el.closest('a[href]');
68
73
  let name = el.getAttribute('aria-label') || (el.innerText || '')
69
74
  .replace(/\s+/g,' ').trim() || el.getAttribute('title') ||
70
- (el.tagName==='INPUT' && el.value) || '';
75
+ (el.tagName==='INPUT' && ['submit','button','reset'].includes(el.type)
76
+ ? el.value : '') || '';
71
77
  return el.id ? '#'+el.id : el.tagName.toLowerCase()+':'+name.slice(0,60).toLowerCase()+
72
78
  (link ? ':'+link.getAttribute('href') : '');
73
79
  }'''
@@ -76,8 +82,8 @@ FOCUS_KEY_JS = r'''() => {
76
82
  # distintos pueden compartir firma (dos botones-icono sin name, un Edit por
77
83
  # fila) y la firma repetida truncaba el pase a la segunda aparición. El primer
78
84
  # enfocable se marca con un data-attribute (token estático) y la vuelta se
79
- # detecta cuando el ACTIVO es ese mismo elemento; la firma del primero queda
80
- # como stop secundario de refuerzo y el cap de iteraciones como tercero.
85
+ # detecta cuando el ACTIVO es ese mismo elemento; el cap de iteraciones es la
86
+ # red de seguridad si el JS del sitio borra el sello.
81
87
  _WALK_STAMP_JS = r'''() => {
82
88
  const el = document.activeElement;
83
89
  if (!el || el === document.body) return false;
@@ -98,8 +104,11 @@ _WALK_CLEAN_JS = r'''() => {
98
104
 
99
105
  def _walk_focus(page, cap):
100
106
  """Tab walk → focus order (list of signatures). Stops on wrap by element
101
- identity (the stamped first focusable), secondarily on the first
102
- signature repeating, and on the iteration cap."""
107
+ identity (the stamped first focusable) and on the iteration cap. The old
108
+ secondary «signature repeats» stop TRUNCATED the walk at the second of
109
+ two same-named controls (Edit, Edit, Continue → one stop): a repeated
110
+ signature is a duplicate control, not a wrap — only the stamped node (or
111
+ the cap, if the site's JS eats the stamp) closes the circle."""
103
112
  order = []
104
113
  page.keyboard.press('Tab')
105
114
  if not page.evaluate(_WALK_STAMP_JS):
@@ -113,7 +122,7 @@ def _walk_focus(page, cap):
113
122
  info = page.evaluate(FOCUS_KEY_JS)
114
123
  if info is None:
115
124
  break
116
- if page.evaluate(_WALK_IS_STAMPED_JS) or info == first:
125
+ if page.evaluate(_WALK_IS_STAMPED_JS):
117
126
  break # focus returned to the FIRST element itself: full circle
118
127
  order.append(info)
119
128
  try:
@@ -184,10 +193,14 @@ def diff(a, b, lang='en'):
184
193
  renamed.append({'key': k, 'before': ea[k]['name'], 'after': eb[k]['name']})
185
194
 
186
195
  oa, ob = a['focus_order'], b['focus_order']
187
- common_a = [x for x in oa if x in set(ob)]
188
- common_b = [x for x in ob if x in set(oa)]
189
- focus_removed = [x for x in oa if x not in set(ob)] # perdió el Tab: regresión real
190
- focus_added = [x for x in ob if x not in set(oa)] # nuevo enfocable: cambio, no pérdida
196
+ # conjuntos UNA vez (revisión externa 2026-11-22): rebuilds por parada
197
+ # eran O(a·b) — 646 ms con 4.800 stops; ahora O(a+b) y el orden de las
198
+ # listas resultantes se conserva igual (filtro sobre la lista original)
199
+ sa, sb = set(oa), set(ob)
200
+ common_a = [x for x in oa if x in sb]
201
+ common_b = [x for x in ob if x in sa]
202
+ focus_removed = [x for x in oa if x not in sb] # perdió el Tab: regresión real
203
+ focus_added = [x for x in ob if x not in sa] # nuevo enfocable: cambio, no pérdida
191
204
  focus_changed = common_a != common_b
192
205
  first_divergence = next((i for i, (x, y) in enumerate(zip(common_a, common_b)) if x != y), None)
193
206
 
@@ -52,13 +52,19 @@ def _recheck_static(url, findings, timeout=30, lang='en'):
52
52
  return verified, None
53
53
 
54
54
 
55
- def _recheck_rendered(url, findings, timeout=45, lang='en'):
56
- """Re-run the rendered audit and check which findings still fire."""
55
+ def _recheck_rendered(url, findings, timeout=45, lang='en', color_scheme=None):
56
+ """Re-run the rendered audit and check which findings still fire.
57
+
58
+ Repite las CONDICIONES del informe original (revisión externa
59
+ 2026-11-22): un informe auditado en dark mode reverificado en claro
60
+ «rechazaba» contrast_fail reales — 88→100 con la página intacta. Sin la
61
+ condición registrada, nada se rechaza: not-rechecked."""
57
62
  try:
58
63
  from .a11ydom import audit_dom_url
59
64
  except ImportError:
60
65
  return findings, "Playwright not installed"
61
- fresh_report = audit_dom_url(url, timeout=timeout, lang=lang)
66
+ fresh_report = audit_dom_url(url, timeout=timeout, lang=lang,
67
+ color_scheme=color_scheme or 'light')
62
68
  if 'error' in fresh_report:
63
69
  return findings, fresh_report['error']
64
70
  fresh_signals = {h['signal'] for h in fresh_report.get('findings', [])}
@@ -113,7 +119,24 @@ def disprove(url, report=None, timeout=30, lang='en'):
113
119
  if mode_name in ('static', 'site'):
114
120
  verified, err = _recheck_static(url, findings, timeout=timeout, lang=lang)
115
121
  elif mode_name == 'rendered':
116
- verified, err = _recheck_rendered(url, findings, timeout=timeout, lang=lang)
122
+ # condición necesaria: el esquema de color bajo el que se auditó. Sin
123
+ # él no se reverifica (rechazar un contrast_fail de dark mode tras
124
+ # mirar la página en claro es exactamente el falso «arreglado» que
125
+ # este patrón existe para impedir)
126
+ scheme = report.get('color_scheme') or report.get('scheme')
127
+ if scheme not in ('light', 'dark'):
128
+ res = dict(report)
129
+ res['findings'] = [dict(h, disprover_status='not-rechecked') for h in findings]
130
+ res['disprover'] = {
131
+ 'executed': False,
132
+ 'reason': ('the rendered report does not record its color_scheme '
133
+ '— re-verifying under a different condition could reject '
134
+ 'real findings (a dark-only contrast fail looks fixed '
135
+ 'under light); re-audit with a11y_audit_dom and disprove '
136
+ 'THAT report')}
137
+ return res
138
+ verified, err = _recheck_rendered(url, findings, timeout=timeout, lang=lang,
139
+ color_scheme=scheme)
117
140
  else:
118
141
  # no re-verifier for this mode: report not-rechecked, never a proxy
119
142
  # audit (a keyboard finding must not vanish just because the wrong
@@ -25,6 +25,10 @@ from . import a11yi18n
25
25
 
26
26
  T = a11yi18n.pair('docx') # locales/<lang>.json — community-editable
27
27
 
28
+ # techo de ingesta por miembro ZIP: 40 MB descomprimidos — un .docx legítimo
29
+ # no llega ni de lejos; una bomba ZIP sí
30
+ _MAX_MEMBER_BYTES = 40 * 1024 * 1024
31
+
28
32
  _CRIT = {
29
33
  'docx_no_alt': ('1.1.1', 'high'), 'docx_fake_headings': ('1.3.1', 'medium'),
30
34
  'docx_no_lang': ('3.1.1', 'medium'), 'docx_table_no_header': ('1.3.1', 'low'),
@@ -44,6 +48,18 @@ def docx_screen(path, lang='en'):
44
48
  if 'word/document.xml' not in z.namelist():
45
49
  return {'error': 'ZIP without word/document.xml (is this really a .docx?)'}
46
50
 
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
+
47
63
  body = z.read('word/document.xml').decode('utf-8', errors='replace')
48
64
 
49
65
  findings = []
@@ -76,10 +92,18 @@ def docx_screen(path, lang='en'):
76
92
  if not language:
77
93
  add('docx_no_lang')
78
94
 
79
- # tablas sin fila de encabezado (tblHeader)
95
+ # tablas sin fila de encabezado (tblHeader) — POR TABLA (5ª pasada: el
96
+ # encabezado de la primera tapaba la falta de la segunda con un conteo
97
+ # global, y <w:tblHeader w:val="true"/> —con atributos— no casaba con el
98
+ # regex de elemento vacío)
80
99
  n_tables = len(re.findall(r'<w:tbl>', body))
81
- n_tblheader = len(re.findall(r'<w:tblHeader\s*/?>', body))
82
- if n_tables and not n_tblheader:
100
+ tables_missing = 0
101
+ for tbl in re.findall(r'<w:tbl>.*?</w:tbl>', body, re.S):
102
+ marked = [m for m in re.findall(r'<w:tblHeader\b[^>]*/?>', tbl)
103
+ if not re.search(r'w:val="(?:0|false|off)"', m, re.I)]
104
+ if not marked:
105
+ tables_missing += 1
106
+ if n_tables and tables_missing:
83
107
  add('docx_table_no_header')
84
108
 
85
109
  # falsos encabezados: párrafo todo-bold + tamaño grande sin estilo Heading
@@ -112,7 +136,7 @@ def docx_screen(path, lang='en'):
112
136
  return {
113
137
  'mode': 'docx', 'file': str(path).rsplit('/', 1)[-1],
114
138
  'language': language, 'images': len(docprs),
115
- 'tables': n_tables, 'tables_with_header': n_tblheader,
139
+ 'tables': n_tables, 'tables_without_header': tables_missing,
116
140
  'score': compute_score(findings),
117
141
  'findings': findings,
118
142
  'summary': {s2: sum(1 for h in findings if h['severity'] == s2)