@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.
Files changed (44) hide show
  1. package/README.md +1 -1
  2. package/a11y_toolkit/a11y.py +27 -4
  3. package/a11y_toolkit/a11yact.py +9 -1
  4. package/a11y_toolkit/a11yannotate.py +185 -0
  5. package/a11y_toolkit/a11yaudit.py +853 -193
  6. package/a11y_toolkit/a11ybadge.py +24 -17
  7. package/a11y_toolkit/a11ybudget.py +145 -1
  8. package/a11y_toolkit/a11ycorpus.py +58 -24
  9. package/a11y_toolkit/a11ycrit.py +110 -53
  10. package/a11y_toolkit/a11ydiff.py +104 -34
  11. package/a11y_toolkit/a11ydisprove.py +15 -8
  12. package/a11y_toolkit/a11ydocx.py +8 -6
  13. package/a11y_toolkit/a11ydom.py +425 -95
  14. package/a11y_toolkit/a11yen301549.py +53 -1
  15. package/a11y_toolkit/a11yengines.py +157 -0
  16. package/a11y_toolkit/a11yevidence.py +81 -33
  17. package/a11y_toolkit/a11yfix.py +131 -52
  18. package/a11y_toolkit/a11yinit.py +30 -5
  19. package/a11y_toolkit/a11yjourney.py +110 -4
  20. package/a11y_toolkit/a11yledger.py +119 -12
  21. package/a11y_toolkit/a11ylocate.py +247 -0
  22. package/a11y_toolkit/a11yopenacr.py +10 -3
  23. package/a11y_toolkit/a11ypatches.py +154 -0
  24. package/a11y_toolkit/a11ypatterns.py +344 -0
  25. package/a11y_toolkit/a11ypdf.py +109 -53
  26. package/a11y_toolkit/a11yrgaa.py +60 -0
  27. package/a11y_toolkit/a11yroute.py +34 -12
  28. package/a11y_toolkit/a11ysarif.py +45 -18
  29. package/a11y_toolkit/a11yscope.py +67 -15
  30. package/a11y_toolkit/a11yscroll.py +7 -5
  31. package/a11y_toolkit/a11ystatement.py +30 -6
  32. package/a11y_toolkit/a11ytrace.py +293 -0
  33. package/a11y_toolkit/a11yvalidate.py +21 -15
  34. package/a11y_toolkit/a11yvpat.py +34 -7
  35. package/a11y_toolkit/a11yvtt.py +22 -6
  36. package/a11y_toolkit/a11ywiz.py +121 -0
  37. package/a11y_toolkit/contrast.py +62 -24
  38. package/a11y_toolkit/locales/en.json +177 -20
  39. package/a11y_toolkit/locales/es.json +178 -21
  40. package/a11y_toolkit/rgaa.json +2661 -0
  41. package/a11y_toolkit/server.py +149 -50
  42. package/package.json +2 -2
  43. package/a11y_toolkit/a11yplan.py +0 -214
  44. package/a11y_toolkit/a11ywcagem.py +0 -237
