@kinti/a11y-toolkit 5.22.1 → 5.22.3
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.
- package/LICENSE +21 -0
- package/a11y_toolkit/__init__.py +5 -0
- package/a11y_toolkit/a11y.py +117 -0
- package/a11y_toolkit/a11yact.py +167 -0
- package/a11y_toolkit/a11yaudit.py +1951 -0
- package/a11y_toolkit/a11ybadge.py +102 -0
- package/a11y_toolkit/a11ybudget.py +122 -0
- package/a11y_toolkit/a11ycrit.py +1017 -0
- package/a11y_toolkit/a11ydiff.py +192 -0
- package/a11y_toolkit/a11ydisprove.py +175 -0
- package/a11y_toolkit/a11ydocx.py +132 -0
- package/a11y_toolkit/a11ydom.py +1831 -0
- package/a11y_toolkit/a11yevidence.py +272 -0
- package/a11y_toolkit/a11yfix.py +330 -0
- package/a11y_toolkit/a11yi18n.py +100 -0
- package/a11y_toolkit/a11yinit.py +113 -0
- package/a11y_toolkit/a11yjourney.py +284 -0
- package/a11y_toolkit/a11yledger.py +210 -0
- package/a11y_toolkit/a11ymutants.py +406 -0
- package/a11y_toolkit/a11yopenacr.py +207 -0
- package/a11y_toolkit/a11ypdf.py +273 -0
- package/a11y_toolkit/a11yroute.py +378 -0
- package/a11y_toolkit/a11ysarif.py +139 -0
- package/a11y_toolkit/a11yscroll.py +212 -0
- package/a11y_toolkit/a11ystatement.py +158 -0
- package/a11y_toolkit/a11yvalidate.py +127 -0
- package/a11y_toolkit/a11yvpat.py +238 -0
- package/a11y_toolkit/a11yvtt.py +136 -0
- package/a11y_toolkit/a11ywcag3.py +262 -0
- package/a11y_toolkit/a11ywcagem.py +177 -0
- package/a11y_toolkit/arialive.js +107 -0
- package/a11y_toolkit/arialive_js.py +113 -0
- package/a11y_toolkit/contrast.py +536 -0
- package/a11y_toolkit/locales/_template.json +468 -0
- package/a11y_toolkit/locales/en.json +525 -0
- package/a11y_toolkit/locales/es.json +525 -0
- package/a11y_toolkit/server.py +1529 -0
- package/package.json +7 -2
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Coverage ledger — accumulated audit knowledge across runs (Cloudflare pattern).
|
|
3
|
+
|
|
4
|
+
The lesson from Cloudflare's security-audit-skill: no single pass is complete,
|
|
5
|
+
and prior runs should inform (not replace) the current one. This module
|
|
6
|
+
maintains a persistent ledger of what has been audited, when, and with what
|
|
7
|
+
result — so subsequent runs can:
|
|
8
|
+
|
|
9
|
+
- Skip unchanged criteria on unchanged pages (carry forward)
|
|
10
|
+
- Re-audit pages whose hash changed
|
|
11
|
+
- Target gaps (criteria never checked on a page)
|
|
12
|
+
|
|
13
|
+
The ledger is a JSON file you keep next to your project. It integrates with
|
|
14
|
+
the evidence pack: a ledger IS the evidence pack accumulated over time.
|
|
15
|
+
|
|
16
|
+
CLI:
|
|
17
|
+
a11yledger.py record --url https://x --audit report.json [--ledger ledger.json]
|
|
18
|
+
a11yledger.py gaps --url https://x [--ledger ledger.json]
|
|
19
|
+
a11yledger.py summary [--ledger ledger.json]
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
import argparse
|
|
23
|
+
import hashlib
|
|
24
|
+
import json
|
|
25
|
+
import os
|
|
26
|
+
import sys
|
|
27
|
+
from datetime import datetime, timezone
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
import tempfile
|
|
31
|
+
|
|
32
|
+
from .a11yaudit import normalize_signal # noqa: E402 (compat 5.10)
|
|
33
|
+
|
|
34
|
+
# per-path lock: always multi-thread; multi-process on POSIX (fcntl).
|
|
35
|
+
# Without it, two concurrent writes left a truncated JSON (external review
|
|
36
|
+
# 2026-10) — schedulers and interactive writers coexist here.
|
|
37
|
+
_LOCKS = {}
|
|
38
|
+
|
|
39
|
+
from contextlib import contextmanager
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@contextmanager
|
|
43
|
+
def _lock(path):
|
|
44
|
+
import threading
|
|
45
|
+
lk = _LOCKS.setdefault(os.path.abspath(path), threading.Lock())
|
|
46
|
+
with lk:
|
|
47
|
+
fd = None
|
|
48
|
+
try:
|
|
49
|
+
try:
|
|
50
|
+
import fcntl
|
|
51
|
+
fd = open(os.path.abspath(path) + '.lock', 'w')
|
|
52
|
+
fcntl.flock(fd, fcntl.LOCK_EX)
|
|
53
|
+
except ImportError:
|
|
54
|
+
pass # Windows: solo lock de hilo (documentado)
|
|
55
|
+
yield
|
|
56
|
+
finally:
|
|
57
|
+
if fd:
|
|
58
|
+
fd.close() # libera el flock
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _load(path='a11y-ledger.json'):
|
|
62
|
+
if os.path.exists(path):
|
|
63
|
+
try:
|
|
64
|
+
with open(path, encoding='utf-8') as f:
|
|
65
|
+
ledger = json.load(f)
|
|
66
|
+
for e in ledger.get('entries', {}).values():
|
|
67
|
+
e['active_signals'] = sorted(normalize_signal(x) for x in e.get('active_signals', []))
|
|
68
|
+
e['resolved_signals'] = sorted(normalize_signal(x) for x in e.get('resolved_signals', []))
|
|
69
|
+
# renames de claves 5.11.0 (por si un proceso antiguo reescribe después)
|
|
70
|
+
e['last_audit'] = e.pop('ultimo_audit') if 'ultimo_audit' in e else e.get('last_audit')
|
|
71
|
+
return ledger
|
|
72
|
+
except json.JSONDecodeError:
|
|
73
|
+
# corrupto (crash a mitad de escritura de una versión anterior):
|
|
74
|
+
# no arrastrar la corrupción — aislar y empezar limpio
|
|
75
|
+
os.replace(path, path + '.corrupto-' + datetime.now(timezone.utc)
|
|
76
|
+
.strftime('%Y%m%dT%H%M%SZ'))
|
|
77
|
+
return {'version': 1, 'entries': {}, 'history': []}
|
|
78
|
+
return {'version': 1, 'entries': {}, 'history': []}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _save(ledger, path='a11y-ledger.json'):
|
|
82
|
+
# escritura atómica: tempfile EN EL MISMO DIRECTORIO + os.replace —
|
|
83
|
+
# un crash a mitad nunca deja el fichero a medias
|
|
84
|
+
d = os.path.dirname(os.path.abspath(path)) or '.'
|
|
85
|
+
temporal = None
|
|
86
|
+
try:
|
|
87
|
+
with tempfile.NamedTemporaryFile('w', encoding='utf-8', dir=d,
|
|
88
|
+
delete=False, suffix='.tmp') as f:
|
|
89
|
+
temporal = f.name
|
|
90
|
+
json.dump(ledger, f, ensure_ascii=False, indent=1)
|
|
91
|
+
f.flush()
|
|
92
|
+
os.fsync(f.fileno())
|
|
93
|
+
os.replace(temporal, path)
|
|
94
|
+
except BaseException:
|
|
95
|
+
if temporal and os.path.exists(temporal):
|
|
96
|
+
os.unlink(temporal)
|
|
97
|
+
raise
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def record(url, report, ledger=None, path='a11y-ledger.json'):
|
|
101
|
+
"""Record an audit result in the ledger (thread/process safe)."""
|
|
102
|
+
with _lock(path):
|
|
103
|
+
return _record(url, report, ledger=ledger, path=path)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _hash_url(url):
|
|
107
|
+
return hashlib.sha256(url.encode()).hexdigest()[:16]
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _record(url, report, ledger=None, path='a11y-ledger.json'):
|
|
111
|
+
if ledger is None:
|
|
112
|
+
ledger = _load(path)
|
|
113
|
+
now = datetime.now(timezone.utc).isoformat(timespec='seconds')
|
|
114
|
+
entry_key = _hash_url(url)
|
|
115
|
+
|
|
116
|
+
# señales activas y score
|
|
117
|
+
signals = sorted({normalize_signal(h.get('signal', '')) for h in report.get('findings', [])})
|
|
118
|
+
score = report.get('score')
|
|
119
|
+
|
|
120
|
+
entry = {
|
|
121
|
+
'url': url,
|
|
122
|
+
'last_audit': now,
|
|
123
|
+
'score': score,
|
|
124
|
+
'previous_score': ledger['entries'].get(entry_key, {}).get('score'),
|
|
125
|
+
'active_signals': signals,
|
|
126
|
+
'resolved_signals': sorted(
|
|
127
|
+
set(ledger['entries'].get(entry_key, {}).get('active_signals', [])) - set(signals)
|
|
128
|
+
),
|
|
129
|
+
'mode': report.get('mode', 'static'),
|
|
130
|
+
'disprover': report.get('disprover'),
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
ledger['entries'][entry_key] = entry
|
|
134
|
+
ledger['history'].append({
|
|
135
|
+
'ts': now, 'url': url, 'score': score,
|
|
136
|
+
'change': 'new' if entry['previous_score'] is None else
|
|
137
|
+
f"{entry['previous_score']}→{score}",
|
|
138
|
+
'resolved': len(entry['resolved_signals']),
|
|
139
|
+
})
|
|
140
|
+
_save(ledger, path)
|
|
141
|
+
return entry
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def gaps(url, ledger=None, path='a11y-ledger.json'):
|
|
145
|
+
"""What has never been checked on this URL?"""
|
|
146
|
+
if ledger is None:
|
|
147
|
+
ledger = _load(path)
|
|
148
|
+
from .a11yaudit import CRIT
|
|
149
|
+
entry_key = _hash_url(url)
|
|
150
|
+
entry = ledger['entries'].get(entry_key)
|
|
151
|
+
if not entry:
|
|
152
|
+
return {'url': url, 'status': 'never_audited',
|
|
153
|
+
'criteria_without_signal': len(CRIT['en'])}
|
|
154
|
+
audited = set(entry.get('active_signals', []))
|
|
155
|
+
return {
|
|
156
|
+
'url': url,
|
|
157
|
+
'status': 'audited',
|
|
158
|
+
'last_audit': entry.get('last_audit') or entry.get('ultimo_audit'),
|
|
159
|
+
'score': entry['score'],
|
|
160
|
+
'resolved_signals': entry.get('resolved_signals', []),
|
|
161
|
+
'note': ('re-audit this URL if its content changed since '
|
|
162
|
+
+ (entry.get('last_audit') or entry.get('ultimo_audit'))),
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def summary(ledger=None, path='a11y-ledger.json'):
|
|
167
|
+
"""Summary of the ledger."""
|
|
168
|
+
if ledger is None:
|
|
169
|
+
ledger = _load(path)
|
|
170
|
+
entries = ledger['entries']
|
|
171
|
+
if not entries:
|
|
172
|
+
return {'total_urls': 0, 'note': 'ledger empty — run your first audit'}
|
|
173
|
+
scores = [e.get('score', 0) for e in entries.values() if e.get('score') is not None]
|
|
174
|
+
return {
|
|
175
|
+
'total_urls': len(entries),
|
|
176
|
+
'mean_score': round(sum(scores) / len(scores)) if scores else None,
|
|
177
|
+
'worst_score': min(scores) if scores else None,
|
|
178
|
+
'best_score': max(scores) if scores else None,
|
|
179
|
+
'total_resolved': sum(len(e.get('resolved_signals', [])) for e in entries.values()),
|
|
180
|
+
'recent': ledger['history'][-5:],
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def main(argv):
|
|
185
|
+
ap = argparse.ArgumentParser(description='Coverage ledger')
|
|
186
|
+
sub = ap.add_subparsers(dest='cmd', required=True)
|
|
187
|
+
s1 = sub.add_parser('record')
|
|
188
|
+
s1.add_argument('--url', required=True)
|
|
189
|
+
s1.add_argument('--audit', required=True, help='audit report JSON file')
|
|
190
|
+
s1.add_argument('--ledger', default='a11y-ledger.json')
|
|
191
|
+
s2 = sub.add_parser('gaps')
|
|
192
|
+
s2.add_argument('--url', required=True)
|
|
193
|
+
s2.add_argument('--ledger', default='a11y-ledger.json')
|
|
194
|
+
s3 = sub.add_parser('summary')
|
|
195
|
+
s3.add_argument('--ledger', default='a11y-ledger.json')
|
|
196
|
+
a = ap.parse_args(argv)
|
|
197
|
+
if a.cmd == 'record':
|
|
198
|
+
with open(a.audit, encoding='utf-8') as f:
|
|
199
|
+
report = json.load(f)
|
|
200
|
+
r = record(a.url, report, path=a.ledger)
|
|
201
|
+
print(json.dumps(r, ensure_ascii=False, indent=1))
|
|
202
|
+
elif a.cmd == 'gaps':
|
|
203
|
+
print(json.dumps(gaps(a.url, path=a.ledger), ensure_ascii=False, indent=1))
|
|
204
|
+
elif a.cmd == 'summary':
|
|
205
|
+
print(json.dumps(summary(path=a.ledger), ensure_ascii=False, indent=1))
|
|
206
|
+
return 0
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
if __name__ == '__main__':
|
|
210
|
+
sys.exit(main(sys.argv[1:]))
|
|
@@ -0,0 +1,406 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""a11y_mutants — the engine's sealed exam (WCAG mutation testing).
|
|
3
|
+
|
|
4
|
+
Cross-industry translation: mutation testing — inject known defects into a
|
|
5
|
+
working program and count what the test suite kills — applied to
|
|
6
|
+
accessibility evaluation. The generator builds a CLEAN page that varies
|
|
7
|
+
with the seed, injects ONE violation per mutant (each operator derived
|
|
8
|
+
from the toolkit's own signal→criterion map), and keeps the sealed answer
|
|
9
|
+
log (operator + expected signal + criterion). Same seed = same exam, to
|
|
10
|
+
compare auditors fairly; fresh seed = an exam nobody has memorized.
|
|
11
|
+
|
|
12
|
+
Placebo control pages (clean, no violation injected) catch false
|
|
13
|
+
positives: any finding on them is a false positive by construction.
|
|
14
|
+
|
|
15
|
+
This is a self-exam, not a tool (D17): the engine that publishes its own
|
|
16
|
+
kill rate is an engine that can be measured. CLI:
|
|
17
|
+
|
|
18
|
+
a11ymutants.py --seed 7 --n 12 [--out exam-dir]
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
import argparse
|
|
22
|
+
import json
|
|
23
|
+
import os
|
|
24
|
+
import random
|
|
25
|
+
import re
|
|
26
|
+
import sys
|
|
27
|
+
|
|
28
|
+
from .a11yaudit import audit_html, normalize_signal
|
|
29
|
+
|
|
30
|
+
# ── página limpia regenerable ──────────────────────────────────────────────
|
|
31
|
+
# La estructura es siempre accesible; el contenido varía por semilla (títulos,
|
|
32
|
+
# nº de imágenes, textos). El test clava los placebos a CERO hallazgos: si
|
|
33
|
+
# alguien rompe una plantilla limpia, la suite se tiñe.
|
|
34
|
+
_WORDS = {
|
|
35
|
+
'title': ['Quarterly accessibility report', 'Service dashboard guide',
|
|
36
|
+
'Inclusion handbook for editors', 'Regional transit study',
|
|
37
|
+
'Public library annual review', 'Water quality summary'],
|
|
38
|
+
'h1': ['Accessibility report', 'Service overview', 'Editorial handbook',
|
|
39
|
+
'Transit study', 'Annual review', 'Water quality summary'],
|
|
40
|
+
'h2': ['Key findings', 'Methodology', 'Recommendations', 'Data summary',
|
|
41
|
+
'Next steps', 'Background', 'Annexes'],
|
|
42
|
+
'alt': ['Bar chart comparing audit scores by quarter',
|
|
43
|
+
'Map of stations audited this year',
|
|
44
|
+
'Team reviewing a document together',
|
|
45
|
+
'Cover of the printed handbook',
|
|
46
|
+
'Flow diagram of the review process',
|
|
47
|
+
'Photo of the reading room'],
|
|
48
|
+
'nav': ['Findings', 'Method', 'Data', 'Contact', 'About', 'Archive'],
|
|
49
|
+
'btn': ['Download the full report', 'Start the survey', 'Show details',
|
|
50
|
+
'Print this page', 'Export as CSV'],
|
|
51
|
+
'field': [('Report title', 'report'), ('Your reference', 'reference'),
|
|
52
|
+
('Notes', 'notes'), ('Keywords', 'keywords'),
|
|
53
|
+
('Project code', 'project')],
|
|
54
|
+
'li': ['Plain language summaries for every finding',
|
|
55
|
+
'Keyboard-only walkthrough of the checkout flow',
|
|
56
|
+
'Contrast measurements with the exact ratios',
|
|
57
|
+
'Captions reviewed against the audio track',
|
|
58
|
+
'Focus order verified on every dialog',
|
|
59
|
+
'Forms submitted empty to judge the error messages'],
|
|
60
|
+
'iframe': ['Monthly satisfaction chart', 'Station occupancy map',
|
|
61
|
+
'Feedback form summary', 'Reading room calendar'],
|
|
62
|
+
'para': ['This report summarizes the quarterly review and lists the '
|
|
63
|
+
'corrective actions already shipped by each team.',
|
|
64
|
+
'Every number in this page was measured twice and cross-checked '
|
|
65
|
+
'against the raw data set before publication.',
|
|
66
|
+
'The review followed the published methodology and was verified '
|
|
67
|
+
'by a second reader before the editor approved it.'],
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
# el input de email es el objetivo del operador autocomplete_removed: su name
|
|
71
|
+
# ("email") es dato personal a ojos del motor y su autocomplete lo mantiene
|
|
72
|
+
# limpio mientras no se lo quiten
|
|
73
|
+
_EMAIL_FIELD = ('<label for="field-b">Work email</label>\n'
|
|
74
|
+
'<input id="field-b" name="email" type="email" autocomplete="email">')
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def base_page(rng):
|
|
78
|
+
"""Página limpia (cero hallazgos) con ranuras donde operan los mutantes."""
|
|
79
|
+
n_imgs = rng.randint(3, 5)
|
|
80
|
+
n_btns = rng.randint(2, 4)
|
|
81
|
+
n_links = rng.randint(3, 5)
|
|
82
|
+
n_lis = rng.randint(3, 5)
|
|
83
|
+
f1, n1 = rng.choice(_WORDS['field'])
|
|
84
|
+
f2, n2 = rng.choice(_WORDS['field'])
|
|
85
|
+
nav = '\n'.join(f'<li><a href="/{w.lower()}">{w}</a></li>'
|
|
86
|
+
for w in rng.sample(_WORDS['nav'], n_links))
|
|
87
|
+
imgs = '\n'.join(f'<img src="figure-{i}.png" alt="{rng.choice(_WORDS["alt"])}">'
|
|
88
|
+
for i in range(1, n_imgs + 1))
|
|
89
|
+
btns = '\n'.join(f'<button type="button" id="act-{i}">{rng.choice(_WORDS["btn"])}'
|
|
90
|
+
f'</button>' for i in range(1, n_btns + 1))
|
|
91
|
+
lis = '\n'.join(f'<li>{rng.choice(_WORDS["li"])}</li>' for _ in range(n_lis))
|
|
92
|
+
h2s = rng.sample(_WORDS['h2'], 3)
|
|
93
|
+
return f'''<!doctype html>
|
|
94
|
+
<html lang="en">
|
|
95
|
+
<head>
|
|
96
|
+
<meta charset="utf-8">
|
|
97
|
+
<title>{rng.choice(_WORDS['title'])}</title>
|
|
98
|
+
</head>
|
|
99
|
+
<body>
|
|
100
|
+
<a href="#main" class="skip">Skip to content</a>
|
|
101
|
+
<header>
|
|
102
|
+
<nav aria-label="Primary">
|
|
103
|
+
<ul>
|
|
104
|
+
{nav}
|
|
105
|
+
</ul>
|
|
106
|
+
</nav>
|
|
107
|
+
</header>
|
|
108
|
+
<main id="main">
|
|
109
|
+
<h1>{rng.choice(_WORDS['h1'])}</h1>
|
|
110
|
+
<p>{rng.choice(_WORDS['para'])}</p>
|
|
111
|
+
<h2>{h2s[0]}</h2>
|
|
112
|
+
{imgs}
|
|
113
|
+
<h2>{h2s[1]}</h2>
|
|
114
|
+
<p>{rng.choice(_WORDS['para'])}</p>
|
|
115
|
+
<ul>
|
|
116
|
+
{lis}
|
|
117
|
+
</ul>
|
|
118
|
+
<h2>{h2s[2]}</h2>
|
|
119
|
+
{btns}
|
|
120
|
+
<label for="field-a">{f1}</label>
|
|
121
|
+
<input id="field-a" name="{n1}" type="text">
|
|
122
|
+
{_EMAIL_FIELD}
|
|
123
|
+
<label for="field-c">{f2}</label>
|
|
124
|
+
<input id="field-c" name="{n2}" type="text">
|
|
125
|
+
<iframe src="panel-1.html" title="{rng.choice(_WORDS['iframe'])}"></iframe>
|
|
126
|
+
</main>
|
|
127
|
+
</body>
|
|
128
|
+
</html>'''
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
# ── utilidades de cirugía ──────────────────────────────────────────────────
|
|
132
|
+
def _pick(pattern, html, rng):
|
|
133
|
+
"""El k-ésimo match (k al azar): el mismo operador cae en objetivo distinto."""
|
|
134
|
+
ms = list(re.finditer(pattern, html))
|
|
135
|
+
if not ms:
|
|
136
|
+
return None
|
|
137
|
+
return ms[rng.randrange(len(ms))]
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _splice(html, m, new):
|
|
141
|
+
return html[:m.start()] + new + html[m.end():]
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _src(tag_str):
|
|
145
|
+
s = re.search(r'src="([^"]*)"', tag_str)
|
|
146
|
+
return s.group(1) if s else '?'
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
# ── operadores: cada uno inyecta UNA violación con respuesta sellada ───────
|
|
150
|
+
# Señal y criterio salen del mapa del propio motor (test de integridad).
|
|
151
|
+
OPERATORS = []
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _op(name, signal, criterion, apply):
|
|
155
|
+
OPERATORS.append({'op': name, 'signal': signal, 'criterion': criterion,
|
|
156
|
+
'apply': apply})
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _img_alt_removed(html, rng):
|
|
160
|
+
m = _pick(r'<img\b[^>]*>', html, rng)
|
|
161
|
+
return _splice(html, m, re.sub(r'\s+alt="[^"]*"', '', m.group(0), count=1)), \
|
|
162
|
+
f'alt removed from <img src="{_src(m.group(0))}">'
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _button_name_removed(html, rng):
|
|
166
|
+
m = _pick(r'<button type="button"[^>]*>[^<]*</button>', html, rng)
|
|
167
|
+
return _splice(html, m, re.sub(r'>[^<]*</button>', '></button>',
|
|
168
|
+
m.group(0), count=1)), 'text removed from a button'
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _field_label_removed(html, rng):
|
|
172
|
+
m = _pick(r'<label for="field-[ac]">[^<]*</label>\s*', html, rng)
|
|
173
|
+
target = m.group(0).split('"')[1] # field-a / field-c
|
|
174
|
+
return html[:m.start()] + html[m.end():], f'label removed from input {target}'
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _lang_missing(html, rng):
|
|
178
|
+
return html.replace('<html lang="en">', '<html>', 1), 'lang attribute removed'
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _lang_invalid(html, rng):
|
|
182
|
+
return html.replace('<html lang="en">', '<html lang="xyz">', 1), 'lang="xyz"'
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _title_emptied(html, rng):
|
|
186
|
+
m = re.search(r'<title>[^<]*</title>', html)
|
|
187
|
+
return _splice(html, m, '<title></title>'), 'title emptied'
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _zoom_locked(html, rng):
|
|
191
|
+
return html.replace('<meta charset="utf-8">',
|
|
192
|
+
'<meta charset="utf-8">\n'
|
|
193
|
+
'<meta name="viewport" content="width=device-width, '
|
|
194
|
+
'user-scalable=no">', 1), 'viewport user-scalable=no'
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _refresh_injected(html, rng):
|
|
198
|
+
secs = rng.randint(2, 30)
|
|
199
|
+
return html.replace('<meta charset="utf-8">',
|
|
200
|
+
f'<meta charset="utf-8">\n'
|
|
201
|
+
f'<meta http-equiv="refresh" content="{secs}">', 1), \
|
|
202
|
+
f'meta refresh {secs}s'
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _tabindex_positive(html, rng):
|
|
206
|
+
m = _pick(r'<a href="/[^"]*">', html, rng)
|
|
207
|
+
return _splice(html, m, m.group(0)[:-1] + f' tabindex="{rng.randint(2, 9)}">'), \
|
|
208
|
+
'positive tabindex on a nav link'
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _iframe_title_removed(html, rng):
|
|
212
|
+
m = _pick(r'<iframe\b[^>]*>', html, rng)
|
|
213
|
+
return _splice(html, m, re.sub(r'\s+title="[^"]*"', '', m.group(0), count=1)), \
|
|
214
|
+
f'title removed from <iframe src="{_src(m.group(0))}">'
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _video_no_track(html, rng):
|
|
218
|
+
k = rng.randint(1, 9)
|
|
219
|
+
return html.replace('</main>',
|
|
220
|
+
f'<video controls width="480" height="270" '
|
|
221
|
+
f'src="clip-{k}.mp4"></video>\n</main>', 1), \
|
|
222
|
+
f'<video src="clip-{k}.mp4"> without captions track'
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _div_onclick(html, rng):
|
|
226
|
+
return html.replace('</main>',
|
|
227
|
+
'<div onclick="togglePanel()">Show the interactive '
|
|
228
|
+
'panel</div>\n</main>', 1), 'onclick on a non-focusable div'
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _blank_unwarned(html, rng):
|
|
232
|
+
k = rng.randint(1, 9)
|
|
233
|
+
return html.replace('</main>',
|
|
234
|
+
f'<p>See the <a href="https://example.org/data/{k}" '
|
|
235
|
+
f'target="_blank">open data set</a> behind these '
|
|
236
|
+
f'numbers.</p>\n</main>', 1), \
|
|
237
|
+
f'target=_blank link without new-window warning'
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _autocomplete_removed(html, rng):
|
|
241
|
+
return html.replace(' autocomplete="email"', '', 1), \
|
|
242
|
+
'autocomplete="email" removed from the email input'
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _heading_skip(html, rng):
|
|
246
|
+
m = _pick(r'<h2>[^<]*</h2>', html, rng)
|
|
247
|
+
return _splice(html, m, m.group(0).replace('<h2>', '<h4>', 1)
|
|
248
|
+
.replace('</h2>', '</h4>', 1)), \
|
|
249
|
+
f'{m.group(0)[:44]}… demoted to h4'
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _id_duplicated(html, rng):
|
|
253
|
+
# el 2º botón roba el id del 1º (n_btns ≥ 2 garantizado en base_page)
|
|
254
|
+
return html.replace('id="act-2"', 'id="act-1"', 1), \
|
|
255
|
+
'button id act-2 duplicated as act-1'
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _aria_ref_broken(html, rng):
|
|
259
|
+
m = _pick(r'<button type="button" id="act-\d+">', html, rng)
|
|
260
|
+
return _splice(html, m, m.group(0)[:-1] + ' aria-labelledby="missing-ref">'), \
|
|
261
|
+
'aria-labelledby points to a non-existent id'
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _list_item_div(html, rng):
|
|
265
|
+
# solo los <li> de TEXTO (los del nav llevan <a>): div como hijo directo
|
|
266
|
+
# de <ul> rompe la estructura de lista
|
|
267
|
+
m = _pick(r'<li>(?=[A-Z])[^<]*</li>', html, rng)
|
|
268
|
+
return _splice(html, m, m.group(0).replace('<li>', '<div>', 1)
|
|
269
|
+
.replace('</li>', '</div>', 1)), \
|
|
270
|
+
f'{m.group(0)[:44]}… became a div inside the ul'
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
_op('img_alt_removed', 'img_no_alt', '1.1.1', _img_alt_removed)
|
|
274
|
+
_op('button_name_removed', 'ctrl_name', '4.1.2', _button_name_removed)
|
|
275
|
+
_op('field_label_removed', 'field_label', '3.3.2', _field_label_removed)
|
|
276
|
+
_op('lang_missing', 'lang_missing', '3.1.1', _lang_missing)
|
|
277
|
+
_op('lang_invalid', 'lang_invalid', '3.1.1', _lang_invalid)
|
|
278
|
+
_op('title_emptied', 'title_missing', '2.4.2', _title_emptied)
|
|
279
|
+
_op('zoom_locked', 'zoom_no', '1.4.4', _zoom_locked)
|
|
280
|
+
_op('refresh_injected', 'meta_refresh', '2.2.1', _refresh_injected)
|
|
281
|
+
_op('tabindex_positive', 'tabindex_pos', '2.4.3', _tabindex_positive)
|
|
282
|
+
_op('iframe_title_removed', 'iframe_title', '4.1.2', _iframe_title_removed)
|
|
283
|
+
_op('video_no_track', 'video_captions', '1.2.2', _video_no_track)
|
|
284
|
+
_op('div_onclick', 'click_nonfocusable', '2.1.1', _div_onclick)
|
|
285
|
+
_op('blank_unwarned', 'blank_no_warning', '3.2.5', _blank_unwarned)
|
|
286
|
+
_op('autocomplete_removed', 'autocomplete', '1.3.5', _autocomplete_removed)
|
|
287
|
+
_op('heading_skip', 'heading_skips', '1.3.1', _heading_skip)
|
|
288
|
+
_op('id_duplicated', 'dup_ids', '4.1.2', _id_duplicated)
|
|
289
|
+
_op('aria_ref_broken', 'aria_ref_missing', '4.1.2', _aria_ref_broken)
|
|
290
|
+
_op('list_item_div', 'list_structure', '1.3.1', _list_item_div)
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
# ── examen ─────────────────────────────────────────────────────────────────
|
|
294
|
+
_NOTE_EXAM = {
|
|
295
|
+
'es': ('Un hallazgo sobre una página placebo es un falso positivo por '
|
|
296
|
+
'construcción. El sobre sellado (operador/señal/criterio) se '
|
|
297
|
+
'abre solo después de puntuar.'),
|
|
298
|
+
'en': ('Findings on placebo control pages are false positives by '
|
|
299
|
+
'construction. Sealed answers (operator/signal/criterion) open '
|
|
300
|
+
'only after scoring.'),
|
|
301
|
+
}
|
|
302
|
+
def generate(seed=7, n=12):
|
|
303
|
+
"""Examen determinista: n mutantes (operadores al azar sobre páginas
|
|
304
|
+
distintas por semilla) + placebos de control."""
|
|
305
|
+
rng = random.Random(seed)
|
|
306
|
+
ops = list(OPERATORS)
|
|
307
|
+
if n <= len(ops):
|
|
308
|
+
chosen = rng.sample(ops, max(n, 0))
|
|
309
|
+
else:
|
|
310
|
+
chosen = []
|
|
311
|
+
while len(chosen) < n:
|
|
312
|
+
shuffled = ops[:]
|
|
313
|
+
rng.shuffle(shuffled)
|
|
314
|
+
chosen += shuffled
|
|
315
|
+
chosen = chosen[:n]
|
|
316
|
+
# semillas hijas por ENTEROS (no str): estables entre procesos y versiones
|
|
317
|
+
mutants = []
|
|
318
|
+
for i, op in enumerate(chosen):
|
|
319
|
+
prng = random.Random(seed * 1000003 + 7 * i + 13)
|
|
320
|
+
html = base_page(prng)
|
|
321
|
+
html2, detail = op['apply'](html, prng)
|
|
322
|
+
mutants.append({'id': f'm{seed}-{i}', 'html': html2,
|
|
323
|
+
'sealed': {'operator': op['op'], 'signal': op['signal'],
|
|
324
|
+
'criterion': op['criterion'], 'detail': detail}})
|
|
325
|
+
# placebos de control: páginas limpias del mismo generador
|
|
326
|
+
controls = []
|
|
327
|
+
for j in range(max(1, n // 6)):
|
|
328
|
+
prng = random.Random(seed * 999331 + 101 * j + 7)
|
|
329
|
+
controls.append({'id': f'p{seed}-{j}', 'html': base_page(prng),
|
|
330
|
+
'sealed': {'operator': 'placebo', 'signal': None,
|
|
331
|
+
'criterion': None,
|
|
332
|
+
'detail': 'no violation injected'}})
|
|
333
|
+
return {'seed': seed, 'n': n, 'mutants': mutants, 'control_pages': controls}
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def run_exam(seed=7, n=12, engine=None, lang='en'):
|
|
337
|
+
"""Corre el examen contra un evaluador (por defecto, el propio motor) y
|
|
338
|
+
abre el sobre SOLO después de puntuar: kill rate + falsos positivos.
|
|
339
|
+
El evaluador externo puede firmar (html) o (html, lang=): el examen se
|
|
340
|
+
adapta a su firma — medir a otros es el punto del módulo."""
|
|
341
|
+
import inspect
|
|
342
|
+
eng = engine or audit_html
|
|
343
|
+
_takes_lang = 'lang' in inspect.signature(eng).parameters
|
|
344
|
+
|
|
345
|
+
def _call(h):
|
|
346
|
+
return eng(h, lang='en') if _takes_lang else eng(h)
|
|
347
|
+
exam = generate(seed, n)
|
|
348
|
+
killed, missed, fps, per_op = [], [], [], {}
|
|
349
|
+
for m in exam['mutants']:
|
|
350
|
+
rep = _call(m['html'])
|
|
351
|
+
sigs = ({normalize_signal(h.get('signal', ''))
|
|
352
|
+
for h in rep.get('findings', [])}
|
|
353
|
+
if isinstance(rep, dict) else set())
|
|
354
|
+
op = m['sealed']['operator']
|
|
355
|
+
per_op.setdefault(op, {'total': 0, 'killed': 0})
|
|
356
|
+
per_op[op]['total'] += 1
|
|
357
|
+
if m['sealed']['signal'] in sigs:
|
|
358
|
+
killed.append(m['id'])
|
|
359
|
+
per_op[op]['killed'] += 1
|
|
360
|
+
else:
|
|
361
|
+
missed.append({'id': m['id'], **m['sealed'], 'found_instead': sorted(sigs)})
|
|
362
|
+
for p in exam['control_pages']:
|
|
363
|
+
rep = _call(p['html'])
|
|
364
|
+
for h in (rep.get('findings', []) if isinstance(rep, dict) else []):
|
|
365
|
+
fps.append({'control_page': p['id'],
|
|
366
|
+
'signal': normalize_signal(h.get('signal', ''))})
|
|
367
|
+
total = len(exam['mutants'])
|
|
368
|
+
return {
|
|
369
|
+
'mode': 'mutant-exam', 'seed': seed, 'mutants': total,
|
|
370
|
+
'control_pages': len(exam['control_pages']),
|
|
371
|
+
'killed': len(killed), 'missed': len(missed),
|
|
372
|
+
'missed_detail': missed,
|
|
373
|
+
'kill_rate': round(len(killed) / total, 4) if total else None,
|
|
374
|
+
'false_positives': fps,
|
|
375
|
+
'per_operator': per_op,
|
|
376
|
+
'note': _NOTE_EXAM['es' if lang == 'es' else 'en'],
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def main(argv):
|
|
381
|
+
ap = argparse.ArgumentParser(description=__doc__)
|
|
382
|
+
ap.add_argument('--seed', type=int, default=7, help='exam id (same seed, same exam)')
|
|
383
|
+
ap.add_argument('--n', type=int, default=12, help='number of mutants')
|
|
384
|
+
ap.add_argument('--lang', default='en', choices=['en', 'es'])
|
|
385
|
+
ap.add_argument('--out', help='directory: writes each page + answers.json '
|
|
386
|
+
'(sealed log) for external examiners')
|
|
387
|
+
a = ap.parse_args(argv)
|
|
388
|
+
report = run_exam(a.seed, a.n, lang=a.lang)
|
|
389
|
+
if a.out:
|
|
390
|
+
exam = generate(a.seed, a.n)
|
|
391
|
+
os.makedirs(a.out, exist_ok=True)
|
|
392
|
+
for item in exam['mutants'] + exam['control_pages']:
|
|
393
|
+
with open(os.path.join(a.out, item['id'] + '.html'), 'w',
|
|
394
|
+
encoding='utf-8') as f:
|
|
395
|
+
f.write(item['html'])
|
|
396
|
+
with open(os.path.join(a.out, 'answers.json'), 'w', encoding='utf-8') as f:
|
|
397
|
+
json.dump({'seed': a.seed,
|
|
398
|
+
'sealed': [dict(i['sealed'], id=i['id'])
|
|
399
|
+
for i in exam['mutants']]}, f, indent=1)
|
|
400
|
+
report['out'] = a.out
|
|
401
|
+
print(json.dumps(report, ensure_ascii=False, indent=1))
|
|
402
|
+
return 0
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
if __name__ == '__main__':
|
|
406
|
+
sys.exit(main(sys.argv[1:]))
|