diff --git a/.github/workflows/snippets.yml b/.github/workflows/snippets.yml index 3d64618..30c1e78 100644 --- a/.github/workflows/snippets.yml +++ b/.github/workflows/snippets.yml @@ -326,7 +326,7 @@ jobs: - name: Install Playwright browser run: pnpm exec playwright install --with-deps chromium - - name: Run playground smoke tests + - name: Run playground smoke and accessibility tests run: pnpm run test:playground check-stellar-reference: diff --git a/package.json b/package.json index 4c54331..2dc3f1b 100644 --- a/package.json +++ b/package.json @@ -35,6 +35,7 @@ "@wraith-protocol/sdk": "1.4.5" }, "devDependencies": { + "@axe-core/playwright": "4.14.0", "@playwright/test": "^1.49.1", "@types/js-yaml": "4.0.9", "@types/node": "^22.10.2", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e132f48..7c323f4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -24,6 +24,9 @@ importers: specifier: 1.4.5 version: 1.4.5(@solana/web3.js@1.99.0(bufferutil@4.1.0)(typescript@5.9.3)(utf-8-validate@6.0.6))(@stellar/stellar-sdk@13.3.0(debug@4.4.3))(bufferutil@4.1.0)(typescript@5.9.3)(utf-8-validate@6.0.6) devDependencies: + '@axe-core/playwright': + specifier: 4.14.0 + version: 4.14.0(playwright-core@1.62.1) '@playwright/test': specifier: ^1.49.1 version: 1.62.1 @@ -48,6 +51,12 @@ packages: '@adraffy/ens-normalize@1.11.1': resolution: {integrity: sha512-nhCBV3quEgesuf7c7KYfperqSS14T8bYuvJ8PcLJp6znkZpFc0AuW4qBtr8eKVyPPe/8RSr7sglCWPU5eaxwKQ==} + '@axe-core/playwright@4.14.0': + resolution: {integrity: sha512-SGUhG5PIHd2eMdpgBF2PyQLOhX+qyDR2PT4cmoS4Qk2ak+jX/rrSvst9l0PGv5WTHolKpUMvVmoHpr4cZgf1RQ==} + engines: {node: '>=22.12.0'} + peerDependencies: + playwright-core: '>= 1.0.0' + '@babel/runtime@7.29.7': resolution: {integrity: sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==} engines: {node: '>=6.9.0'} @@ -349,6 +358,10 @@ packages: resolution: {integrity: sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==} engines: {node: '>= 0.4'} + axe-core@4.14.1: + resolution: {integrity: sha512-FHfa+lmNjQZfJz1q8wKqIDwC6DExcHt/pkjNQb09a3NPjCKg2rhu5qb2S4r76ASyFNNtuFooJpZe37OgudVGtQ==} + engines: {node: '>=4'} + axios@1.20.0: resolution: {integrity: sha512-r8aOh8j9cGKpgQAqpzrUHnSIc6a59Y3Xf/cv8sy1DrHCkZHzQGEuoq1tARk6qSyDdtQGSDgpb9kFlruzPvrgwg==} @@ -789,6 +802,11 @@ snapshots: '@adraffy/ens-normalize@1.11.1': {} + '@axe-core/playwright@4.14.0(playwright-core@1.62.1)': + dependencies: + axe-core: 4.14.1 + playwright-core: 1.62.1 + '@babel/runtime@7.29.7': {} '@esbuild/aix-ppc64@0.28.1': @@ -1037,6 +1055,8 @@ snapshots: dependencies: possible-typed-array-names: 1.1.0 + axe-core@4.14.1: {} + axios@1.20.0(debug@4.4.3): dependencies: follow-redirects: 1.16.1(debug@4.4.3) diff --git a/scripts/playground/index.html b/scripts/playground/index.html index 1b35b43..fcb26bd 100644 --- a/scripts/playground/index.html +++ b/scripts/playground/index.html @@ -16,13 +16,14 @@ --surface: #181c27; --border: #2a2f3d; --accent: #7c6af7; + --accent-solid: #6a56e8; --accent-lo: #7c6af720; --green: #34d399; --green-lo: #34d39918; --red: #f87171; --red-lo: #f8717118; --text: #e2e8f0; - --muted: #64748b; + --muted: #94a3b8; --mono: 'Fira Mono', 'Cascadia Code', 'Consolas', monospace; } @@ -36,6 +37,32 @@ min-height: 100vh; } + /* ── Accessibility utilities ─────────────────────────── */ + .sr-only { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0 0 0 0); + white-space: nowrap; + border: 0; + } + :focus-visible { + outline: 2px solid #c4bcff; + outline-offset: 2px; + } + .panel h2:focus { outline: none; } + .field-error { + margin-top: 5px; + font-size: 11px; + font-weight: 600; + color: var(--red); + } + [aria-invalid="true"] { border-color: var(--red); } + button[aria-disabled="true"] { opacity: .4; cursor: not-allowed; } + h1 { font-size: 17px; font-weight: 600; @@ -92,7 +119,7 @@ font-weight: 700; flex-shrink: 0; } - .stepper .step.active .step-num { background: var(--accent); color: #fff; } + .stepper .step.active .step-num { background: var(--accent-solid); color: #fff; } /* ── Panels ──────────────────────────────────────────── */ .panel h2 { @@ -147,7 +174,7 @@ button { padding: 9px 14px; - background: var(--accent); + background: var(--accent-solid); border: none; border-radius: 6px; color: #fff; @@ -168,6 +195,22 @@ button.ghost:hover { border-color: var(--accent); } button.small { padding: 5px 10px; font-size: 11px; margin-top: 8px; } + .link-btn { + display: inline-flex; + align-items: center; + min-height: 24px; + flex: 0 0 auto; + padding: 0; + background: none; + border: none; + color: var(--accent); + font: inherit; + font-weight: 600; + text-decoration: none; + cursor: pointer; + } + .link-btn:hover { text-decoration: underline; opacity: 1; } + .hint { margin-top: 8px; font-size: 11px; @@ -178,7 +221,9 @@ text-decoration: none; cursor: pointer; } + .hint a { text-decoration: underline; } .hint a:hover { text-decoration: underline; } + .hint .link-btn { color: var(--accent); } .hint code { font-family: var(--mono); font-size: 10px; @@ -372,7 +417,28 @@ color: var(--muted); font-size: 11px; } - .privacy-note a { color: var(--accent); } + /* The privacy note sits inside a match card (tinted green), where the + default accent does not reach 4.5:1 for body text. */ + .privacy-note a { color: #b9b0ff; text-decoration: underline; } + + /* ── Motion + reflow preferences ─────────────────────── */ + @media (prefers-reduced-motion: reduce) { + *, *::before, *::after { + animation-duration: 0.01ms !important; + animation-iteration-count: 1 !important; + transition-duration: 0.01ms !important; + } + .dot-scanning { animation: none; } + } + + @media (max-width: 480px) { + body { padding: 16px 12px 24px; } + .row { flex-wrap: wrap; } + .btn-row { flex-wrap: wrap; } + /* Two rows of two steps keep the labels on one line at 320–480px. */ + .stepper { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); } + .stepper .step { min-width: 0; } + } @@ -380,27 +446,28 @@

Wraith Stealth Playground

Run the full stealth payment flow client-side — no wallet, no network calls, nothing leaves your browser.

- +
+
-
-

1 · Derive stealth keys

+
+

1 · Derive stealth keys

A wallet signs the canonical Wraith message; the 64-byte signature is split into two domain-separated seeds, and each seed expands into a key pair. The public halves form @@ -408,22 +475,23 @@

1 · Derive stealth keys

- + + placeholder="64-byte ed25519 signature as hex" aria-describedby="sigError" /> +
- - + +
-
-

Copy permalink — share the current step + inputs.

+
+

— share the current step + inputs.

-
diff --git a/scripts/playground/playground.js b/scripts/playground/playground.js index 92e55d1..a7316ee 100644 --- a/scripts/playground/playground.js +++ b/scripts/playground/playground.js @@ -32,31 +32,84 @@ const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', }[c])); +// ── Accessibility helpers ─────────────────────────────────── +// The live region carries short status messages that are not already +// announced by a role="status"/"alert" result block — copy confirmations +// and step changes, for example. Clearing first makes repeated identical +// messages announce again. +function announce(message) { + const region = $('liveRegion'); + if (!region) return; + region.textContent = ''; + requestAnimationFrame(() => { region.textContent = message; }); +} + +function setFieldError(input, errorEl, message) { + errorEl.textContent = message; + errorEl.hidden = false; + input.setAttribute('aria-invalid', 'true'); +} + +function clearFieldError(input, errorEl) { + errorEl.textContent = ''; + errorEl.hidden = true; + input.removeAttribute('aria-invalid'); +} + +function clearAllFieldErrors() { + for (const [inputId, errorId] of [ + ['sigInput', 'sigError'], + ['sendMeta', 'sendMetaError'], + ['sendAmount', 'sendAmountError'], + ['scanMeta', 'scanMetaError'], + ['scanVk', 'scanVkError'], + ['scanScalar', 'scanScalarError'], + ]) { + clearFieldError($(inputId), $(errorId)); + } +} + // ── Stepper ───────────────────────────────────────────────── function activateStep(step) { if (!STEPS.includes(step)) step = 'derive'; for (const s of STEPS) { $('panel-' + s).hidden = s !== step; - $('stepper-' + s).classList.toggle('active', s === step); + const tab = $('stepper-' + s); + const active = s === step; + tab.classList.toggle('active', active); + if (active) tab.setAttribute('aria-current', 'step'); + else tab.removeAttribute('aria-current'); } if (step === 'withdraw') renderWithdraw(); if (step === 'scan') renderFixtureTable(); syncPermalink(); } +// Move focus to the visible panel heading after a stepper change so keyboard +// and screen-reader users land in the newly revealed step instead of at the +// top of the document. The heading is tabindex="-1" for this reason only. +function focusStepHeading(step) { + const heading = $('panel-' + step).querySelector('h2'); + if (heading) heading.focus(); +} + // ── Status / result helpers ───────────────────────────────── function statusBar(kind, html) { - return `
${html}
`; + // Errors interrupt (role="alert"); progress and success announce politely. + const role = kind === 'err' ? 'alert' : 'status'; + return `
` + + `${html}
`; } function kvRow(k, v, mono = true) { return `
${k}${v}
`; } -function copyText(text, btn) { +function copyText(text, btn, message = 'Copied to clipboard.') { const done = () => { const old = btn.textContent; btn.textContent = 'Copied ✓'; + announce(message); setTimeout(() => { btn.textContent = old; }, 1200); }; if (navigator.clipboard && window.isSecureContext) { @@ -103,10 +156,16 @@ async function loadFixtures() { // ── Derive step ───────────────────────────────────────────── async function runDerive() { - const sigRaw = $('sigInput').value.trim(); + const sigInput = $('sigInput'); + const sigError = $('sigError'); + const sigRaw = sigInput.value.trim(); const out = $('deriveResults'); + clearFieldError(sigInput, sigError); if (!/^[0-9a-fA-F]{128}$/.test(sigRaw)) { - out.innerHTML = statusBar('err', 'Signature must be 128 hex chars (a 64-byte ed25519 signature).'); + out.innerHTML = ''; + setFieldError(sigInput, sigError, + 'Signature must be 128 hex characters (a 64-byte ed25519 signature).'); + sigInput.focus(); return; } try { @@ -133,30 +192,51 @@ async function runDerive() {

The seeds are SHA-256("wraith:spending:" ‖ signature) and SHA-256("wraith:viewing:" ‖ signature) — the same split the SDK performs.

`; - $('copyMetaBtn').addEventListener('click', () => copyText(metaAddress, $('copyMetaBtn'))); + $('copyMetaBtn').addEventListener('click', () => + copyText(metaAddress, $('copyMetaBtn'), 'Stealth meta-address copied to clipboard.')); } catch (err) { out.innerHTML = statusBar('err', `Derivation failed: ${esc(err.message)}`); + out.focus(); } } // ── Send step ─────────────────────────────────────────────── async function constructAnnouncement() { - const metaRaw = $('sendMeta').value.trim(); - const amount = $('sendAmount').value.trim(); + const metaInput = $('sendMeta'); + const metaError = $('sendMetaError'); + const amountInput = $('sendAmount'); + const amountError = $('sendAmountError'); + const metaRaw = metaInput.value.trim(); + const amount = amountInput.value.trim(); const asset = $('sendAsset').value; const out = $('sendResults'); + clearFieldError(metaInput, metaError); + clearFieldError(amountInput, amountError); if (!metaRaw.startsWith('st:xlm:')) { - out.innerHTML = statusBar('err', 'Recipient meta-address must start with st:xlm:.'); + out.innerHTML = ''; + setFieldError(metaInput, metaError, 'Recipient meta-address must start with st:xlm:.'); + metaInput.focus(); return; } - if (!amount || Number.isNaN(Number(amount)) || Number(amount) <= 0) { - out.innerHTML = statusBar('err', 'Amount must be a positive number.'); + if (!amount || !Number.isFinite(Number(amount)) || Number(amount) <= 0) { + out.innerHTML = ''; + setFieldError(amountInput, amountError, 'Amount must be a positive number.'); + amountInput.focus(); + return; + } + + let spendingPubKey, viewingPubKey; + try { + ({ spendingPubKey, viewingPubKey } = decodeStealthMetaAddress(metaRaw)); + } catch (err) { + out.innerHTML = ''; + setFieldError(metaInput, metaError, `Recipient meta-address is invalid: ${err.message}`); + metaInput.focus(); return; } try { - const { spendingPubKey, viewingPubKey } = decodeStealthMetaAddress(metaRaw); // Deterministic one-time ephemeral keypair per click, so the demo is // reproducible — the real protocol uses a random seed. @@ -193,12 +273,13 @@ async function constructAnnouncement() {
Horizon event emitted by this payment -
${esc(JSON.stringify(event, null, 2))}
+
${esc(JSON.stringify(event, null, 2))}