@@ -0,0 +1,344 @@
1
+ #!/usr/bin/env python3
2
+ """a11y_patterns — APG keyboard contracts for high-risk ARIA widgets, tested live.
3
+
4
+ The deterministic piece of "screen-reader regression testing for web
5
+ components": detect the widget pattern in the rendered page and PROVE its
6
+ keyboard contract against the ARIA Authoring Practices Guide:
7
+
8
+ dialog / alertdialog Esc closes it; focus stays inside while open
9
+ (modal), focus returns after close
10
+ tablist ArrowRight/Left move focus between tabs (roving
11
+ tabindex); the tab becomes selected — by focus
12
+ (automatic) or by Enter/Space (manual)
13
+ disclosure activating the button FLIPS aria-expanded (the
14
+ state must be exposed, not just the visual)
15
+
16
+ Findings are family `pattern_*` with bilingual remediation. Honesty (what
17
+ v1 deliberately does NOT do): only patterns VISIBLE at load are tested —
18
+ opening a closed dialog means guessing a trigger flow (side effects on a
19
+ real site are never acceptable); nesting/corner cases (combobox, menu,
20
+ slider) are future operators, not silent gaps — this is a filter, not a
21
+ verdict.
22
+
23
+ CLI (infrastructure, not a tool — D17, like corpus/mutants/engines):
24
+ a11ypatterns.py https://web [--lang en] [-o report.json]
25
+ """
26
+
27
+ import argparse
28
+ import json
29
+ import sys
30
+ from datetime import datetime, timezone
31
+
32
+ from . import a11yi18n
33
+
34
+ _P = a11yi18n.pair('patterns') # locales/<lang>.json — community-editable
35
+
36
+ # patterns visibles en carga: dialogs abiertos, tablists, disclosures, combobox,
37
+ # menu buttons y sliders (widgets ARIA de alto riesgo, contratos APG v1+v2)
38
+ _COUNTS = r'''() => {
39
+ const vis = el => !!(el.offsetWidth || el.offsetHeight || el.getClientRects().length);
40
+ return {
41
+ dialogs: [...document.querySelectorAll('[role=dialog], [role=alertdialog], dialog[open]')]
42
+ .filter(vis).length,
43
+ tablists: [...document.querySelectorAll('[role=tablist]')].filter(vis)
44
+ .map(l => l.querySelectorAll('[role=tab]').length),
45
+ disclosures: [...document.querySelectorAll('button[aria-expanded]:not([aria-haspopup="menu"]), [role=button][aria-expanded]:not([aria-haspopup="menu"])')]
46
+ .filter(vis).length,
47
+ comboboxes: [...document.querySelectorAll('[role=combobox]')].filter(vis).length,
48
+ menus: [...document.querySelectorAll('button[aria-haspopup="menu"], [role="button"][aria-haspopup="menu"]')]
49
+ .filter(vis).length,
50
+ sliders: [...document.querySelectorAll('[role="slider"]')].filter(vis).length,
51
+ };
52
+ }'''
53
+
54
+ _INSIDE = r'''() => {
55
+ const el = document.activeElement;
56
+ return !!el && !!el.closest('[role=dialog], [role=alertdialog], dialog');
57
+ }'''
58
+
59
+
60
+ def _finding(findings, lang, severity, criterion, key, **fmt):
61
+ cat = _P['es' if lang == 'es' else 'en']
62
+ findings.append({'severity': severity, 'criterion': criterion,
63
+ 'signal': key,
64
+ 'issue': cat[key].format(**fmt),
65
+ 'remediation': cat[key + '_rem']})
66
+
67
+
68
+ def _test_dialogs(page, findings, lang, cap=3):
69
+ """Visible dialogs: Esc closes; focus stays inside (modal); returns after."""
70
+ loc = page.locator('[role="dialog"]:visible, [role="alertdialog"]:visible, '
71
+ 'dialog[open]:visible')
72
+ n = min(loc.count(), cap)
73
+ for i in range(n):
74
+ d = loc.nth(i)
75
+ try:
76
+ d.evaluate('el => (el.querySelector("a[href],button,input,select,textarea,[tabindex]") '
77
+ '|| el).focus()')
78
+ except Exception: # noqa: BLE001
79
+ continue
80
+ is_modal = (d.get_attribute('aria-modal') or '').lower() == 'true'
81
+ if is_modal:
82
+ page.keyboard.press('Tab')
83
+ page.wait_for_timeout(120)
84
+ try:
85
+ inside = page.evaluate(_INSIDE)
86
+ except Exception: # noqa: BLE001
87
+ inside = True
88
+ if not inside:
89
+ _finding(findings, lang, 'medium', '2.4.3', 'pattern_modal_focus_escapes')
90
+ page.keyboard.press('Escape')
91
+ page.wait_for_timeout(250)
92
+ try:
93
+ still_open = d.is_visible()
94
+ except Exception: # noqa: BLE001
95
+ still_open = False
96
+ if still_open:
97
+ _finding(findings, lang, 'high', '2.1.2', 'pattern_dialog_esc_no_close')
98
+
99
+
100
+ def _test_tablists(page, findings, lang, cap=3):
101
+ """Visible tablists: arrows move focus (roving tabindex); activation follows."""
102
+ locs = page.locator('[role="tablist"]:visible')
103
+ n = min(locs.count(), cap)
104
+ for i in range(n):
105
+ tabs = locs.nth(i).locator('[role="tab"]')
106
+ total = tabs.count()
107
+ if total < 2:
108
+ continue
109
+ # APG tablist: horizontal usa Right/Left; VERTICAL (aria-orientation)
110
+ # prescribe Up/Down — acusar de HIGH una tablist vertical correcta era
111
+ # un FP. Se acepta que CUALQUIERA de las dos flechas mueva el foco
112
+ try:
113
+ tabs.nth(0).evaluate('el => el.focus()')
114
+ page.keyboard.press('ArrowRight')
115
+ page.wait_for_timeout(120)
116
+ is_second = page.evaluate(
117
+ '''(tab) => document.activeElement === tab''',
118
+ tabs.nth(1).element_handle())
119
+ if not is_second:
120
+ page.keyboard.press('ArrowDown')
121
+ page.wait_for_timeout(120)
122
+ is_second = page.evaluate(
123
+ '''(tab) => document.activeElement === tab''',
124
+ tabs.nth(1).element_handle())
125
+ if not is_second:
126
+ _finding(findings, lang, 'high', '2.1.1', 'pattern_tabs_arrows_dead',
127
+ n=total)
128
+ continue
129
+ # selección: automática (aria-selected sigue al foco) o manual
130
+ # (Enter/Space activa) — ninguna = estado expuesto muerto
131
+ if (tabs.nth(1).get_attribute('aria-selected') or '').lower() != 'true':
132
+ page.keyboard.press('Enter')
133
+ page.wait_for_timeout(150)
134
+ if (tabs.nth(1).get_attribute('aria-selected') or '').lower() != 'true':
135
+ page.keyboard.press(' ') # Space, la otra vía manual
136
+ page.wait_for_timeout(150)
137
+ if (tabs.nth(1).get_attribute('aria-selected') or '').lower() != 'true':
138
+ _finding(findings, lang, 'medium', '4.1.2',
139
+ 'pattern_tabs_no_activation')
140
+ except Exception: # noqa: BLE001 — un widget roto no debe matar el pase
141
+ continue
142
+
143
+
144
+ def _test_disclosures(page, findings, lang, cap=8):
145
+ """Disclosure buttons: activation must FLIP the exposed state.
146
+ Menu buttons are excluded — they are the menu pattern's subject."""
147
+ loc = page.locator('button[aria-expanded]:visible:not([aria-haspopup="menu"]), '
148
+ '[role="button"][aria-expanded]:visible:not([aria-haspopup="menu"])')
149
+ n = min(loc.count(), cap)
150
+ for i in range(n):
151
+ b = loc.nth(i)
152
+ try:
153
+ before = (b.get_attribute('aria-expanded') or '').lower()
154
+ name = ((b.get_attribute('aria-label') or '') or b.inner_text()
155
+ or 'disclosure').strip().replace('\n', ' ')[:40]
156
+ b.click()
157
+ page.wait_for_timeout(250)
158
+ after = (b.get_attribute('aria-expanded') or '').lower()
159
+ if before == after and before in ('true', 'false'):
160
+ _finding(findings, lang, 'medium', '4.1.2',
161
+ 'pattern_disclosure_state_frozen', name=name)
162
+ elif after in ('true', 'false') and after != before:
163
+ b.click() # dejar la página como estaba
164
+ page.wait_for_timeout(150)
165
+ except Exception: # noqa: BLE001
166
+ continue
167
+
168
+
169
+ def _visible_open(page, sel):
170
+ """Is a matching element visible right now?"""
171
+ try:
172
+ return page.locator(sel).first.is_visible()
173
+ except Exception: # noqa: BLE001
174
+ return False
175
+
176
+
177
+ def _test_comboboxes(page, findings, lang, cap=3):
178
+ """Comboboxes: activation opens the popup; Escape closes it."""
179
+ loc = page.locator('[role="combobox"]:visible')
180
+ n = min(loc.count(), cap)
181
+ for i in range(n):
182
+ c = loc.nth(i)
183
+ try:
184
+ c.evaluate('el => el.focus()')
185
+ before = (c.get_attribute('aria-expanded') or '').lower()
186
+ page.keyboard.press('ArrowDown')
187
+ page.wait_for_timeout(300)
188
+ after = (c.get_attribute('aria-expanded') or '').lower()
189
+ opened = after == 'true' or _visible_open(page, '[role="listbox"]:visible')
190
+ if not opened and before != 'true':
191
+ _finding(findings, lang, 'medium', '2.1.1', 'pattern_combobox_no_open')
192
+ continue
193
+ page.keyboard.press('Escape')
194
+ page.wait_for_timeout(250)
195
+ closed = (c.get_attribute('aria-expanded') or '').lower() != 'true' \
196
+ and not _visible_open(page, '[role="listbox"]:visible')
197
+ if not closed:
198
+ _finding(findings, lang, 'medium', '2.1.1', 'pattern_combobox_esc_no_close')
199
+ except Exception: # noqa: BLE001
200
+ continue
201
+
202
+
203
+ def _test_menu_buttons(page, findings, lang, cap=3):
204
+ """Menu buttons: activation opens the menu; Escape closes + refocuses."""
205
+ loc = page.locator('button[aria-haspopup="menu"]:visible, '
206
+ '[role="button"][aria-haspopup="menu"]:visible')
207
+ n = min(loc.count(), cap)
208
+ for i in range(n):
209
+ b = loc.nth(i)
210
+ try:
211
+ b.click()
212
+ page.wait_for_timeout(300)
213
+ opened = _visible_open(page, '[role="menu"]:visible') \
214
+ or (b.get_attribute('aria-expanded') or '').lower() == 'true'
215
+ if not opened:
216
+ _finding(findings, lang, 'medium', '2.1.1', 'pattern_menu_no_open')
217
+ continue
218
+ page.keyboard.press('Escape')
219
+ page.wait_for_timeout(250)
220
+ closed = not _visible_open(page, '[role="menu"]:visible') \
221
+ and (b.get_attribute('aria-expanded') or '').lower() != 'true'
222
+ if not closed:
223
+ _finding(findings, lang, 'medium', '2.1.1', 'pattern_menu_esc_no_close')
224
+ except Exception: # noqa: BLE001
225
+ continue
226
+
227
+
228
+ def _test_sliders(page, findings, lang, cap=3):
229
+ """Custom sliders: arrows change the value; the state trio must be exposed."""
230
+ loc = page.locator('[role="slider"]:visible')
231
+ n = min(loc.count(), cap)
232
+ for i in range(n):
233
+ s = loc.nth(i)
234
+ try:
235
+ has_state = all((s.get_attribute(a) or '').strip() not in ('', None)
236
+ for a in ('aria-valuenow', 'aria-valuemin', 'aria-valuemax'))
237
+ if not has_state:
238
+ _finding(findings, lang, 'medium', '4.1.2', 'pattern_slider_no_state',
239
+ name=((s.get_attribute('aria-label') or '') or 'slider')[:40])
240
+ now = (s.get_attribute('aria-valuenow') or '').strip()
241
+ s.evaluate('el => el.focus()')
242
+ page.keyboard.press('ArrowRight')
243
+ page.wait_for_timeout(150)
244
+ after_r = (s.get_attribute('aria-valuenow') or '').strip()
245
+ if after_r == now:
246
+ page.keyboard.press('ArrowUp')
247
+ page.wait_for_timeout(150)
248
+ after_up = (s.get_attribute('aria-valuenow') or '').strip()
249
+ if after_up == now:
250
+ _finding(findings, lang, 'high', '2.1.1', 'pattern_slider_arrows_dead')
251
+ continue
252
+ # devolver el valor original (dejar la página como estaba)
253
+ if now and (s.get_attribute('aria-valuenow') or '').strip() != now:
254
+ s.evaluate('(el, v) => el.setAttribute("aria-valuenow", v)', now)
255
+ except Exception: # noqa: BLE001
256
+ continue
257
+
258
+
259
+ def audit_patterns(url, timeout=45, lang='en', auth_state=None, browser='auto'):
260
+ """One url → widget patterns found + contract findings (filter, not verdict)."""
261
+ from playwright.sync_api import sync_playwright
262
+ from .a11ydom import _get_browser
263
+ lang = 'es' if lang == 'es' else 'en'
264
+ with sync_playwright() as p:
265
+ nav = _get_browser(p, preferred=browser)
266
+ ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
267
+ page = ctx.new_page() if auth_state else nav.new_page()
268
+ try:
269
+ page.goto(url, wait_until='load', timeout=timeout * 1000)
270
+ page.wait_for_timeout(400)
271
+ except Exception as e: # noqa: BLE001
272
+ nav.close()
273
+ return {'error': f'could not load: {e}'}
274
+
275
+ counts = page.evaluate(_COUNTS)
276
+ findings = []
277
+ _test_dialogs(page, findings, lang)
278
+ _test_tablists(page, findings, lang)
279
+ _test_disclosures(page, findings, lang)
280
+ _test_comboboxes(page, findings, lang)
281
+ _test_menu_buttons(page, findings, lang)
282
+ _test_sliders(page, findings, lang)
283
+ nav.close()
284
+
285
+ limits = ('Only patterns VISIBLE at page load are tested: opening a closed '
286
+ 'dialog means guessing a trigger flow — never acceptable on a '
287
+ 'live site. Operators: dialog (Esc + modal containment), '
288
+ 'tablist (arrows + activation), disclosure (aria-expanded flips), '
289
+ 'combobox (opens + Esc closes), menu button (opens + Esc closes), '
290
+ 'slider (arrows change value + value trio exposed). A '
291
+ 'clean pass proves THESE contracts at THIS moment — not full '
292
+ 'APG conformance.'
293
+ if lang == 'en' else
294
+ 'Solo se prueban patrones VISIBLES en carga: abrir un diálogo '
295
+ 'cerrado exige adivinar un disparador — jamás aceptable en un '
296
+ 'sitio real. Operadores: dialog (Esc + contención modal), '
297
+ 'tablist (flechas + activación), disclosure (aria-expanded '
298
+ 'cambia), combobox (abre + Esc cierra), menu button (abre + Esc '
299
+ 'cierra), slider (flechas cambian el valor + trío de estado '
300
+ 'expuesto). Un pase limpio prueba ESTOS contratos en '
301
+ 'ESTE momento — no conformidad APG completa.')
302
+ return {'mode': 'patterns', 'url': url,
303
+ 'ts': datetime.now(timezone.utc).isoformat(),
304
+ 'patterns_seen': {'dialog': counts.get('dialogs', 0),
305
+ 'tablist': len(counts.get('tablists', [])),
306
+ 'tabs': sum(counts.get('tablists', [])),
307
+ 'disclosure': counts.get('disclosures', 0),
308
+ 'combobox': counts.get('comboboxes', 0),
309
+ 'menu': counts.get('menus', 0),
310
+ 'slider': counts.get('sliders', 0)},
311
+ 'findings': findings,
312
+ 'limits': limits}
313
+
314
+
315
+ def main(argv):
316
+ ap = argparse.ArgumentParser(description=__doc__)
317
+ ap.add_argument('url')
318
+ ap.add_argument('--lang', default='en', choices=['en', 'es'])
319
+ ap.add_argument('--timeout', type=int, default=45)
320
+ ap.add_argument('--auth-state', help='Playwright storage_state JSON (session)')
321
+ ap.add_argument('-o', '--out', help='write the report here (default: stdout)')
322
+ a = ap.parse_args(argv)
323
+ try:
324
+ res = audit_patterns(a.url, timeout=a.timeout, lang=a.lang,
325
+ auth_state=a.auth_state)
326
+ except ImportError:
327
+ print(json.dumps({'error': 'Playwright not installed: pip install '
328
+ 'playwright && playwright install chromium'}))
329
+ return 1
330
+ out = json.dumps(res, ensure_ascii=False, indent=1)
331
+ if a.out:
332
+ with open(a.out, 'w', encoding='utf-8') as f:
333
+ f.write(out + '\n')
334
+ print(json.dumps({'url': a.url,
335
+ 'patterns_seen': res.get('patterns_seen'),
336
+ 'findings': len(res.get('findings', [])),
337
+ 'out': a.out}, ensure_ascii=False))
338
+ else:
339
+ print(out)
340
+ return 1 if 'error' in res else 0
341
+
342
+
343
+ if __name__ == '__main__':
344
+ sys.exit(main(sys.argv[1:]))
@@ -38,11 +38,20 @@ def _t(lang, key):
38
38
  return T.get(lang, T['en'])[key]
