#!/usr/bin/env python3 """Landing page 审计门禁:结构可访问性 + 全量可见文字对比度扫描。 用法(在仓库根目录,先起静态服务): cd landing && python3 -m http.server 8099 --bind 127.0.0.1 /usr/bin/python3 scripts/landing-audit.py --url http://127.0.0.1:8099/ /usr/bin/python3 scripts/landing-audit.py --url http://127.0.0.1:8099/ --shots /tmp/out --json 分级判据(第四道 landing 门禁): 阻断级 P1(任一命中 → 退出码 1): - 同色前景/背景:`rgb(x, x, x) on rgb(x, x, x)`。**无条件阻断**,不受 --fail 影响—— 否则把 --fail 调到 ≤ 1.0 时同色(1.00:1)会静默放行,这正是 2026-11-04 Blocking① 的形态。 - 对比度 < --fail(默认 3.0,WCAG 大号文本线) - 结构项:横向溢出 / 缺 alt / 可聚焦元素无名称 / h1 数量 ≠ 1 警告级 P2(逐条打印,**退出码仍为 0**,须人工定夺,不得静默忽略): - 对比度落在 [--fail, --warn)(默认 4.5 = WCAG AA 正文线) - 焦点指示缺失 退出码:有阻断级 P1 → 1;仅警告级 P2 → 0。 结束行打印 `AUDIT_RESULT: PASS|FAIL` 及阻断/警告分项计数。 为什么扫「全量」而不是点选若干选择器:2026-11-04 的 Blocking①(屏 2 白底白字, 对比度 1.05:1)之所以从三道门禁缝里漏掉,是因为点选式断言只覆盖被想到的选择器。 本脚本改为遍历所有直接含文字的元素,并先解除动效的初始隐藏态 (js-grow / js-reveal / showcase-panel hidden),把每一屏都点亮后再测—— 包括当前不在视口内、以及 aria-hidden 装饰子树内的文字。 SVG 文字按 paint 的 fill 判,并以同组内先绘制的形状为底:否则会把继承来的 color(深色主题下是白)当成画出来的颜色,整片图谱标签误报 1.05:1。 """ from playwright.sync_api import sync_playwright import argparse, json, math, sys from pathlib import Path FAIL_MIN_DEFAULT = 3.0 # WCAG 大号文本线;低于此视为不可读 WARN_MIN_DEFAULT = 4.5 # WCAG 正文 AA 线 # 把所有动效门控的初始隐藏态解除,让每一屏、每一个生长元素都真实呈现后再测 REVEAL_ALL_JS = """ () => { const root = document.documentElement; root.classList.remove('js-grow', 'js-reveal'); document.querySelectorAll('.rv').forEach((el) => el.classList.add('in')); // 生长元素:直接落到终态 document.querySelectorAll('[data-grow]').forEach((host) => { host.classList.add('is-grown'); host.querySelectorAll('*').forEach((c) => c.classList.add('is-grown')); if (!host.querySelector('[data-grow]')) host.classList.add('is-grown'); }); // 轮播面板全部展开(默认 hidden + 非 active 不渲染) document.querySelectorAll('.showcase-panel').forEach((p) => { p.hidden = false; p.classList.add('active'); p.style.display = 'grid'; }); // 首屏演示:停在终态并暂停,避免计时器改 DOM const hero = document.querySelector('#heroDemo'); if (hero) hero.className = hero.className.replace(/demo-step-\\d/g, 'demo-final'); ['#showcasePause', '#demoPause'].forEach((sel) => { const b = document.querySelector(sel); if (b && b.getAttribute('aria-pressed') === 'false') b.click(); }); return { panels: document.querySelectorAll('.showcase-panel').length, heroClass: hero ? hero.className : null, }; } """ CONTRAST_SCAN_JS = """ (args) => { const {failMin, warnMin} = args; const parse = (s) => { if (!s) return null; const m = s.match(/rgba?\\(([^)]+)\\)/); if (!m) return null; const p = m[1].split(/[\\s,\\/]+/).filter(Boolean).map(parseFloat); if (p.length < 3 || p.some(isNaN)) return null; return {r: p[0], g: p[1], b: p[2], a: p.length > 3 ? p[3] : 1}; }; const chan = (c) => { c /= 255; return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4); }; const lum = (c) => 0.2126 * chan(c.r) + 0.7152 * chan(c.g) + 0.0722 * chan(c.b); const ratio = (fg, bg) => { const l1 = lum(fg) + 0.05, l2 = lum(bg) + 0.05; return l1 >= l2 ? l1 / l2 : l2 / l1; }; const over = (top, bottom) => ({ r: top.r * top.a + bottom.r * (1 - top.a), g: top.g * top.a + bottom.g * (1 - top.a), b: top.b * top.a + bottom.b * (1 - top.a), a: 1, }); const SVG_TEXT_TAGS = new Set(['text', 'tspan']); const isSvgText = (el) => SVG_TEXT_TAGS.has(el.tagName.toLowerCase()) && !!el.ownerSVGElement; // 前景:HTML 取 color;SVG 文字取 paint 的 fill(color 只是继承值,不是画出来的色) // // ⚠️ 返回的是**已解析但未合成**的色(可能带 alpha)。调用方必须在下结论前用 // compositeFg() 把前景叠到真实背景上——**不要直接拿它算 ratio**,见下方长注释。 const fgOf = (el, st) => { if (isSvgText(el)) { if (st.fill === 'none') return null; const f = parse(st.fill); return f && f.a > 0 ? f : null; } return parse(st.color); }; // 前景按背景合成。 // // 【为什么必须有这一步 —— 2026-11-07 §28.2 评审 BLOCK 落项】 // ratio() 只吃 rgb 三元组、不看 alpha。若把带 alpha 的前景直接喂进去,得到的是 // 「把这个半透明颜色当成不透明色」的对比度,即 alpha 越低算出的对比度越**高**: // color: rgba(0,0,0,.05) 在白底上 → 直接算 21.00:1(完美),真实 1.12:1(不可见) // color: transparent → 解析成 rgba(0,0,0,0) → 直接算 21.00:1,真实 1.00:1 // 后者正是「标题消失」的常见写法之一,会让本门禁对同类回归零判别力 // (本轮的立论点就是「它是唯一覆盖标题是否可见的门禁」)。 // 实测佐证:`.process-step-number`(rgba(15,23,42,.04)) 真值 1.08:1,未合成时报 16.63:1。 // // 背景侧 bgOfAncestors() 一直是逐层 over() 合成到不透明底的(那段是对的), // 缺的一直只有前景这一侧——补上后两侧口径才一致。 // 返回 a=1 的实色;透明度为 0 的前景与背景同色,ratio 自然是 1.00,落入同色阻断。 const compositeFg = (fg, bg) => (fg.a >= 0.999 ? {r: fg.r, g: fg.g, b: fg.b, a: 1} : over(fg, bg)); const bgOfAncestors = (el) => { const layers = []; let n = el; while (n && n.nodeType === 1) { const c = parse(getComputedStyle(n).backgroundColor); if (c) { if (c.a >= 0.999) { layers.push(c); break; } layers.push(c); } n = n.parentElement; } let base = {r: 255, g: 255, b: 255, a: 1}; for (let i = layers.length - 1; i >= 0; i--) base = over(layers[i], base); return base; }; // SVG 文字的真实底:同一容器内、绘制顺序在它之前且有不透明 fill 的形状 const shapeUnder = (el) => { const parent = el.parentElement; if (!parent) return null; let hit = null; for (const k of parent.children) { if (k === el) break; const t = k.tagName.toLowerCase(); if (t === 'text' || t === 'tspan') continue; const f = parse(getComputedStyle(k).fill); if (f && f.a >= 0.9) hit = f; } return hit; }; const effectiveBg = (el) => { const canvas = bgOfAncestors(el); if (isSvgText(el)) { const shape = shapeUnder(el); if (shape) return over({r: shape.r, g: shape.g, b: shape.b, a: shape.a}, canvas); } return canvas; }; const pathOf = (el) => { const parts = []; let n = el; while (n && n.nodeType === 1 && parts.length < 4) { let s = n.id ? '#' + n.id : n.tagName.toLowerCase(); if (!n.id && n.className && typeof n.className === 'string') { const c = n.className.trim().split(/\\s+/).filter(Boolean).slice(0, 2); if (c.length) s += '.' + c.join('.'); } parts.unshift(s); n = n.parentElement; } return parts.join(' > '); }; const hasDirectText = (el) => [...el.childNodes].some( (n) => n.nodeType === 3 && n.textContent.trim().length > 0 ); const visible = (el) => { const st = getComputedStyle(el); if (st.visibility === 'hidden' || st.display === 'none' || parseFloat(st.opacity) < 0.05) return false; const r = el.getBoundingClientRect(); return r.width >= 2 && r.height >= 2; }; const out = []; const seen = new Set(); for (const el of document.querySelectorAll('body *')) { if (!hasDirectText(el) || !visible(el)) continue; const st = getComputedStyle(el); const fg = fgOf(el, st); if (!fg) continue; const bg = effectiveBg(el); const fsz = parseFloat(st.fontSize); const weight = parseInt(st.fontWeight, 10) || 400; const need = (fsz >= 24 || (fsz >= 18.66 && weight >= 700)) ? 3.0 : 4.5; // 必须先按背景合成再算 ratio:否则半透明/透明前景会被算成「高对比」(见 compositeFg 注释) const fgSolid = compositeFg(fg, bg); const r = ratio(fgSolid, bg); if (r >= need) continue; const key = pathOf(el) + '|' + (el.textContent || '').trim().slice(0, 24); if (seen.has(key)) continue; seen.add(key); out.push({ path: pathOf(el), ratio: +r.toFixed(2), need, fg: `rgb(${Math.round(fgSolid.r)}, ${Math.round(fgSolid.g)}, ${Math.round(fgSolid.b)})`, bg: `rgb(${Math.round(bg.r)}, ${Math.round(bg.g)}, ${Math.round(bg.b)})`, font: `${fsz}px/${weight}`, text: (el.textContent || '').trim().replace(/\\s+/g, ' ').slice(0, 40), hidden: !!el.closest('[aria-hidden="true"]'), // 显式装饰标记:**只有作者主动标注**才算,绝不从 aria-hidden 推断。 // 为什么不做自动推断:装饰子图里同样可能藏真缺陷(本脚本刻意连 aria-hidden 子树一起扫), // 用 aria-hidden 推断豁免等于给「整块藏起来」开了后门,与本门禁的立论点冲突。 decorative: !!el.closest('[data-audit-decorative]'), }); } out.sort((a, b) => a.ratio - b.ratio); // 同色检测在全量 out 上做,不能被 worst 的 80 条截断吃掉 const sameColor = out.filter((o) => o.fg === o.bg); // 装饰豁免的成立条件(**两条缺一不可**): // ① 作者以 data-audit-decorative **主动标注**(不从 aria-hidden 自动推断,那等于给"整块藏起来"开后门); // ② 该文字本身在 aria-hidden 子树里 —— 即它对辅助技术不存在、没有信息量。 // 只标属性而不 aria-hidden 的正文**不成立豁免**:否则一段真的低对比度正文 // 只要被打上装饰标记就能逃逸,豁免就变成绕过通道了(已用注入探针验证过这个边界)。 // 另外同色**永远**阻断、不受豁免影响:透明标题是最典型的"标题消失"形态, // 让它可以靠标属性混过去,本门禁就等于没有(同样有注入探针钉住)。 const isDeco = (o) => o.decorative && o.hidden && o.fg !== o.bg; const deco = out.filter(isDeco); const real = out.filter((o) => !isDeco(o)); return { worst: real.slice(0, 80), total: real.length, belowFail: real.filter((o) => o.ratio < failMin).length, belowWarn: real.filter((o) => o.ratio < warnMin).length, minRatio: real.length ? real[0].ratio : null, sameColor: sameColor.length, sameColorKeys: sameColor.map((o) => o.path + '|' + o.text), blocked: real.filter((o) => o.ratio < failMin || o.fg === o.bg).length, warned: real.filter((o) => o.ratio >= failMin && o.ratio < warnMin && o.fg !== o.bg).length, // 装饰豁免项照常回报(逐条打印成 NOTE,不静默吞掉),但不计入阻断/警告 decorative: deco.length, decorativeItems: deco.map((o) => ({path: o.path, ratio: o.ratio, text: o.text})), }; } """ def structural_checks(page, name): """P1/P2 结构项:溢出、alt、可访问名、h1、焦点指示。""" issues = [] scroll_w = page.evaluate("() => document.documentElement.scrollWidth") client_w = page.evaluate("() => window.innerWidth") if scroll_w > client_w: issues.append(f"P1 [{name}] horizontal overflow: {scroll_w} > {client_w}") for img in page.locator("img").all(): if img.get_attribute("alt") is None: issues.append(f"P1 [{name}] img missing alt: src={img.get_attribute('src')}") bad = page.evaluate( """() => { const els = Array.from(document.querySelectorAll( 'a, button, input, textarea, select, [role="tab"], summary')); return els.filter(el => { const name = el.getAttribute('aria-label') || el.getAttribute('title') || el.textContent.trim() || el.getAttribute('placeholder') || ''; return !name; }).map(el => el.outerHTML.slice(0, 120)); }""" ) for b in bad[:5]: issues.append(f"P1 [{name}] interactive element without accessible name: {b}") h1s = page.locator("h1").count() if h1s != 1: issues.append(f"P1 [{name}] heading hierarchy: {h1s} h1") for sel in (".nav-links a", "#navToggle"): loc = page.locator(sel).first try: if not loc.is_visible(): continue loc.focus() if loc.evaluate("el => getComputedStyle(el).outlineWidth") == "0px": issues.append(f"P2 [{name}] focus indicator missing on {sel}") except Exception: pass return issues, (scroll_w, client_w) def audit_page(browser, base_url, width, height, name, args, report): page = browser.new_page(viewport={"width": width, "height": height}) page.goto(base_url, wait_until="networkidle") page.wait_for_timeout(600) issues, dims = structural_checks(page, name) if args.shots: out_dir = Path(args.shots) out_dir.mkdir(parents=True, exist_ok=True) shot = str(out_dir / f"audit-{name}-{width}.png") page.screenshot(path=shot, full_page=True) else: shot = None reveal = page.evaluate(REVEAL_ALL_JS) page.wait_for_timeout(200) scan = page.evaluate(CONTRAST_SCAN_JS, {"failMin": args.fail, "warnMin": args.warn}) same_ids = set(scan["sameColorKeys"]) # 阻断级 = 对比度 < --fail ∪ 同色(同色无条件阻断:--fail 调到 ≤ 1.0 时 1.00:1 不得放行) blocking = [ o for o in scan["worst"] if o["ratio"] < args.fail or (o["path"] + "|" + o["text"]) in same_ids ] band = [ o for o in scan["worst"] if args.fail <= o["ratio"] < args.warn and (o["path"] + "|" + o["text"]) not in same_ids ] for o in blocking: suffix = " [aria-hidden]" if o["hidden"] else "" if (o["path"] + "|" + o["text"]) in same_ids: issues.append( f"P1 [{name}] 同色前景/背景 {o['fg']} on {o['bg']}(对比度 {o['ratio']})" f"@{o['font']} — {o['path']} «{o['text']}»{suffix}" ) else: issues.append( f"P1 [{name}] contrast {o['ratio']} < {args.fail} (需 {o['need']}) " f"{o['fg']} on {o['bg']} @{o['font']} — {o['path']} «{o['text']}»{suffix}" ) for o in band[: args.list]: issues.append( f"P2 [{name}] contrast {o['ratio']} < {args.warn} (需 {o['need']}) " f"{o['fg']} on {o['bg']} @{o['font']} — {o['path']} «{o['text']}»" + (" [aria-hidden]" if o["hidden"] else "") ) if len(band) > args.list: issues.append(f"P2 [{name}] …另有 {len(band) - args.list} 条对比度落在 [{args.fail},{args.warn})") # 装饰豁免项:逐条打印为 NOTE(不静默),但不进阻断/警告计数。 # 「不静默」是刻意的——豁免必须是可审计的,不能因为标了个属性就从报告里消失。 for o in scan["decorativeItems"]: issues.append( f"NOTE [{name}] 装饰豁免 contrast {o['ratio']} — {o['path']} «{o['text']}»" "(作者以 data-audit-decorative 标注为刻意淡化,不计入阻断/警告)" ) page_errors = [] report[name] = { "viewport": [width, height], "screenshot": shot, "scrollWidth": dims[0], "clientWidth": dims[1], "revealedPanels": reveal["panels"], "contrast": { "minRatio": scan["minRatio"], "offenders": scan["total"], "belowFail": scan["belowFail"], "belowWarn": scan["belowWarn"], "sameColor": scan["sameColor"], "decorative": scan["decorative"], }, "blocked": scan["blocked"], "warned": scan["warned"], "issues": issues, } page.close() def main(): ap = argparse.ArgumentParser(description="Landing page 结构与对比度审计门禁") ap.add_argument("--url", default="http://127.0.0.1:8088/", help="已启动的 landing 静态服务地址") ap.add_argument("--shots", default="", help="传入目录则输出整页截图") ap.add_argument("--fail", type=float, default=FAIL_MIN_DEFAULT, help="阻断级对比度下限(默认 3.0);同色前景/背景不受此参数影响,始终阻断") ap.add_argument("--warn", type=float, default=WARN_MIN_DEFAULT, help="警告级对比度上限(默认 4.5);落在 [--fail, --warn) 只打印不阻断") ap.add_argument("--list", type=int, default=20, help="每个视口最多打印多少条 P2(默认 20)") ap.add_argument("--json", action="store_true", help="额外打印 JSON 报告") args = ap.parse_args() report = {} with sync_playwright() as p: browser = p.chromium.launch(headless=True) for width, height, name in ( (1440, 900, "desktop"), (768, 1024, "tablet"), (390, 844, "mobile"), ): audit_page(browser, args.url, width, height, name, args, report) browser.close() p1 = [i for v in report.values() for i in v["issues"] if i.startswith("P1")] p2 = [i for v in report.values() for i in v["issues"] if i.startswith("P2")] notes = [i for v in report.values() for i in v["issues"] if i.startswith("NOTE")] same_total = sum(v["contrast"]["sameColor"] for v in report.values()) print("== Landing 全量可见文字对比度扫描(已解除动效隐藏态)==") for name, v in report.items(): c = v["contrast"] print( f" {name:>8} 展开面板 {v['revealedPanels']} 最低 {c['minRatio']} " f"低于判据 {c['offenders']} 条 其中同色 {c['sameColor']} " f"阻断级(P1) {v['blocked']} 警告级(P2) {v['warned']}" ) if p1 or p2: print("\n== 问题清单 ==") for i in p1: print(" " + i[:220]) for i in p2: print(" " + i[:220]) else: print("\n== 无问题 ==") # 装饰豁免始终单独列出(即使全绿):豁免必须可审计,不能因为"没红"就从报告里消失 if notes: print("\n== 装饰豁免(作者以 data-audit-decorative 主动标注,不计入阻断/警告)==") for i in notes: print(" " + i[:220]) if args.json: print(json.dumps(report, indent=2, ensure_ascii=False)) print("\n" + "=" * 46) blocked_total = sum(v["blocked"] for v in report.values()) warned_total = sum(v["warned"] for v in report.values()) if p1: print( f"AUDIT_RESULT: FAIL (阻断 P1={len(p1)} [同色 {same_total}] " f"警告 P2={len(p2)} 全量: 阻断 {blocked_total} / 警告 {warned_total})" ) sys.exit(1) print( f"AUDIT_RESULT: PASS (阻断 P1=0 警告 P2={len(p2)} " f"全量: 阻断 0 / 警告 {warned_total})" ) sys.exit(0) if __name__ == "__main__": main()