@kinti/a11y-toolkit 5.23.0 → 5.24.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.
@@ -29,6 +29,7 @@
29
29
  a11ytoolkit route --goal "gate my PR" # which tools for the task
30
30
  a11ytoolkit route --file page.html # diagnosis: read the page, order the exams
31
31
  a11ytoolkit mutants --seed 7 --n 12 # the engine's sealed self-exam
32
+ a11ytoolkit fingerprints page1.html page2.html --dir p/ # twin-page detection (one audit per template)
32
33
  """
33
34
 
34
35
  import sys
@@ -60,6 +61,7 @@ from . import a11yinit
60
61
  from . import a11ywcag3
61
62
  from . import a11yroute
62
63
  from . import a11ymutants
64
+ from . import a11yfingerprints
63
65
 
64
66
  SUBCOMMANDS = {
65
67
  'pair': (contrast, 'pair'),
@@ -95,6 +97,7 @@ SUBCOMMANDS = {
95
97
  'wcag3': (a11ywcag3, None),
96
98
  'route': (a11yroute, None),
97
99
  'mutants': (a11ymutants, None),
100
+ 'fingerprints': (a11yfingerprints, None),
98
101
  }
99
102
 
100
103
 
@@ -0,0 +1,270 @@
1
+ #!/usr/bin/env python3
2
+ """a11y_fingerprints — multi-hash template fingerprints (twin-page detection).
3
+
4
+ Cross-industry translation: multi-hash identification. One hash of a page
5
+ breaks the moment a csrf token or a timestamp changes; several independent
6
+ hashes over DIFFERENT normalizations identify by intersection — a template
7
+ stays recognizable when its volatile parts change, and the view that
8
+ diverges tells what KIND of change it was.
9
+
10
+ Three views of the document, text always excluded (content varies per page;
11
+ that is the point):
12
+ structure tag + depth — the skeleton (defines the template)
13
+ classes + sorted class list — the skin (design-system change)
14
+ attributes + stable attributes — real attribute changes, with the
15
+ id-referencing / volatile attrs excluded by design (id, for,
16
+ name, href, src, …) so per-page ids and csrf tokens can never
17
+ split a template
18
+
19
+ Regions: the landmark containers (header/nav/main/aside/footer) plus
20
+ `document` for everything outside them. Each (view, region) → sha256[:12].
21
+
22
+ Template = the complete structure view (same skeleton = same template — a
23
+ declared rule, not fuzzy similarity). Inside a template every page is
24
+ compared view-by-view against the representative (the lexicographically
25
+ smallest page id); each mismatch is a localized {page, region, view} entry:
26
+ "header diverges in classes, footer identical".
27
+
28
+ sample_suggestion = one representative per template, the structured-sample
29
+ helper for WCAG-EM Step 3. The evaluator still owns the sample; identical
30
+ structure does not guarantee identical findings after rendering.
31
+
32
+ CLI:
33
+ a11yfingerprints.py page1.html page2.html [--dir pages/] [--lang es] [-o out.json]
34
+ """
35
+
36
+ import argparse
37
+ import hashlib
38
+ import json
39
+ import os
40
+ import sys
41
+ from html.parser import HTMLParser
42
+
43
+ VIEWS = ('structure', 'classes', 'attributes')
44
+
45
+ # landmarks que abren región propia; lo que queda fuera vive en 'document'
46
+ _REGIONS = ('header', 'nav', 'main', 'aside', 'footer')
47
+
48
+ # attrs volátiles por construcción: referencian ids únicos por página o
49
+ # cambian con cada petición — si entraran en una vista, partirían plantillas
50
+ # falsamente (el csrf/token/per-page-id NO es un rediseño)
51
+ _VOLATILE = frozenset((
52
+ 'id', 'for', 'name', 'href', 'src', 'srcset', 'action', 'headers',
53
+ 'list', 'style', 'value', 'aria-controls', 'aria-describedby',
54
+ 'aria-labelledby', 'aria-owns', 'aria-details', 'aria-errormessage',
55
+ ))
56
+
57
+ _VOID = frozenset(('area', 'base', 'br', 'col', 'embed', 'hr', 'img',
58
+ 'input', 'link', 'meta', 'param', 'source', 'track',
59
+ 'wbr', 'path', 'circle', 'rect', 'line', 'polyline',
60
+ 'polygon', 'ellipse', 'stop', 'use'))
61
+
62
+ # vistas que se comparan dentro de una plantilla (structure NO puede divergir
63
+ # por definición — es la clave de agrupación)
64
+ _DIVERGENCE_VIEWS = ('classes', 'attributes')
65
+
66
+ _NOTES = {
67
+ 'en': ('Suggests a structured sample: one representative per detected '
68
+ 'template (WCAG-EM Step 3 helper). The evaluator still owns sample '
69
+ 'selection; identical structure does not guarantee identical '
70
+ 'findings after rendering. Volatile attributes (per-page ids, '
71
+ 'urls, tokens) are excluded by design so they cannot split '
72
+ 'templates.'),
73
+ 'es': ('Sugiere una muestra estructurada: un representante por plantilla '
74
+ 'detectada (ayudante del paso 3 de WCAG-EM). El evaluador sigue '
75
+ 'siendo dueño de la selección; estructura idéntica no garantiza '
76
+ 'hallazgos idénticos tras el render. Los atributos volátiles '
77
+ '(ids por página, urls, tokens) se excluyen a propósito para que '
78
+ 'no puedan partir plantillas.'),
79
+ }
80
+
81
+
82
+ def _digest(lines):
83
+ return hashlib.sha256('\n'.join(lines).encode('utf-8')).hexdigest()[:12]
84
+
85
+
86
+ class _Serializer(HTMLParser):
87
+ """Serializa el documento a 3 vistas × regiones. Tolerante al HTML hostil:
88
+ cierres sin apertura, anidación imposible y attrs duplicados no rompen
89
+ nada (el parser de stdlib ya de-duplica attrs; los cierres huérfanos se
90
+ ignoran, los abiertos sin cerrar se limpian al final)."""
91
+
92
+ def __init__(self):
93
+ super().__init__(convert_charrefs=True)
94
+ self.lines = {v: {} for v in VIEWS} # view -> region -> [lines]
95
+ self._stack = [] # [(tag, era_landmark_antes)]
96
+ self._landmarks = [] # landmarks abiertos (externo→interno)
97
+
98
+ # región vigente: el landmark MÁS EXTERNO abierto; si ninguno, 'document'
99
+ def _region(self):
100
+ return self._landmarks[0] if self._landmarks else 'document'
101
+
102
+ def _close_landmark(self, tag):
103
+ """Cierra el landmark MÁS RECIENTE de ese tag (LIFO, como el stack).
104
+ remove() a secas borraría el primero y corrompería el orden
105
+ externo→interno con landmarks anidados del mismo tipo."""
106
+ for i in range(len(self._landmarks) - 1, -1, -1):
107
+ if self._landmarks[i] == tag:
108
+ del self._landmarks[i]
109
+ return
110
+
111
+ def _emit(self, tag, attrs, depth):
112
+ region = self._region()
113
+ cls = sorted((attrs.get('class') or '').split())
114
+ # sin \n/\r en los valores: un attr hostil no puede falsificar
115
+ # líneas del material que se hashea (dos documentos distintos, un
116
+ # mismo digest sería una divergencia perdida)
117
+ stable = sorted('{}={}'.format(k, v.replace('\n', ' ').replace('\r', ' '))
118
+ for k, v in attrs.items()
119
+ if k not in _VOLATILE and k != 'class')
120
+ for view, extra in (('structure', ''),
121
+ ('classes', ' .' + '.'.join(cls) if cls else ''),
122
+ ('attributes', ' ' + ' '.join(stable) if stable else '')):
123
+ self.lines[view].setdefault(region, []).append(
124
+ '{} {}{}'.format(depth, tag, extra))
125
+
126
+ def handle_starttag(self, tag, attrs):
127
+ tag = tag.lower()
128
+ adict = {}
129
+ for k, v in attrs: # parser stdlib ya deduplica,
130
+ adict.setdefault(k, v or '') # pero no perdemos nada siendo explícitos
131
+ depth = len(self._stack)
132
+ if tag in _REGIONS:
133
+ # el propio landmark pertenece a SU región: abre antes de emitir
134
+ # (append: el PRIMERO de la lista es el más externo → _region())
135
+ self._landmarks.append(tag)
136
+ self._emit(tag, adict, depth)
137
+ if tag not in _VOID:
138
+ self._stack.append(tag)
139
+
140
+ def handle_startendtag(self, tag, attrs):
141
+ # <tag/> autocontenido: emite sin apilar (el mismo elemento, una vez)
142
+ self.handle_starttag(tag, attrs)
143
+ if self._stack and self._stack[-1] == tag and tag not in _VOID:
144
+ self._stack.pop()
145
+ if tag in self._landmarks:
146
+ self._close_landmark(tag)
147
+
148
+ def handle_endtag(self, tag):
149
+ tag = tag.lower()
150
+ if tag in self._stack:
151
+ # pop hasta el cierre correcto; lo que quede abierto fuera se ignora
152
+ while self._stack:
153
+ open_tag = self._stack.pop()
154
+ if open_tag in _REGIONS:
155
+ self._close_landmark(open_tag)
156
+ if open_tag == tag:
157
+ break
158
+ elif tag in _REGIONS and tag in self._landmarks:
159
+ self._close_landmark(tag)
160
+
161
+
162
+ def fingerprint_html(html_text):
163
+ """html (str) → {hashes: {view: {region: digest}}, template, regions}.
164
+
165
+ Determinista: mismas vistas, mismo sha, sin red ni azar."""
166
+ s = _Serializer()
167
+ try:
168
+ s.feed(html_text or '')
169
+ s.close()
170
+ except Exception:
171
+ pass # el parser stdlib no lanza con entrada hostil, pero si algo
172
+ # escapa, lo YA serializado sigue siendo un fingerprint válido
173
+ hashes = {v: {r: _digest(ls) for r, ls in s.lines[v].items()}
174
+ for v in VIEWS}
175
+ structure = hashes['structure']
176
+ template = 't-' + hashlib.sha256(
177
+ '|'.join('{}:{}'.format(r, structure[r]) for r in sorted(structure))
178
+ .encode('utf-8')).hexdigest()[:8]
179
+ return {'hashes': hashes, 'template': template,
180
+ 'regions': sorted(structure)}
181
+
182
+
183
+ def fingerprint_pages(pages, lang='en'):
184
+ """pages: [{'page': id, 'html': str}] → informe completo.
185
+
186
+ Agrupa por plantilla (vista structure), localiza la divergencia vista a
187
+ vista contra el representante (id lexicográfico mínimo — regla
188
+ declarada) y sugiere una muestra de un representante por plantilla
189
+ (ayudante del paso 3 de WCAG-EM; el evaluador decide)."""
190
+ if not isinstance(pages, list) or not all(
191
+ isinstance(p, dict) and 'page' in p and 'html' in p for p in pages):
192
+ raise ValueError('pages must be a list of {page, html} dicts')
193
+
194
+ entries = []
195
+ for p in pages:
196
+ fp = fingerprint_html(p['html'])
197
+ entries.append({'page': p['page'], 'hashes': fp['hashes'],
198
+ 'regions': fp['regions'], 'template': fp['template']})
199
+
200
+ groups = {}
201
+ for e in entries:
202
+ groups.setdefault(e['template'], []).append(e)
203
+
204
+ templates = []
205
+ for tid in sorted(groups):
206
+ members = sorted(groups[tid], key=lambda e: e['page'])
207
+ rep = members[0]
208
+ rep_h = rep['hashes']
209
+ divergence = []
210
+ for m in members[1:]:
211
+ for view in _DIVERGENCE_VIEWS:
212
+ regions = set(rep_h[view]) | set(m['hashes'][view])
213
+ for r in sorted(regions):
214
+ if rep_h[view].get(r) != m['hashes'][view].get(r):
215
+ divergence.append({'page': m['page'],
216
+ 'region': r, 'view': view})
217
+ templates.append({
218
+ 'template': tid,
219
+ 'pages': [m['page'] for m in members],
220
+ 'page_count': len(members),
221
+ 'representative': rep['page'],
222
+ 'divergence': divergence,
223
+ })
224
+
225
+ return {
226
+ 'mode': 'template-fingerprints',
227
+ 'pages_total': len(entries),
228
+ 'templates_total': len(templates),
229
+ 'views': list(VIEWS),
230
+ 'volatile_attrs_ignored': sorted(_VOLATILE),
231
+ 'pages': entries,
232
+ 'templates': templates,
233
+ 'sample_suggestion': sorted(t['representative'] for t in templates),
234
+ 'note': _NOTES['es' if lang == 'es' else 'en'],
235
+ }
236
+
237
+
238
+ def main(argv):
239
+ ap = argparse.ArgumentParser(description=__doc__)
240
+ ap.add_argument('pages', nargs='*', help='HTML pages to fingerprint')
241
+ ap.add_argument('--dir', help='also read every *.html/*.htm in this '
242
+ 'directory (sorted)')
243
+ ap.add_argument('--lang', default='en', choices=['en', 'es'])
244
+ ap.add_argument('-o', '--out', help='also write the report to this file')
245
+ a = ap.parse_args(argv)
246
+
247
+ names = list(a.pages)
248
+ if a.dir:
249
+ for f in sorted(os.listdir(a.dir)):
250
+ if f.lower().endswith(('.html', '.htm')):
251
+ names.append(os.path.join(a.dir, f))
252
+ if not names:
253
+ ap.error('no pages: pass pages and/or --dir')
254
+
255
+ pages = []
256
+ for name in names:
257
+ with open(name, encoding='utf-8', errors='replace') as f:
258
+ pages.append({'page': name, 'html': f.read()})
259
+
260
+ report = fingerprint_pages(pages, lang=a.lang)
261
+ text = json.dumps(report, ensure_ascii=False, indent=1)
262
+ if a.out:
263
+ with open(a.out, 'w', encoding='utf-8') as f:
264
+ f.write(text + '\n')
265
+ print(text)
266
+ return 0
267
+
268
+
269
+ if __name__ == '__main__':
270
+ sys.exit(main(sys.argv[1:]))
@@ -87,7 +87,7 @@ try:
87
87
  except ImportError:
88
88
  ARIALIVE_JS = None # repo checkout: read the file
89
89
 
90
- VERSION = '5.23.0'
90
+ VERSION = '5.24.0'
91
91
 
92
92
  # Params renombrados a inglés en 5.11.0; se aceptan los nombres previos.
93
93
  PARAM_ALIASES = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kinti/a11y-toolkit",
3
- "version": "5.23.0",
3
+ "version": "5.24.0",
4
4
  "description": "Zero-dependency WCAG 2.2 accessibility engine (34 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.",
5
5
  "license": "MIT",
6
6
  "repository": {