39
39
 
40
40
 
41
+ # Techos anti-bomba de descompresión: por stream y ACUMULADO entre streams
42
+ # (una bomba repartida en 100 streams de 20MB no descomprime 2GB; lo que
43
+ # llegó hasta el techo basta para auditar — doctrina de lectura parcial).
44
+ _STREAM_CAP = 20_000_000 # 20 MB por stream descomprimido
45
+ _STREAM_BUDGET = 120_000_000 # 120 MB en total entre todos los streams
46
+
47
+
41
48
  def _uncompressed_streams(data, limit=60):
42
49
  """Los streams FlateDecode, descomprimidos (zlib es stdlib) — ahí viven
43
50
  el XMP, el contenido y buena parte de la estructura."""
44
- out = []
51
+ out, total = [], 0
45
52
  for m in re.finditer(rb'stream\r?\n', data):
53
+ if total >= _STREAM_BUDGET:
54
+ break # techo acumulado: dejar de inflar, auditar lo que llegó
46
55
  start = m.end()
47
56
  end = data.find(b'endstream', start)
48
57
  if end == -1:
@@ -50,14 +59,92 @@ def _uncompressed_streams(data, limit=60):
50
59
  chunk = data[start:end].rstrip(b'\r\n')
51
60
  try:
52
61
  d = zlib.decompressobj()