The stealth-sender contract transfers the asset and the stealth-announcer contract emits this event in the same transaction.

`; } catch (err) { out.innerHTML = statusBar('err', `Send failed: ${esc(err.message)}`); + out.focus(); } } @@ -209,38 +290,55 @@ function allAnnouncements() { } async function runScan() { - const metaRaw = $('scanMeta').value.trim(); - const vkRaw = $('scanVk').value.trim(); - const ssRaw = $('scanScalar').value.trim(); + const metaInput = $('scanMeta'); + const vkInput = $('scanVk'); + const scalarInput = $('scanScalar'); + const metaRaw = metaInput.value.trim(); + const vkRaw = vkInput.value.trim(); + const ssRaw = scalarInput.value.trim(); const out = $('scanResults'); - const errors = []; + const invalid = []; + clearFieldError(metaInput, $('scanMetaError')); + clearFieldError(vkInput, $('scanVkError')); + clearFieldError(scalarInput, $('scanScalarError')); let spendingPubKey = null; if (metaRaw.startsWith('st:xlm:')) { try { spendingPubKey = decodeStealthMetaAddress(metaRaw).spendingPubKey; } - catch (e) { errors.push(`meta-address: ${e.message}`); } - } else if (metaRaw) { - errors.push('meta-address must start with st:xlm:'); + catch (e) { + setFieldError(metaInput, $('scanMetaError'), `Meta-address is invalid: ${e.message}`); + invalid.push(metaInput); + } + } else { + setFieldError(metaInput, $('scanMetaError'), 'Meta-address must start with st:xlm:.'); + invalid.push(metaInput); } let viewingKey = null; if (/^[0-9a-fA-F]{64}$/.test(vkRaw)) { viewingKey = hexToBytes(vkRaw); } else { - errors.push('viewing key must be 64 hex chars'); + setFieldError(vkInput, $('scanVkError'), 'Viewing key must be 64 hex characters.'); + invalid.push(vkInput); } let spendingScalar = null; - try { spendingScalar = BigInt(ssRaw); } catch (_) { errors.push('spending scalar must be a decimal integer'); } + try { spendingScalar = BigInt(ssRaw); } catch (_) { + setFieldError(scalarInput, $('scanScalarError'), 'Spending scalar must be a decimal integer.'); + invalid.push(scalarInput); + } - if (errors.length > 0) { - out.innerHTML = statusBar('err', `Fix: ${esc(errors.join('; '))}.`); + if (invalid.length > 0) { + out.innerHTML = ''; + invalid[0].focus(); return; } const announcements = allAnnouncements(); const btn = $('scanBtn'); - btn.disabled = true; + if (btn.getAttribute('aria-disabled') === 'true') return; + btn.setAttribute('aria-disabled', 'true'); + out.setAttribute('aria-busy', 'true'); out.innerHTML = statusBar('scanning', `Scanning ${announcements.length} announcements…`); const t0 = performance.now(); @@ -272,8 +370,10 @@ async function runScan() { renderFixtureTable(); } catch (err) { out.innerHTML = statusBar('err', `Scan failed: ${esc(err.message)}`); + out.focus(); } finally { - btn.disabled = false; + btn.removeAttribute('aria-disabled'); + out.removeAttribute('aria-busy'); } } @@ -282,11 +382,17 @@ function renderFixtureTable() { const announcements = allAnnouncements(); const yours = new Set(state.scanMatches.map((m) => m.ephemeralPubKey)); table.innerHTML = ''; + + const caption = document.createElement('caption'); + caption.className = 'sr-only'; + caption.textContent = 'Announcement batch: fixture events plus anything constructed in the Send step.'; + table.appendChild(caption); if (announcements.length === 0) return; const thead = document.createElement('thead'); thead.innerHTML = ` - #Stealth AddressEphemeral Pub KeyView TagOwner + #Stealth AddressEphemeral Pub Key + View TagOwner `; table.appendChild(thead); @@ -335,7 +441,7 @@ async function renderWithdraw() {
Stealth balance
${kvRow('Stealth address', `${m.stealthAddress}`)} ${kvRow('Private scalar (signs withdrawals)', `${m.stealthPrivateScalar.toString()}`)} - +
`); } @@ -369,7 +475,7 @@ function renderWithdrawal(btn, dest) { out.innerHTML = `
Simulated withdrawal transaction -
${esc(JSON.stringify(tx, null, 2))}
+
${esc(JSON.stringify(tx, null, 2))}

