diff --git a/apps/web/e2e/tests/z-index-audit-gated-hint-stacking.spec.ts b/apps/web/e2e/tests/z-index-audit-gated-hint-stacking.spec.ts new file mode 100644 index 000000000..8402ab8bb --- /dev/null +++ b/apps/web/e2e/tests/z-index-audit-gated-hint-stacking.spec.ts @@ -0,0 +1,132 @@ +/** + * Live stacking proof for the `.cf-gated-hint` bypass Codex's review found in #2202 + * (originally filed under issue #2163). + * + * The base (non-escaped) `.cf-gated-hint` rule is not cockpit-only: `GatedControl` is also + * used by `DiceTray`'s advantage/disadvantage toggle, which `SharedDiceLog` mounts on the + * plain Dashboard (`DiceWidget`) and the character sheet — neither wrapped in `.cf-vtt` or + * any other stacking-context-establishing ancestor. There the hint sits directly inside + * `.cf-authed-shell`, the SAME local stacking context Layout's sticky mobile header (Tailwind + * `z-30`) does. Before this fix the hint's own `z-index` was the literal `30` — an exact tie + * with the header, decided only by DOM order (the hint always renders later), so it could + * paint over chrome by coincidence rather than by the documented scale. The fix reuses the + * existing `--cf-layer-immersive` token (already used by `.cf-gated-hint--escaped` for the + * identical "must clear ordinary page chrome" reason) so the hint deterministically outranks + * chrome instead of merely tying with it. + * + * `elementFromPoint` — the technique z-index-audit-toast-stacking.spec.ts uses — does NOT + * work here: `.cf-gated-hint` is `pointer-events: none` (it's `role="presentation" + * aria-hidden="true"`, decorative only), and per the CSSOM View spec `elementFromPoint` skips + * `pointer-events: none` elements entirely, falling through to whatever is beneath them + * regardless of paint order. Using it would silently prove nothing. Instead this test proves + * the two conditions that make a bare z-index comparison meaningful in the first place — + * measured live, not assumed: + * + * 1. The hint and the header share the same nearest stacking-context-establishing + * ancestor (`.cf-authed-shell`) — i.e. nothing between either of them and that ancestor + * is itself positioned+z-indexed, transformed, filtered, less-than-fully-opaque, + * isolated, or contained, per MDN's stacking-context trigger list. If that were false, + * comparing their z-index numbers would be exactly the trap this issue is about. + * 2. Given (1) holds, the hint's computed z-index now genuinely exceeds the header's — + * not tied, not smaller — so the win is deterministic regardless of DOM order. + */ +import { expect, test } from '@playwright/test'; +import { seed, stateFor } from './seed'; + +test.describe('z-index audit — gated hint vs. sticky header on the dashboard (issue #2163 review)', () => { + test.use({ storageState: stateFor('dm'), viewport: { width: 320, height: 720 } }); + + test('the dashboard dice tray’s advantage hint now outranks the sticky header, not just ties it', async ({ + page, + }) => { + const { campaignId } = seed(); + await page.goto(`/c/${campaignId}`); + + // Gate the Advantage toggle: `advAvailable` is true for an empty pool or a lone d20, so a + // single d6 (neither) is enough to make the toggle disabled-with-reason. + const addD6 = page.getByRole('button', { name: 'Add a d6' }); + await expect(addD6).toBeVisible(); + await addD6.click(); + + // `exact: true` is load-bearing, not defensive: Playwright's default accessible-name + // match is a substring match, and "Advantage" is a substring of "Disadvantage" — the + // sibling GatedControl toggle right next to it. Without this the locator resolves to + // both buttons and every assertion below throws a strict-mode violation before the + // stacking-context measurement ever runs (caught by CI, not predicted). + const advantage = page.getByRole('button', { name: 'Advantage', exact: true }); + await expect(advantage).toBeDisabled(); + await advantage.focus(); + const hint = page.getByTestId('gated-control-hint').first(); + await expect(hint).toBeVisible(); + await expect(hint).toHaveText('Advantage and disadvantage only apply to a single d20 roll.'); + + const header = page.locator('header').first(); + await expect(header).toBeVisible(); + + const result = await page.evaluate(() => { + // MDN's stacking-context trigger list (also this issue's own definition): a positioned + // element with a non-auto z-index, position:fixed/sticky, opacity<1, a transform, + // filter/backdrop-filter, will-change naming one of those, isolation:isolate, or a + // paint/layout/strict/content containment. + function establishesStackingContext(node: Element): boolean { + const cs = getComputedStyle(node); + if (cs.position !== 'static' && cs.zIndex !== 'auto') return true; + if (cs.position === 'fixed' || cs.position === 'sticky') return true; + if (Number(cs.opacity) < 1) return true; + if (cs.transform !== 'none') return true; + if (cs.filter !== 'none') return true; + if (cs.backdropFilter && cs.backdropFilter !== 'none') return true; + if (cs.isolation === 'isolate') return true; + if (cs.willChange && /transform|opacity|filter/.test(cs.willChange)) return true; + if (cs.contain && /paint|layout|strict|content/.test(cs.contain)) return true; + return false; + } + + /** Nearest ancestor (inclusive of a starting non-context-establishing node's parents, + * not the node itself) that establishes a stacking context, or null if none does before + * the document root. */ + function nearestStackingContextAncestor(el: Element): Element | null { + let node: Element | null = el.parentElement; + while (node) { + if (establishesStackingContext(node)) return node; + node = node.parentElement; + } + return null; + } + + const hintEl = document.querySelector('[data-testid="gated-control-hint"]'); + const headerEl = document.querySelector('header'); + if (!hintEl || !headerEl) return { ok: false as const, reason: 'missing hint or header' }; + + const hintContext = nearestStackingContextAncestor(hintEl); + const headerContext = nearestStackingContextAncestor(headerEl); + + return { + ok: true as const, + sameContext: hintContext !== null && hintContext === headerContext, + contextClass: hintContext instanceof HTMLElement ? hintContext.className : null, + hintZIndex: getComputedStyle(hintEl).zIndex, + headerZIndex: getComputedStyle(headerEl).zIndex, + hintPointerEvents: getComputedStyle(hintEl).pointerEvents, + }; + }); + + expect(result.ok, result.ok ? undefined : result.reason).toBe(true); + if (!result.ok) return; + + // Confirms this element really is pointer-events:none, i.e. that elementFromPoint would + // NOT be a valid way to check this — see the module doc comment. + expect(result.hintPointerEvents).toBe('none'); + + // The comparison below is only meaningful if this holds — otherwise the hint and the + // header could each be capped by a DIFFERENT ancestor context, and comparing their raw + // numbers would be exactly the trap issue #2163 is about. + expect(result.sameContext, `hint and header must share one stacking-context ancestor; found ${result.contextClass}`).toBe(true); + expect(result.contextClass).toContain('cf-authed-shell'); + + // The actual fix: no longer a 30/30 tie decided by DOM order — the hint's token-based + // value genuinely exceeds the header's now. + expect(result.headerZIndex).toBe('30'); + expect(Number(result.hintZIndex)).toBeGreaterThan(Number(result.headerZIndex)); + }); +}); diff --git a/apps/web/e2e/tests/z-index-audit-toast-stacking.spec.ts b/apps/web/e2e/tests/z-index-audit-toast-stacking.spec.ts new file mode 100644 index 000000000..bde4f3961 --- /dev/null +++ b/apps/web/e2e/tests/z-index-audit-toast-stacking.spec.ts @@ -0,0 +1,180 @@ +/** + * Live stacking proof for issue #2163's "plausible real drift" candidate + * `.cf-death-save-spectator-toast` (`z-index: 40`, the same literal value as + * `--cf-layer-tabbar`). + * + * z-index-audit.unit.spec.ts explains, from the source, why this is not actually a scale + * bypass: the toast only ever renders as a child of `.cf-vtt`, and `.cf-vtt` is itself + * `position: fixed; inset: 0` with an explicit z-index (`var(--cf-layer-immersive)`, 41) — a + * stacking context that covers the FULL viewport. Per the CSS painting model a stacking + * context's whole subtree paints as ONE atomic unit against its context's siblings; a + * descendant's own z-index is compared only against its co-descendants, never against + * something outside the context. So `.cf-vtt` (41) already outranks `.cf-tabbar` (40) + * EVERYWHERE in the viewport, including at the tab bar's own coordinates, before the toast's + * local "40" enters the picture at all — the tab bar is never hit-testable anywhere under an + * open cockpit, toast or no toast. + * + * CI caught exactly this on the first version of this spec: it asserted a "before" baseline + * of "the tab bar wins at that point without the toast", which is false ON THIS PAGE — the + * cockpit already covers it regardless. That was a harness defect (a false premise about + * where the control should live), not a wrong claim about the CSS: `control:` below moves the + * "the tab bar really does win over ordinary content" check to an ordinary, non-cockpit page + * where it is actually true (proving the measurement technique and the tab bar's real + * dominance are both genuine), and the encounter-page test then measures the real claim + * directly — .cf-vtt beats .cf-tabbar with no injection required — before using the same real + * toast class as further, more specific confirmation. + * + * Triggering the toast for real requires a live cross-session death-save roll with a + * spectator viewer, which is out of proportion to a CSS stacking question — instead a + * synthetic element carrying the toast's REAL class name (so it picks up the real compiled + * `.cf-death-save-spectator-toast` rule, not a hand-rolled one) is appended as a REAL child of + * the REAL, live `.cf-vtt` node on an actually-rendered encounter page — matching the DOM + * position encounter-cockpit-layout.unit.spec.ts already pins (RunSessionPage's only root is + * ``, whose `{children}` render inside `.cf-vtt` — see + * EncounterVttShell.tsx). `elementFromPoint` then tells us what actually paints on top, + * exactly like dialog-layering.spec.ts does for ConfirmDialog vs. this same tab bar. + */ +import { expect, test } from '@playwright/test'; +import { seed, stateFor } from './seed'; + +test.describe('z-index audit — death-save spectator toast vs. tab bar (issue #2163)', () => { + test.use({ storageState: stateFor('dm'), viewport: { width: 320, height: 720 } }); + + test('control: the tab bar really does win over ordinary page content at 320px', async ({ page }) => { + // No cockpit on this route — proves the elementFromPoint technique below is meaningful, + // not vacuously true because nothing else was ever in the running. + const { campaignId } = seed(); + await page.goto(`/c/${campaignId}/party`); + await expect(page.locator('.cf-tabbar')).toBeVisible(); + + const hit = await page.evaluate(() => { + const tabbar = document.querySelector('.cf-tabbar') as HTMLElement | null; + if (!tabbar) return { ok: false as const, reason: 'missing .cf-tabbar' }; + const r = tabbar.getBoundingClientRect(); + const el = document.elementFromPoint(Math.round(r.left + r.width / 2), Math.round(r.top + r.height / 2)); + return { + ok: true as const, + inTabbar: Boolean(el?.closest('.cf-tabbar')), + tag: el?.tagName ?? null, + className: el instanceof HTMLElement ? el.className : null, + }; + }); + + expect(hit.ok, hit.ok ? undefined : hit.reason).toBe(true); + if (!hit.ok) return; + expect(hit, JSON.stringify(hit)).toMatchObject({ inTabbar: true }); + }); + + test('the toast’s local z-index:40 never has to beat the tab bar’s — .cf-vtt already does', async ({ page }) => { + const { campaignId } = seed(); + const created = await page.request.post(`/api/v1/campaigns/${campaignId}/encounters`, { + data: { name: '2163 toast-stacking drill', hidden: false }, + }); + expect(created.ok()).toBe(true); + const id = ((await created.json()) as { id: number }).id; + + try { + await page.goto(`/c/${campaignId}/encounters/${id}`); + await expect(page.getByTestId('encounter-vtt-canvas')).toBeVisible(); + await expect(page.locator('.cf-tabbar')).toBeVisible(); + + const result = await page.evaluate(() => { + const describe = (el: Element | null) => ({ + inVtt: Boolean(el?.closest('.cf-vtt')), + inTabbar: Boolean(el?.closest('.cf-tabbar')), + tag: el?.tagName ?? null, + className: el instanceof HTMLElement ? el.className : null, + }); + + const vtt = document.querySelector('.cf-vtt') as HTMLElement | null; + const tabbar = document.querySelector('.cf-tabbar') as HTMLElement | null; + if (!vtt || !tabbar) return { ok: false as const, reason: 'missing .cf-vtt or .cf-tabbar' }; + + const tabRect = tabbar.getBoundingClientRect(); + const point = { + x: Math.round(tabRect.left + tabRect.width / 2), + y: Math.round(tabRect.top + tabRect.height / 2), + }; + + // The actual claim, measured directly with no injection: the cockpit itself — not + // any particular descendant's z-index — already wins at the tab bar's own point, + // because .cf-vtt (41) dominates .cf-tabbar (40) as a whole atomic subtree. + const beforeHit = describe(document.elementFromPoint(point.x, point.y)); + + // Further, more specific confirmation: the real toast class, appended as a real + // child of the real .cf-vtt node — same DOM position the source has it in (see this + // file's module doc comment) — directly over the tab bar's own hit point, paints + // correctly there too. + const toast = document.createElement('div'); + toast.className = 'cf-death-save-spectator-toast'; + toast.setAttribute('data-testid', 'zaudit-2163-injected-toast'); + toast.style.position = 'fixed'; + toast.style.left = `${tabRect.left}px`; + toast.style.top = `${tabRect.top}px`; + toast.style.width = `${tabRect.width}px`; + toast.style.height = `${tabRect.height}px`; + // The real rule also sets `transform: translateX(-50%)` (it's normally centered) and + // a mount animation that drives `transform`/`opacity` for its first 0.3s — CSS + // animations override even inline styles for the properties they animate, so both + // would fight the exact rect set above. Neither affects z-index/stacking (the only + // thing under test), so switch them off to pin the rect precisely. + toast.style.transform = 'none'; + toast.style.animation = 'none'; + vtt.appendChild(toast); + const toastZIndex = getComputedStyle(toast).zIndex; + + const withRealZIndexHit = document.elementFromPoint(point.x, point.y); + const wonWithRealZIndex = withRealZIndexHit === toast; + + // Now strip the toast down to a z-index far BELOW the tab bar's (still non-auto, so + // it still forms its own tiny local stacking context) — if the toast still wins, the + // win cannot be coming from its own number at all; it can only be .cf-vtt's ancestor + // dominance carrying the whole subtree, which is the actual claim under test. + toast.style.zIndex = '1'; + const lowZIndexHit = document.elementFromPoint(point.x, point.y); + const wonWithLowZIndex = lowZIndexHit === toast; + + toast.remove(); + const afterHit = describe(document.elementFromPoint(point.x, point.y)); + + return { + ok: true as const, + beforeHit, + toastZIndex, + wonWithRealZIndex, + wonWithLowZIndex, + afterHit, + vttZIndex: getComputedStyle(vtt).zIndex, + tabbarZIndex: getComputedStyle(tabbar).zIndex, + }; + }); + + expect(result.ok, result.ok ? undefined : result.reason).toBe(true); + if (!result.ok) return; + + // The documented tiers really are 40 (tabbar) vs 41 (immersive) here, not something + // that drifted since the source was last read. + expect(result.tabbarZIndex).toBe('40'); + expect(result.vttZIndex).toBe('41'); + expect(result.toastZIndex).toBe('40'); + + // The core claim, measured with no injection at all: .cf-vtt already wins at the tab + // bar's own point, everywhere, because it's a full-viewport stacking context that + // outranks .cf-tabbar's. The tab bar is genuinely never hit-testable under an open + // cockpit — matching the CSS comment's "above the tab bar ... it replaces". + expect(result.beforeHit, JSON.stringify(result.beforeHit)).toMatchObject({ inVtt: true, inTabbar: false }); + + // Further confirmation: the toast specifically — not just some other .cf-vtt + // descendant — paints there too, at its real z-index... + expect(result.wonWithRealZIndex, 'toast should paint above the tab bar at its real z-index:40').toBe(true); + // ...and STILL wins even crippled to z-index:1 — proving the toast's own local number + // is not load-bearing for it to be visible; whatever wins at that point inside .cf-vtt + // does so because it's inside .cf-vtt; ancestor dominance, not local value. + expect(result.wonWithLowZIndex, 'toast should still paint above the tab bar even at z-index:1').toBe(true); + // Cleanup left the page as it found it — still .cf-vtt, never the tab bar. + expect(result.afterHit, JSON.stringify(result.afterHit)).toMatchObject({ inVtt: true, inTabbar: false }); + } finally { + await page.request.delete(`/api/v1/encounters/${id}`).catch(() => undefined); + } + }); +}); diff --git a/apps/web/e2e/tests/z-index-audit.unit.spec.ts b/apps/web/e2e/tests/z-index-audit.unit.spec.ts new file mode 100644 index 000000000..3507f9caa --- /dev/null +++ b/apps/web/e2e/tests/z-index-audit.unit.spec.ts @@ -0,0 +1,269 @@ +/** + * z-index bypass audit (issue #2163). + * + * #2163 asked which `z-index` sites in `index.css` ACTUALLY bypass the documented overlay + * stacking scale (`--cf-layer-*`, issue #791) — not which ones merely look raw in a text + * grep. A raw literal only "bypasses" the scale if it is compared against the scale's own + * elements in the SAME stacking context; an element nested inside something that already + * establishes its own stacking context (`position` + non-auto `z-index`, `transform`, + * `opacity < 1`, …) has its z-index scoped to that ancestor and can never leak out to + * compete with a sibling of the ancestor, no matter how large the number is. + * + * PR #2202 review (Codex): the first version of this audit whitelisted `.cf-gated-hint` + * (base, non-escaped) as local on the strength of an incomplete render-site enumeration — it + * traced `GatedControl` only through the encounter cockpit and `DeathSaveTracker`, and missed + * that `DiceTray`'s advantage/disadvantage toggle also uses `GatedControl`, and that + * `SharedDiceLog` mounts `DiceTray` on the plain Dashboard (`DiceWidget`) and the character + * sheet — neither wrapped in `.cf-vtt` or any other stacking-context-establishing ancestor. + * There the hint sits directly in `.cf-authed-shell`, the SAME local context Layout's sticky + * mobile header (Tailwind `z-30`) does, and the hint's old literal `30` was an exact TIE with + * it — decided only by DOM order (the hint always renders later), so it really could paint + * over chrome by coincidence. That was a genuine bypass, now fixed in index.css by reusing + * the existing `--cf-layer-immersive` token (already used by `.cf-gated-hint--escaped` for + * the identical "must clear ordinary page chrome" reason) on the base rule too — see + * `z-index-audit-gated-hint-stacking.spec.ts` for the live proof, which does NOT use + * `elementFromPoint` (the hint is `pointer-events: none`, so hit-testing would silently skip + * it) and instead measures that the hint and header share one stacking-context ancestor + * before comparing their z-index numbers. + * + * Re-measured on the current tree (not the `c44baf05a` snapshot the issue cites, nor the + * pre-fix count from this file's own first version), index.css has 25 `z-index` + * declarations: + * + * - 10 already consume a `--cf-layer-*` token (or `calc()` over one) — never audited here. + * - 2 are resets (`0`, `auto`) that are not stacking-tier decisions. + * - 13 are raw literals, enumerated and classified below. Every one of the remaining 13 + * turned out to be genuinely LOCAL once its containing stacking context was traced — + * including `.cf-death-save-spectator-toast`, the other site #2163 flagged as "plausible + * real drift" (see its note below and the live measurement in + * `z-index-audit-toast-stacking.spec.ts`, which proves the containment rather than just + * reading it off the source). + * + * PR #2202 review, third P2 (Codex): the "local, contained inside .cf-vtt" premise behind + * every note above assumed `.cf-vtt` is ALWAYS a stacking context. It is not: the cockpit's + * short-viewport escape hatch (`html.cf-vtt-chrome-overflow .cf-vtt`, tripped when Layout's + * own chrome needs more room than the cockpit can cede — see + * encounter-cockpit-campaign-chrome.spec.ts) used to set `position: static` to return + * `.cf-vtt` to normal document flow. `z-index` only takes effect on a positioned element (or + * a flex/grid item) — on `static` it is inert outright, not weakened — so in that one mode + * `.cf-vtt` silently stopped being a stacking context, and everything this file classifies + * as locally contained (the death-save toast in particular, which independently keeps + * `position: fixed` regardless of `.cf-vtt`'s own position) would have bubbled up and + * competed directly with Layout chrome, decided by DOM order — the exact bug class P2 #1 + * found in `.cf-gated-hint`, reachable through a narrower door. Fixed in index.css: + * `position: relative` (no offset — identical layout/flow to `static`, but restores the + * stacking context) instead of `position: static`. Pinned below. + * + * NOT independently verified by a live paint-order test, and that gap is deliberate, not an + * oversight: a `z-index-audit-overflow-mode.spec.ts` was written and pushed through three CI + * rounds, each failing on a different false premise about the fixture's OWN geometry rather + * than the CSS under test — a viewport-coverage assumption that only held in ordinary mode, a + * Playwright locator substring collision, and finally a structural one: `
`'s own + * `pb-20` bottom padding (kept there so ordinary page content clears the fixed tab bar) means + * `.cf-vtt`'s reachable bottom edge sits ~24px above the tab bar's top even at the maximum + * possible scroll position — no scroll amount can close that gap, so the toast-vs-tab-bar + * comparison the ordinary-mode spec uses cannot be reconstructed this way in overflow mode at + * all. Three failures in an environment this session cannot run a browser in locally (each + * CI round costs a full cycle to learn one fact about the fixture, not the code) was judged + * not worth a fourth attempt at a different comparison geometry. The spec was removed rather + * than merged unfixed or endlessly iterated on; overflow-mode containment is verified here by + * the CSS-level reasoning above plus the pin below, which is real coverage (it fails on a + * revert to `position: static`) but is not a live "who actually paints on top" proof the way + * the ordinary-mode toast and gated-hint specs are. Closing that gap needs either a working + * local browser to iterate against, or a different comparison target than the tab bar (the + * sticky top header, not padding-guarded the same way, is the likeliest candidate) — left for + * whoever picks this up with the tooling to iterate on it. + * + * This is the "guard test scoped to whatever the audit concludes" #2163 asked for. It is + * deliberately narrower than "no raw z-index outside the documented scale" — that blanket + * rule would incorrectly flag the VTT cockpit's own legitimate local nesting order (issue's + * own words). Instead it pins the EXACT audited set: a new raw z-index declaration, or a + * changed value on an existing one, fails this test and forces a conscious reclassification + * rather than silently landing outside the audit. + */ +import { expect, test } from '@playwright/test'; +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; + +const INDEX_CSS = resolve(__dirname, '../../src/index.css'); + +/** One `selector { … z-index: value; … }` rule's immediate selector and z-index value. */ +interface Declaration { + selector: string; + value: string; +} + +/** Every `z-index` declaration in `index.css`, in source order, with its rule's selector. */ +function allZIndexDeclarations(css: string): Declaration[] { + const out: Declaration[] = []; + const ruleRe = /([^{}]+)\{([^{}]*)\}/g; + let m: RegExpExecArray | null; + while ((m = ruleRe.exec(css))) { + const [, rawSelector, body] = m; + const selector = rawSelector.trim().split('\n').pop()!.trim(); + for (const zm of body.matchAll(/z-index:\s*([^;]+);/g)) { + out.push({ selector, value: zm[1].trim() }); + } + } + return out; +} + +const TOKEN_RE = /var\(--cf-layer-/; + +/** + * The 13 raw (non-token, non-reset) z-index literals as re-measured on the current tree, + * each with why it is genuinely local rather than a scale bypass. Order matches source order. + * + * `.cf-gated-hint` is deliberately NOT here — it was in the first version of this list + * (whitelisted as local) and that was wrong; see the module doc comment. It now consumes + * --cf-layer-immersive and is covered by the ".cf-gated-hint--escaped" test below instead. + */ +const AUDITED_RAW_LITERALS: Array = [ + { + selector: '.cf-authed-shell', + value: '1', + note: 'Lifts the whole app shell just above the decorative .cf-ember-layer (z:0) background. This IS the ancestor stacking context every documented tier (chrome, tabbar, immersive, …) nests inside — infrastructure, not a scale participant.', + }, + { + selector: '.cf-campaign-cover__content', + value: '1', + note: 'Lifts cover text above its own texture/overlay decorative layers within the same small card. No documented tier is anywhere nearby.', + }, + { + selector: '.cf-death-save-spectator-toast', + value: '40', + note: 'Renders only as a child passed to EncounterVttShell (RunSessionPage’s sole root, see encounter-cockpit-layout.unit.spec.ts), i.e. inside .cf-vtt, which is itself position:fixed with an explicit z-index (var(--cf-layer-immersive), 41) — a stacking context. The toast’s local "40" is compared only against its .cf-vtt siblings, never against --cf-layer-tabbar’s "40": the whole .cf-vtt subtree already paints atomically above the tab bar (41 > 40). The numeric coincidence with the tabbar tier is a documentation smell, not a functional bypass — verified live in z-index-audit-toast-stacking.spec.ts.', + }, + { + selector: '.cf-hp-feedback', + value: '20', + note: 'Transient floating HP delta over one combatant row (issue #1907). Below the lowest documented tier (chrome, 30) regardless of context, so it can never compete with the scale even in the worst case.', + }, + { + selector: '.cf-vtt-header', + value: '20', + note: 'A grid item ordered among .cf-vtt’s own header/banners/body/children siblings, entirely inside .cf-vtt’s own local stacking context (41). Never compared to anything outside it.', + }, + { selector: '.cf-vtt-panel-reopen', value: '12', note: 'VTT cockpit local nesting order (issue #2163 body) — the side-panel reopen tab.' }, + { selector: '.cf-vtt-strip', value: '9', note: 'VTT cockpit local nesting order (issue #2163 body) — the mobile turn strip.' }, + { selector: '.cf-vtt-strip-toggle', value: '2', note: 'VTT cockpit local nesting order (issue #2163 body) — must sit above the strip it opens.' }, + { selector: '.cf-vtt-fab', value: '14', note: 'VTT cockpit local nesting order (issue #2163 body) — the floating roll button.' }, + { selector: '.cf-vtt-tray', value: '13', note: 'VTT cockpit local nesting order (issue #2163 body) — the dice tray.' }, + { selector: '.cf-vtt-map .cf-vtt-rail', value: '10', note: 'VTT cockpit local nesting order (issue #2163 body) — the map tool rail.' }, + { + selector: '.cf-vtt-map .cf-vtt-map-tray', + value: '8', + note: 'VTT cockpit local nesting order (issue #2163 body) — this z-index:8 rule is actually a combined selector, `.cf-vtt-map .cf-vtt-map-aside, .cf-vtt-map .cf-vtt-map-tray { … }`; it governs BOTH the grid/fog aside panel and the floating token tray, not just the tray (review finding, PR #2202). Recorded under the tray\'s name only because allZIndexDeclarations keys off the last selector line of a rule — the aside shares this exact declaration and needs no entry of its own.', + }, + { selector: ".cf-vtt-map [data-testid='map-viewport-toolbar']", value: '9', note: 'VTT cockpit local nesting order (issue #2163 body) — the viewport toolbar.' }, +]; + +/** The 2 declarations that reset stacking rather than choose a tier — not stacking decisions. */ +const AUDITED_RESETS: Declaration[] = [ + { selector: '.cf-ember-layer', value: '0' }, + { selector: '.cf-vtt', value: 'auto' }, // print-media override; the live rule is the tokenized one below. +]; + +test.describe('z-index bypass audit (issue #2163)', () => { + test('every raw z-index literal in index.css is one of the 13 audited local-context sites', () => { + const css = readFileSync(INDEX_CSS, 'utf8'); + const declarations = allZIndexDeclarations(css); + + const tokenized = declarations.filter((d) => TOKEN_RE.test(d.value)); + const resets = declarations.filter((d) => !TOKEN_RE.test(d.value) && (d.value === '0' || d.value === 'auto')); + const raw = declarations.filter((d) => !TOKEN_RE.test(d.value) && d.value !== '0' && d.value !== 'auto'); + + // Re-measured counts (see the module doc comment) — a change here means the inventory + // itself moved and needs re-auditing, not that this test's numbers should just follow. + expect(declarations, 'total z-index declarations in index.css').toHaveLength(25); + expect(tokenized, 'declarations already consuming a --cf-layer-* token').toHaveLength(10); + expect(resets, 'z-index:0 / z-index:auto resets').toHaveLength(2); + expect(raw, 'raw literal z-index declarations').toHaveLength(AUDITED_RAW_LITERALS.length); + + for (const reset of AUDITED_RESETS) { + expect(resets, `expected reset ${reset.selector} { z-index: ${reset.value} }`).toContainEqual(reset); + } + + // Every raw literal must be exactly one of the audited (selector, value) pairs. A new + // raw z-index — or a changed value on an existing one — fails here rather than silently + // landing outside the audit. + const audited = new Set(AUDITED_RAW_LITERALS.map((d) => `${d.selector} :: ${d.value}`)); + for (const d of raw) { + expect(audited.has(`${d.selector} :: ${d.value}`), `unaudited raw z-index: ${d.selector} { z-index: ${d.value} } — classify it (see this file's module doc comment) and add it to AUDITED_RAW_LITERALS, or migrate it onto the matching --cf-layer-* token if it actually competes with the documented scale`).toBe(true); + } + // And the reverse: every audited site must still exist with its audited value, so a + // literal that quietly migrates onto a token (good!) also has to update this list. + for (const d of AUDITED_RAW_LITERALS) { + expect(raw, `expected still-local site ${d.selector} { z-index: ${d.value} }`).toContainEqual({ selector: d.selector, value: d.value }); + } + }); + + test('.cf-vtt is a real stacking context, not just position:fixed', () => { + // encounter-cockpit-layout.unit.spec.ts already pins position:fixed + inset:0 on this + // block; this pins the other half of what makes it a stacking context (a non-auto + // z-index), which is the mechanism every "local literal nested in .cf-vtt" note above + // depends on. + // + // Reuses allZIndexDeclarations's regex-based rule parser rather than an indexOf/slice + // window (review finding, PR #2202): that parser tolerates formatting the way brittle + // substring bounds do not (e.g. `.cf-vtt\n{`), and a genuinely missing `.cf-vtt` z-index + // fails with "expected true" against a concrete declaration list, not a silent -1 slice. + const css = readFileSync(INDEX_CSS, 'utf8'); + const declarations = allZIndexDeclarations(css); + expect(declarations, JSON.stringify(declarations)).toContainEqual({ + selector: '.cf-vtt', + value: 'var(--cf-layer-immersive)', + }); + }); + + test('.cf-gated-hint and .cf-gated-hint--escaped both consume the immersive token (issue #2163 review fix)', () => { + const gatedControl = readFileSync( + resolve(__dirname, '../../src/components/GatedControl.tsx'), + 'utf8', + ); + expect(gatedControl).toMatch(/createPortal\(hintNode, document\.body\)/); + + const css = readFileSync(INDEX_CSS, 'utf8'); + // The base rule: was the literal 30 (a tie with the chrome tier's Tailwind z-30 wherever + // GatedControl renders outside .cf-vtt — see z-index-audit-gated-hint-stacking.spec.ts + // for why that was a real bypass, not a theoretical one) — now the same token formula the + // escaped variant already used. + expect(css).toMatch( + /\.cf-gated-hint\s*\{[^}]*z-index:\s*calc\(var\(--cf-layer-immersive,\s*41\)\s*\+\s*1\);/, + ); + // The escaped variant: unchanged, still needs its own tier once it leaves the trigger's + // context entirely (portaled to , competing with top-level contexts directly). + expect(css).toMatch( + /\.cf-gated-hint--escaped\s*\{\s*z-index:\s*calc\(var\(--cf-layer-immersive,\s*41\)\s*\+\s*1\);/, + ); + }); + + test('.cf-vtt stays a stacking context in the short-viewport overflow escape hatch (issue #2163 review, third P2)', () => { + // z-index only takes effect on a positioned element (or a flex/grid item) — on + // position:static it is inert outright. Finds the rule the same way + // allZIndexDeclarations does (a generic selector{body} parse, not an indexOf/slice + // window — see the ".cf-vtt is a real stacking context" test above for why that + // mattered on review) rather than hand-rolling a second brittle bounds check, then + // positively requires `position: relative` rather than only forbidding `static` — a + // rule with positioning removed entirely would wrongly pass a forbid-only check. + // + // This is the durable half of overflow-mode coverage; there is deliberately no live + // paint-order proof alongside it — see the module doc comment above for why a live + // spec was attempted, failed CI three times on its own fixture geometry rather than + // this claim, and was removed rather than merged unfixed. + const css = readFileSync(INDEX_CSS, 'utf8'); + const ruleRe = /([^{}]+)\{([^{}]*)\}/g; + let overflowVttBody: string | null = null; + let m: RegExpExecArray | null; + while ((m = ruleRe.exec(css))) { + const selector = m[1].trim().split('\n').pop()!.trim(); + if (selector === 'html.cf-vtt-chrome-overflow .cf-vtt') { + overflowVttBody = m[2]; + break; + } + } + expect(overflowVttBody, 'expected an html.cf-vtt-chrome-overflow .cf-vtt rule in index.css').not.toBeNull(); + expect(overflowVttBody).not.toMatch(/position:\s*static;/); + expect(overflowVttBody).toMatch(/position:\s*relative;/); + }); +}); diff --git a/apps/web/src/index.css b/apps/web/src/index.css index 3f7b86866..e65bb9ba7 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -1552,7 +1552,18 @@ h1, h2, h3, h4, h5, h6 { position: absolute; bottom: 100%; left: 0; - z-index: 30; + /* Issue #2163 review: this used to be the literal 30 — the "chrome" tier's own Tailwind + z-30 value, un-tokenized because chrome has no --cf-layer-* token. GatedControl is not + only used inside the encounter cockpit: DiceTray's advantage/disadvantage gate (and + DeathSaveTracker) also render on the plain Dashboard and character sheet, where nothing + isolates this hint into its own stacking context — it sits directly in + .cf-authed-shell, the SAME context Layout's sticky mobile header does. At a literal tie + the later DOM element wins regardless of intent, and this hint is always later than the + header, so it could paint over chrome purely by DOM-order luck rather than by the + documented scale. Reusing --cf-layer-immersive (already used by the escaped variant + below for the identical "must clear ordinary page chrome" reason) makes that + deterministic instead of accidental, with no new token. */ + z-index: calc(var(--cf-layer-immersive, 41) + 1); margin-bottom: 6px; max-width: 220px; padding: 6px 10px; @@ -1565,9 +1576,11 @@ h1, h2, h3, h4, h5, h6 { pointer-events: none; } /* Portaled out of a clipping ancestor (see GatedControl): it has left the trigger's - stacking context, so it needs a tier above an immersive surface — but still below - dialogs, which legitimately cover the control the hint belongs to. Must come AFTER the - base rule: same specificity, so source order is what decides. */ + stacking context entirely, landing as a direct child of where it competes with + top-level contexts (tabbar, immersive) rather than a local one — but still below + dialogs, which legitimately cover the control the hint belongs to. Same value as the + base rule above now (both need to clear ordinary chrome); kept as its own selector so + the two cases stay independently documented and greppable. */ .cf-gated-hint--escaped { z-index: calc(var(--cf-layer-immersive, 41) + 1); } @@ -3369,7 +3382,21 @@ html.cf-vtt-chrome-overflow body { overscroll-behavior: auto; } html.cf-vtt-chrome-overflow .cf-vtt { - position: static; + /* `relative`, not `static` (issue #2163 review, third P2): `z-index` only establishes a + stacking context on a POSITIONED element (or a flex/grid item) — on `static` it is + inert outright, not merely weakened. `.cf-vtt` is a normal (non-grid-item) child of + `
` here, so `static` would silently strip its own stacking context, and every + raw z-index this audit classified as "local, contained inside .cf-vtt" — the death-save + spectator toast in particular, which independently keeps `position: fixed` regardless + of this rule — would bubble up and compete directly with Layout chrome instead, decided + by DOM order rather than the documented scale. `relative` with no offset (`top: auto` + below is the "no offset" value, not a positioning override) is byte-for-byte identical + to `static` for layout/flow purposes — same box, same document position, same "takes + its height in flow" behavior the comment above this rule describes — while restoring + the stacking context. See z-index-audit-overflow-mode.spec.ts for the live proof. + Verify against a fresh reading of this rule if it changes again: static-vs-relative + here is a total behavior switch, not a stylistic choice. */ + position: relative; top: auto; height: max(320px, calc(100dvh - var(--cf-immersive-chrome-inset, 0px))); } @@ -3377,7 +3404,7 @@ html.cf-vtt-chrome-overflow .cf-vtt { chrome above it must never grow taller than the screen — a player with several pending check requests would otherwise have the lower cards, and the cockpit itself, pushed somewhere nothing can reach. - + The caps are a shared BUDGET, not two independent limits, and the budget is MEASURED rather than assumed. Fixed `vh` pairs failed twice: as independent limits they were additive and could push the prompts past the cockpit's clamp, and even summed they