53
- out.append(d.decompress(chunk, 20_000_000)) # bomba: techo por stream
62
+ dec = d.decompress(chunk, _STREAM_CAP) # bomba: techo por stream
54
63
  except Exception: # noqa: BLE001
55
64
  continue
65
+ out.append(dec)
66
+ total += len(dec)
56
67
  if len(out) >= limit:
57
68
  break
58
69
  return out
59
70
 
60
71
 
72
+ # ── 1.4.3 en PDF: contraste del texto contra el fondo efectivo ──
73
+ # Parseo de la secuencia de operadores: `rg`/`g`/`k` cambian el color de
74
+ # relleno (con el que se escribe texto), `re` declara un rectángulo —
75
+ # candidato a FONDO solo si un operador de pintado (f/F/B/B*/b) lo pinta
76
+ # después, con el relleno VIGENTE —, y `Tj`/`TJ` escriben texto (TJ también
77
+ # en forma de array: `[(H) -3 (ola)] TJ`). El fondo por defecto del PDF es
78
+ # blanco si nadie lo pinta: un rect oscuro pintado antes del texto cambia
79
+ # el fondo efectivo — no acusar blanco-sobre-oscuro como bajo (el mismo bug
80
+ # que CSS var() en HTML). Los operandos de `re` NUNCA se interpretan como
81
+ # color (bug histórico: `0 0 612 792 re` se leía como triple RGB).
82
+ _RE_STREAM_OPS = re.compile(
83
+ r'(?P<r>[\d.]+)\s+(?P<g>[\d.]+)\s+(?P<b>[\d.]+)\s+rg\b' # relleno RGB
84
+ r'|(?P<gray>[\d.]+)\s+g\b' # relleno gris
85
+ r'|(?P<k1>[\d.]+)\s+(?P<k2>[\d.]+)\s+(?P<k3>[\d.]+)\s+(?P<k4>[\d.]+)\s+k\b' # relleno CMYK
86
+ r'|(?P<x1>[\d.]+)\s+(?P<y1>[\d.]+)\s+(?P<w1>[\d.]+)\s+(?P<h1>[\d.]+)\s+re\b' # rectángulo
87
+ r'|(?P<paint>\b[fFBb]\*?(?![\w*]))' # pintado del path
88
+ r'|(?P<text>\((?:[^()\\]|\\.)*\)\s*(?:Tj|TJ)|\]\s*TJ)') # texto (cadena o array)
89
+
90
+
91
+ def _l(r, g, b):
92
+ def lin(v):
93
+ v /= 255.0
94
+ return v / 12.92 if v <= 0.03928 else ((v + 0.055) / 1.055) ** 2.4
95
+ return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b)
96
+
97
+
98
+ def _ratio(f, b):
99
+ l1, l2 = max(f, b), min(f, b)
100
+ return (l1 + 0.05) / (l2 + 0.05)
101
+
102
+
103
+ def _stream_low_contrast(text):
104
+ """Un content stream (ya decodificado latin-1) → lista de ejemplos
105
+ 'color sobre fondo' por debajo de 4.5:1. Escaneo secuencial
106
+ determinista de los operadores de color/pintado/texto."""
107
+ hits = []
108
+ fill = (0, 0, 0) # relleno vigente: el color con el que se escribe
109
+ bg = (255, 255, 255) # fondo efectivo: blanco salvo rect pintado
110
+ rect_pending = False # un `re` declarado, esperando su operador de pintado
111
+ for m in _RE_STREAM_OPS.finditer(text):
112
+ if m.group('r') is not None: # rg — relleno RGB
113
+ try:
114
+ fill = tuple(max(0, min(255, round(float(x) * 255)))
115
+ for x in (m.group('r'), m.group('g'), m.group('b')))
116
+ except ValueError:
117
+ pass
118
+ elif m.group('gray') is not None: # g — relleno en escala de grises
119
+ try:
120
+ v = max(0, min(255, round(float(m.group('gray')) * 255)))
121
+ fill = (v, v, v)
122
+ except ValueError:
123
+ pass
124
+ elif m.group('k1') is not None: # k — relleno CMYK (aprox. naive)
125
+ try:
126
+ c_, mm_, y_, black = (max(0.0, min(1.0, float(x))) for x in
127
+ (m.group('k1'), m.group('k2'),
128
+ m.group('k3'), m.group('k4')))
129
+ fill = tuple(max(0, min(255, round(255 * (1 - x) * (1 - black))))
130
+ for x in (c_, mm_, y_))
131
+ except ValueError:
132
+ pass
133
+ elif m.group('x1') is not None: # re — rectángulo: solo candidato a fondo
134
+ rect_pending = True # sin pintado posterior no cambia nada
135
+ elif m.group('paint') is not None: # f/F/B/B*/b — pinta el path pendiente
136
+ if rect_pending:
137
+ bg = fill # pintado con el relleno VIGENTE: ese rect es el fondo
138
+ rect_pending = False
139
+ else: # Tj / TJ — texto con el relleno vigente
140
+ ratio_ = _ratio(_l(*fill), _l(*bg))
141
+ if ratio_ < 4.5:
142
+ hits.append(f'rgb({fill[0]},{fill[1]},{fill[2]})'
143
+ f' sobre rgb({bg[0]},{bg[1]},{bg[2]})'
144
+ f' \u2192 {ratio_:.2f}:1')
145
+ return hits
146
+
147
+
61
148
  def pdf_screen(path_or_bytes, lang='en'):