Privacy: space real withdrawals at least 1 hour apart and avoid uniform round amounts — see Privacy Best Practices.

`; @@ -379,6 +485,7 @@ function renderWithdrawal(btn, dest) { function resetStep(step) { if (!state.fixtures) return; const r = state.fixtures.recipient; + clearAllFieldErrors(); if (step === 'derive') { $('sigInput').value = r.signature; $('deriveResults').innerHTML = ''; @@ -441,11 +548,14 @@ async function boot() { try { await loadFixtures(); } catch (err) { - $('bootError').hidden = false; - $('bootError').innerHTML = statusBar('err', + // #bootError already has role="alert"; fill it before revealing it so the + // message is announced once, without a nested live region. + $('bootError').innerHTML = + `
` + `Could not load fixtures.json (${esc(err.message)}). ` + `Serve the playground over HTTP — opening it via file:// or embedding without ` + - `allow-same-origin blocks the fixture request.`); + `allow-same-origin blocks the fixture request.
`; + $('bootError').hidden = false; return; } @@ -454,18 +564,26 @@ async function boot() { $('stepper-' + s).addEventListener('click', () => { _currentStep = s; activateStep(s); + focusStepHeading(s); + }); + $('reset-' + s).addEventListener('click', () => { + resetStep(s); + announce(`${STEP_LABELS[s]} step reset.`); }); - $('reset-' + s).addEventListener('click', () => resetStep(s)); - $('permalink-' + s).addEventListener('click', (e) => { - e.preventDefault(); - copyText(new URL($('permalink-' + s).dataset.url, location.href).href, $('permalink-' + s)); + $('permalink-' + s).addEventListener('click', () => { + copyText(new URL($('permalink-' + s).dataset.url, location.href).href, + $('permalink-' + s), 'Permalink copied to clipboard.'); }); } $('deriveBtn').addEventListener('click', runDerive); $('constructBtn').addEventListener('click', constructAnnouncement); $('scanBtn').addEventListener('click', runScan); - $('loadFixture').addEventListener('click', () => resetStep('scan')); + $('loadFixture').addEventListener('click', () => { + resetStep('scan'); + announce('Demo keys and fixture data loaded.'); + $('scanMeta').focus(); + }); // Read the step (and optional prefilled inputs) from the URL. const params = new URLSearchParams(location.search); diff --git a/scripts/playground/tests/a11y.spec.ts b/scripts/playground/tests/a11y.spec.ts new file mode 100644 index 0000000..ed838d6 --- /dev/null +++ b/scripts/playground/tests/a11y.spec.ts @@ -0,0 +1,283 @@ +import AxeBuilder from "@axe-core/playwright"; +import { expect, test, type Page } from "@playwright/test"; + +// Accessibility and keyboard coverage for the Wraith Stealth Playground. +// +// The playground is embedded in docs pages, so it has to work for keyboard and +// assistive-technology users at desktop, 200% zoom, and mobile widths without a +// pointer. These tests complement playground.spec.ts (which covers the smoke +// flow and the zero-external-request gate) and enforce the issue #220 +// acceptance criteria. +// +// Rule exceptions: none. The palette and markup are fixed rather than excluding +// axe rules, so any serious/critical violation is a failure. + +const WCAG_TAGS = ["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22a", "wcag22aa"]; + +async function analyze(page: Page, context: string) { + const results = await new AxeBuilder({ page }).withTags(WCAG_TAGS).analyze(); + const blocking = results.violations.filter( + (v) => v.impact === "serious" || v.impact === "critical", + ); + const summary = blocking + .map((v) => + `${v.id} (${v.impact}) ${v.help}\n` + + v.nodes.map((n) => ` ${n.target.join(" ")}: ${n.failureSummary}`).join("\n"), + ) + .join("\n\n"); + expect(blocking, `${context}\n${summary}`).toEqual([]); +} + +// Press Tab until the given element owns focus. This is deliberately keyboard +// only: no locator.click(), no programmatic focus(), no pointer events. +async function tabTo(page: Page, selector: string, maxTabs = 80) { + const target = page.locator(selector).first(); + for (let i = 0; i < maxTabs; i++) { + await page.keyboard.press("Tab"); + if (await target.evaluate((el) => el === document.activeElement)) return; + } + throw new Error(`Tab did not reach ${selector} within ${maxTabs} presses`); +} + +async function assertNoHorizontalOverflow(page: Page, context: string) { + const metrics = await page.evaluate(() => ({ + scrollWidth: document.documentElement.scrollWidth, + clientWidth: document.documentElement.clientWidth, + })); + expect( + metrics.scrollWidth, + `${context} must reflow without horizontal scrolling (${metrics.scrollWidth}px > ${metrics.clientWidth}px)`, + ).toBeLessThanOrEqual(metrics.clientWidth + 1); +} + +// The whole guided flow, activated only with Tab and Enter/Space aside from +// typing the amount. +async function completeFlowWithKeyboard(page: Page) { + await page.goto("/index.html"); + + await tabTo(page, "#deriveBtn"); + await page.keyboard.press("Enter"); + await expect(page.locator("#deriveResults .card-accent")).toContainText("st:xlm:"); + + await tabTo(page, "#stepper-send"); + await page.keyboard.press("Enter"); + // Activating a step moves focus to its heading. + await expect(page.locator("#panel-send-title")).toBeFocused(); + await tabTo(page, "#sendAmount"); + await page.keyboard.type("10"); + await tabTo(page, "#constructBtn"); + await page.keyboard.press("Enter"); + await expect(page.locator("#sendResults")).toContainText("added to the scan batch"); + + await tabTo(page, "#stepper-scan"); + await page.keyboard.press("Enter"); + await tabTo(page, "#loadFixture"); + await page.keyboard.press("Enter"); + await tabTo(page, "#scanBtn"); + await page.keyboard.press("Enter"); + await expect(page.locator("#scanResults [role='status']")).toContainText("matches found"); + + await tabTo(page, "#stepper-withdraw"); + await page.keyboard.press("Enter"); + await expect(page.locator("#withdrawResults")).toContainText("withdrawable stealth balance"); + await tabTo(page, ".withdraw-btn"); + await page.keyboard.press("Enter"); + await expect(page.locator("#withdrawResults .code-block").first()).toContainText( + "stealth private scalar", + ); +} + +test("no serious or critical axe violations across the guided flow", async ({ page }) => { + await page.goto("/index.html?step=derive"); + await analyze(page, "derive step"); + + await page.locator("#deriveBtn").click(); + await expect(page.locator("#deriveResults .card-accent")).toBeVisible(); + await analyze(page, "derive results"); + + await page.locator("#stepper-send").click(); + await page.locator("#sendAmount").fill("10"); + await page.locator("#constructBtn").click(); + await expect(page.locator("#sendResults .card-accent")).toBeVisible(); + // Expand the event JSON so the scrollable code region is exposed. + await page.locator("#sendResults details summary").click(); + await analyze(page, "send results"); + + await page.locator("#stepper-scan").click(); + await page.locator("#loadFixture").click(); + await page.locator("#scanBtn").click(); + await expect(page.locator("#scanResults .match-card")).toHaveCount(3); + // Expand the announcement table so its caption and headers are scanned. + await page.locator("#panel-scan details.fixture-section summary").click(); + await analyze(page, "scan results"); + + await page.locator("#stepper-withdraw").click(); + await expect(page.locator("#withdrawResults .withdraw-btn")).toHaveCount(3); + await page.locator("#withdrawResults .withdraw-btn").first().click(); + await analyze(page, "withdraw results"); +}); + +test("no serious or critical axe violations at mobile width", async ({ page }) => { + await page.setViewportSize({ width: 360, height: 740 }); + await page.goto("/index.html?step=derive"); + await page.locator("#deriveBtn").click(); + await expect(page.locator("#deriveResults .card-accent")).toBeVisible(); + await analyze(page, "derive results at 360px"); + + await page.locator("#stepper-scan").click(); + await page.locator("#loadFixture").click(); + await page.locator("#scanBtn").click(); + // The fixture batch alone matches twice; the Send step adds the third. + await expect(page.locator("#scanResults .match-card")).toHaveCount(2); + await analyze(page, "scan results at 360px"); +}); + +test("every cryptographic input and select has an accessible name", async ({ page }) => { + await page.goto("/index.html?step=derive"); + await expect(page.getByLabel(/Wallet signature/)).toBeVisible(); + + await page.locator("#stepper-send").click(); + await expect(page.getByLabel(/Recipient meta-address/)).toBeVisible(); + await expect(page.getByLabel("Asset")).toHaveValue("XLM"); + await expect(page.getByLabel("Amount")).toBeVisible(); + + await page.locator("#stepper-scan").click(); + await expect(page.getByLabel(/Stealth meta-address/)).toBeVisible(); + await expect(page.getByLabel(/Viewing key/)).toBeVisible(); + await expect(page.getByLabel(/Spending scalar/)).toBeVisible(); + + await page.locator("#stepper-withdraw").click(); + await expect(page.getByLabel(/Destination wallet/)).toBeVisible(); + + // Errors are associated with the input they describe, not just global text. + await page.locator("#stepper-derive").click(); + await expect(page.locator("#sigInput")).toHaveAttribute("aria-describedby", "sigError"); + await expect(page.locator("#sendMeta")).toHaveAttribute("aria-describedby", "sendMetaError"); + await expect(page.locator("#scanVk")).toHaveAttribute("aria-describedby", "scanVkError"); +}); + +test("tab order follows the visual order of the stepper and derive panel", async ({ page }) => { + await page.goto("/index.html?step=derive"); + await page.locator("#stepper-derive").focus(); + + for (const id of [ + "stepper-send", + "stepper-scan", + "stepper-withdraw", + "sigInput", + "deriveBtn", + "reset-derive", + "permalink-derive", + ]) { + await page.keyboard.press("Tab"); + await expect(page.locator(`#${id}`)).toBeFocused(); + } +}); + +test("stepper exposes the current step and moves focus to its heading", async ({ page }) => { + await page.goto("/index.html?step=derive"); + await expect(page.locator("#stepper-derive")).toHaveAttribute("aria-current", "step"); + await expect(page.locator("#stepper-send")).not.toHaveAttribute("aria-current", "step"); + + await page.locator("#stepper-scan").click(); + await expect(page.locator("#stepper-scan")).toHaveAttribute("aria-current", "step"); + await expect(page.locator("#stepper-derive")).not.toHaveAttribute("aria-current", "step"); + await expect(page.locator("#panel-scan-title")).toBeFocused(); +}); + +test("invalid signature moves focus, announces the error, and keeps the input", async ({ + page, +}) => { + await page.goto("/index.html?step=derive"); + await page.locator("#sigInput").fill("abc123"); + await page.locator("#deriveBtn").click(); + + await expect(page.locator("#sigInput")).toBeFocused(); + await expect(page.locator("#sigInput")).toHaveAttribute("aria-invalid", "true"); + await expect(page.locator("#sigInput")).toHaveValue("abc123"); + await expect(page.locator("#sigError")).toBeVisible(); + await expect(page.getByRole("alert")).toContainText("128 hex characters"); + await expect(page.locator("#deriveResults")).toHaveText(""); +}); + +test("scan errors focus the first invalid field and preserve all input", async ({ page }) => { + await page.goto("/index.html?step=scan"); + await expect(page.locator("#scanVk")).toHaveValue(/^[0-9a-f]{64}$/); + + await page.locator("#scanMeta").fill("not-a-meta-address"); + await page.locator("#scanVk").fill("zz"); + await page.locator("#scanScalar").fill("not-a-number"); + await page.locator("#scanBtn").click(); + + await expect(page.locator("#scanMeta")).toBeFocused(); + await expect(page.locator("#scanMeta")).toHaveAttribute("aria-invalid", "true"); + await expect(page.locator("#scanVk")).toHaveAttribute("aria-invalid", "true"); + await expect(page.locator("#scanScalar")).toHaveAttribute("aria-invalid", "true"); + await expect(page.locator("#scanVk")).toHaveValue("zz"); + await expect(page.locator("#scanScalar")).toHaveValue("not-a-number"); + await expect(page.locator("#scanMetaError")).toContainText( + "Meta-address must start with st:xlm:", + ); + await expect(page.locator("#scanResults")).toHaveText(""); +}); + +test("result statuses and copy actions announce through live regions", async ({ page }) => { + await page.goto("/index.html?step=derive"); + await page.locator("#deriveBtn").click(); + await expect(page.locator("#deriveResults [role='status']")).toContainText("Keys derived"); + + await page.locator("#copyMetaBtn").click(); + await expect(page.locator("#copyMetaBtn")).toContainText("Copied ✓"); + await expect(page.locator("#liveRegion")).toHaveText( + "Stealth meta-address copied to clipboard.", + ); + + await page.locator("#permalink-derive").click(); + await expect(page.locator("#liveRegion")).toHaveText("Permalink copied to clipboard."); + await expect(page.locator("#permalink-derive")).toContainText("Copied ✓"); + + await page.locator("#stepper-scan").click(); + await page.locator("#loadFixture").click(); + await page.locator("#scanBtn").click(); + const scanStatus = page.locator("#scanResults [role='status']"); + await expect(scanStatus).toContainText("matches found"); + await expect(scanStatus).toHaveAttribute("aria-atomic", "true"); +}); + +test("reduced motion disables the scanning pulse", async ({ page }) => { + await page.goto("/index.html?step=derive"); + + const normal = await page.evaluate(() => { + const dot = document.createElement("span"); + dot.className = "dot dot-scanning"; + document.body.appendChild(dot); + const name = getComputedStyle(dot).animationName; + dot.remove(); + return name; + }); + expect(normal).toBe("pulse"); + + await page.emulateMedia({ reducedMotion: "reduce" }); + const reduced = await page.evaluate(() => { + const dot = document.createElement("span"); + dot.className = "dot dot-scanning"; + document.body.appendChild(dot); + const style = getComputedStyle(dot); + const result = { name: style.animationName, duration: style.animationDuration }; + dot.remove(); + return result; + }); + expect(reduced.name).toBe("none"); + expect(parseFloat(reduced.duration)).toBeLessThanOrEqual(0.01); +}); + +test("critical flow works with the keyboard at 200% zoom and mobile width", async ({ page }) => { + for (const viewport of [ + { width: 640, height: 512, label: "200% zoom (640x512 CSS px)" }, + { width: 360, height: 740, label: "mobile width (360x740 CSS px)" }, + ]) { + await page.setViewportSize(viewport); + await completeFlowWithKeyboard(page); + await assertNoHorizontalOverflow(page, viewport.label); + } +}); diff --git a/scripts/playground/tests/playwright.config.ts b/scripts/playground/tests/playwright.config.ts index ee7340a..2627f0c 100644 --- a/scripts/playground/tests/playwright.config.ts +++ b/scripts/playground/tests/playwright.config.ts @@ -2,7 +2,7 @@ import path from "node:path"; import { fileURLToPath } from "node:url"; import { defineConfig } from "@playwright/test"; -// Playwright config for the Wraith Stealth Playground smoke tests. +// Playwright config for the Wraith Stealth Playground smoke and accessibility tests. // The playground is served over HTTP (not file://) because module script // loading and CSP behave differently on file://. const __dirname = path.dirname(fileURLToPath(import.meta.url));