62
149
  """Cribado estructural de accesibilidad de un PDF (fichero local)."""
63
150
  if isinstance(path_or_bytes, (bytes, bytearray)):
@@ -75,19 +162,33 @@ def pdf_screen(path_or_bytes, lang='en'):
75
162
  return {'error': 'not a PDF (no %PDF- marker)'}
76
163
 
77
164
  streams = _uncompressed_streams(data)
78
- todo = data + b'\n'.join(streams[:40])
165
+ # `todo` respeta el MISMO presupuesto acumulado: ensamblar 40 streams de
166
+ # 20MB sería una segunda bomba
167
+ parts, total_todo = [data], len(data)
168
+ for s in streams[:40]:
169
+ if total_todo + len(s) > _STREAM_BUDGET:
170
+ break
171
+ parts += [b'\n', s]
172
+ total_todo += len(s) + 1
173
+ todo = b''.join(parts)
79
174
 
80
175
  def present(pat):
81
176
  return re.search(pat, todo) is not None
82
177
 
83
178
  encrypted = b'/Encrypt' in data # el trailer vive al FINAL del fichero
84
- tagged = present(rb'/StructTreeRoot\s+\d+\s+0\s+R') or present(rb'/StructTreeRoot')
179
+ # tagged: la forma canónica es la referencia del catálogo (/StructTreeRoot
180
+ # N 0 R). Una mención suelta (p. ej. dentro de un content stream) solo
181
+ # cuenta como estructura cuando el documento además declara /Marked true.
85
182
  marked = present(rb'/Marked\s+true')
183
+ tagged = present(rb'/StructTreeRoot\s+\d+\s+0\s+R') or \
184
+ (marked and present(rb'/StructTreeRoot'))
86
185
  lang_doc = re.search(rb'/Lang\s*\(([^)]{2,20})\)', todo)
87
186
  title_meta = re.search(rb'/Title\s*\(([^)]{1,300})\)', todo) or \
88
187
  re.search(rb'<dc:title>.{0,200}?<rdf:li[^>]*>([^<]{1,300})</rdf:li>', todo, re.S)
89
188
  n_pages = len(re.findall(rb'/Type\s*/Page[^s]', todo))
90
- n_alt = len(re.findall(rb'/Alt\s*\(', todo))
189
+ # /Alt acepta literal (/Alt (…)) y hex (/Alt <FEFF…>, la forma natural
190
+ # UTF-16BE para alt no latino) — misma paridad que /TU
191
+ n_alt = len(re.findall(rb'/Alt\s*[<(]', todo))
91
192
  n_actual = len(re.findall(rb'/ActualText', todo))
92
193
  n_imgs = len(re.findall(rb'/Subtype\s*/Image', todo))
93
194
  n_outline = len(re.findall(rb'/Outlines\s+\d+\s+0\s+R', todo))
@@ -100,56 +201,11 @@ def pdf_screen(path_or_bytes, lang='en'):
100
201
  findings = []
101
202
 
102
203
  # ── 1.4.3 en PDF: contraste del texto contra el fondo efectivo ──
103
- # Parseo de la secuencia: `rg` cambia el color de relleno de texto,
104
- # `re` + `f` pinta un rectángulo (fondo), `Tj`/`TJ` escriben texto.
105
- # El fondo por defecto del PDF es blanco si nadie lo pinta. Si un rect
106
- # oscuro precede al texto, el fondo efectivo es ese fill — no acusar
107
- # blanco-sobre-oscuro como bajo (el mismo bug que CSS var() en HTML).
108
- def _l(r, g, b):
109
- def lin(v):
110
- v /= 255.0
111
- return v / 12.92 if v <= 0.03928 else ((v + 0.055) / 1.055) ** 2.4
112
- return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b)
113
-
114
- def _ratio(f, b):
115
- l1, l2 = max(f, b), min(f, b)
116
- return (l1 + 0.05) / (l2 + 0.05)
117
-
118
- blanc = _l(255, 255, 255)
119
204
  low_hits = []
120
205
  for stream in streams:
121
- text = stream.decode('latin-1', 'replace')
122
- text_color = (0, 0, 0)
123
- bg_color = (255, 255, 255) # el PDF no pinta fondo por defecto
124
- painted_bg = False
125
- for m in re.finditer(
126
- r'([\d.]+)\s+([\d.]+)\s+([\d.]+)\s+(rg|re)\b'
127
- r'|\b(f)\b'
128
- r'|\((?:[^()\\]|\\.)*\)\s*(Tj|TJ)'
129
- , text):
130
- op = m.group(4) or m.group(5) or m.group(6)
131
- if op in ('rg', 're'):
132
- try:
133
- text_color = tuple(
134
- max(0, min(255, round(float(x) * 255)))
135
- for x in m.groups()[:3])
136
- except ValueError:
137
- pass
138
- if op == 're':
139
- # el rect se pinta con el fill actual: es el FONDO
140
- bg_color = text_color
141
- elif op == 'f':
142
- pass # el f pinta con el fill ya establecido (fondo ya guardado)
143
- else: # Tj / TJ
144
- lt = _l(*text_color)
145
- lb = _l(*bg_color)
146
- ratio = _ratio(lt, lb)
147
- if ratio < 4.5:
148
- ej = (f'rgb({text_color[0]},{text_color[1]},{text_color[2]})'
149
- f' sobre rgb({bg_color[0]},{bg_color[1]},{bg_color[2]})'
150
- f' \u2192 {ratio:.2f}:1')
151
- if ej not in [x.split(' \u2014 ')[0] for x in low_hits]:
152
- low_hits.append(ej)
206
+ for ej in _stream_low_contrast(stream.decode('latin-1', 'replace')):
207
+ if ej not in low_hits:
208
+ low_hits.append(ej)
153
209
  if len(low_hits) >= 4:
154
210
  break
155
211
  if low_hits:
@@ -0,0 +1,60 @@
1
+ #!/usr/bin/env python3
2
+ """RGAA 4.1 — the French legal standard as data.
3
+
4
+ Generated by scripts/rgaa_ingest.py from the OFFICIAL government JSON
5
+ (github.com/DISIC/accessibilite.numerique.gouv.fr — open data, 106/106
6
+ criteria with a mechanical bridge to WCAG SC). This module is the thin
7
+ loader + the lookup surfaces other modules use; never hand-edit the JSON.
8
+
9
+ The RGAA has its own numbering (1.1–13.12 across 13 topics) and NO A/AA
10
+ levels — every criterion is conformant / not conformant. Titles and tests
11
+ are French (the standard's language); the WCAG bridge lives in each
12
+ criterion's `wcag` list.
13
+ """
14
+
15
+ import json
16
+ import os
17
+
18
+ _HERE = os.path.dirname(os.path.abspath(__file__))
19
+
20
+ with open(os.path.join(_HERE, 'rgaa.json'), encoding='utf-8') as _f:
21
+ _DATA = json.load(_f)
22
+
23
+ STANDARD_NAME = 'RGAA 4.1 (France)'
24
+ VERSION = _DATA['version']
25
+ WCAG_BASE = _DATA['wcag_base']
26
+ SOURCE = _DATA['source']
27
+ TOPICS = [(t['number'], t['name']) for t in _DATA['topics']]
28
+ CRITERIA = _DATA['criteria'] # 106: {num, topic, number, title, tests, notes, wcag}
29
+
30
+ # índice inverso: WCAG SC code → [números RGAA] (el puente mecánico)
31
+ _BY_SC = {}
32
+ for _c in CRITERIA:
33
+ for _w in _c['wcag']:
34
+ _sc = _w.split(' ')[0]
35
+ _BY_SC.setdefault(_sc, []).append(_c['num'])
36
+
37
+
38
+ def rgaa_for_sc(sc_code):
39
+ """'1.1.1' → ['1.1', …]: los criterios RGAA que verifican ese SC.
40
+ Devuelve [] si ningún criterio RGAA lo referencia."""
41
+ return list(_BY_SC.get(sc_code, []))
42
+
43
+
44
+ def criterion(num):
45
+ """'1.1' → el criterio completo, o None."""
46
+ return next((c for c in CRITERIA if c['num'] == num), None)
47
+
48
+
49
+ def standard_block(lang='en'):
50
+ """Bloque 'standard' para informes audit --standard rgaa."""
51
+ names = {'en': 'RGAA 4.1 — the French web accessibility framework',
52
+ 'es': 'RGAA 4.1 — el marco francés de accesibilidad web'}
53
+ return {
54
+ 'name': names.get(lang) or names['en'],
55
+ 'version': VERSION,
56
+ 'topics': len(TOPICS),
57
+ 'criteria': len(CRITERIA),
58
+ 'wcag_base': WCAG_BASE,
59
+ 'source': SOURCE,
60
+ }