feat: client shell, sign-in and protocol client (#67)

New `client/` package (Vite + TypeScript + PixiJS v8, plain DOM overlay):
the pure reducer seam (no Pixi import), an append-only slice registry
build-time glob, the `proto` 2 WS client with envelope/ack/closing mapping,
the sign-in door (`POST /join`, one "Key not recognised." for wrong and
unknown), the DOM shell/HUD and a minimal Pixi stage created only after a
live `hello`. `hello` resets every slice so a reconnect cannot show stale
state; `proto-mismatch` shows reload; `revoked` returns to the sign-in page
and stops.

The browser e2e moves into the client package (`client/e2e/`, owning
playwright-core) and runs the real Vite build through the TLS/HTTP2 test
nginx: join -> canvas -> hello/roster for GM and player, no data before
join, identical wrong/unknown key refusal, proto mismatch, revoked.
`devbox run client-test` adds the Vitest seam; `devbox run e2e` builds the
client first. The #66 stub dist stays local to `tools/vhost.test.mjs`, so
`devbox run test` still needs no npm install.

Refs #67
This commit is contained in:
2026-11-20 23:57:16 +01:00
parent 97f618c5ad
commit 3c0258ea31
37 changed files with 3439 additions and 178 deletions
+55
View File
@@ -0,0 +1,55 @@
// The browser half of the vhost gate (#66, TESTING 10.3): real Chromium loads the real client build
// from `/` through the TLS/HTTP2 test nginx and reports h2 for the document and its hashed assets.
// The client bundle replaces the throwaway `tools/distfixture.mjs` of #66; `client/e2e/run.sh`
// builds it before this test runs.
import test from 'node:test'
import assert from 'node:assert/strict'
import { launchBrowser, newPage, withStack } from './stack.mjs'
test('e2e: headless chromium loads the real client build and the page reports h2', { timeout: 120000 }, async () => {
await withStack(async ({ origin }) => {
const browser = await launchBrowser()
try {
const { page } = await newPage(browser)
const loaded = []
page.on('response', response => loaded.push({ url: response.url(), status: response.status() }))
const errors = []
page.on('pageerror', error => errors.push(error.message))
page.on('console', message => {
// The boot probe's refused WebSocket upgrade is the expected no-session path (the browser
// logs it); it is not a page error. Everything else must be silent.
if (message.type() === 'error' && !message.text().includes('WebSocket connection')) {
errors.push(message.text())
}
})
await page.goto(`${origin}/`, { waitUntil: 'load' })
assert.equal(await page.title(), 'FFF VTT')
await page.locator('#app').waitFor({ state: 'attached' })
// A visitor with no session gets the sign-in door; the canvas is created only after `hello`.
await page.locator('#signin').waitFor({ state: 'visible', timeout: 20000 })
assert.deepEqual(errors, [])
const assets = loaded.filter(response => new URL(response.url).pathname.startsWith('/assets/'))
assert.ok(assets.length > 0, `the page loaded hashed assets: ${JSON.stringify(loaded)}`)
assert.ok(assets.every(response => response.status === 200))
const proto = await page.evaluate(() => {
const navigation = performance.getEntriesByType('navigation')[0]
const resources = performance
.getEntriesByType('resource')
.map(entry => ({ name: entry.name, protocol: entry.nextHopProtocol }))
return { scheme: location.protocol, navigation: navigation.nextHopProtocol, resources }
})
assert.equal(proto.scheme, 'https:')
assert.equal(proto.navigation, 'h2', 'the document came over HTTP/2')
assert.ok(
proto.resources.some(resource => resource.protocol === 'h2' && resource.name.endsWith('.js')),
`subresources are h2 too: ${JSON.stringify(proto.resources)}`,
)
} finally {
await browser.close()
}
})
})
+38
View File
@@ -0,0 +1,38 @@
// Story 9 / DR 6.2 (#67): a proto mismatch completes the upgrade, sends closing{proto-mismatch}
// and closes; the client must show "reload" and stop, not sign in and not retry.
//
// The real server's mismatch path is already proven by tools/protocol.test.mjs (it takes a build
// whose proto differs). Here the browser's own WebSocket is intercepted and given exactly that
// documented frame sequence, so the assertion is about the client's UI and close-code mapping.
import test from 'node:test'
import assert from 'node:assert/strict'
import { launchBrowser, newPage, waitForText, waitForVisible, withStack } from './stack.mjs'
test('protocol mismatch: the client shows reload and does not reconnect', { timeout: 120000 }, async () => {
await withStack(async ({ origin }) => {
const browser = await launchBrowser()
try {
const { page } = await newPage(browser)
let sockets = 0
await page.routeWebSocket(/\/ws\?proto=2$/, ws => {
sockets += 1
// DESIGN 6.5 row 5: closing then the close frame; no hello, no state.
ws.send(JSON.stringify({ t: 'closing', n: 1, reason: 'proto-mismatch', code: 4003 }))
ws.close()
})
await page.goto(`${origin}/`)
await waitForVisible(page, '#fatal')
await waitForText(page, '#fatal-text', /out of date.*reload/i)
const reload = page.locator('#reload')
assert.equal(await reload.isVisible(), true)
assert.equal(await page.locator('#signin').isVisible(), false)
assert.equal(await page.locator('#stage canvas').count(), 0)
await new Promise(resolve => setTimeout(resolve, 400))
assert.equal(sockets, 1, 'a mismatch is terminal: exactly one connection attempt')
} finally {
await browser.close()
}
})
})
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env bash
# devbox run e2e: the headless-browser gate (TESTING 10.3). Builds the real client, then runs the
# browser suite against the real server through the TLS/HTTP2 test nginx. Separate from
# `devbox run test` so the fast server gate stays fast (TESTING 11.1); the client's own unit tests
# are `devbox run client-test`.
set -euo pipefail
cd "$(dirname "$0")/../.." || exit 1
mkdir -p results
export CHROMIUM="${CHROMIUM:-$(command -v chromium || true)}"
if [ -z "$CHROMIUM" ]; then
echo "e2e: chromium not found; it is a root devbox package (devbox.json) - run inside devbox" >&2
exit 1
fi
# npm deps stay out of tools/ (TESTING 10.4) and out of git; install once per checkout.
( cd client && { [ -d node_modules ] || npm ci --no-audit --no-fund; } )
( cd client && npm run build )
node --test --test-concurrency=1 --test-reporter=spec client/e2e/*.test.mjs > results/e2e.log 2>&1
rc=$?
cat results/e2e.log
exit $rc
+103
View File
@@ -0,0 +1,103 @@
// T4 client shell (#67, TESTING 10.3): join -> canvas -> hello/roster for the GM and a player, no
// data before join, one plain refusal for a wrong and an unknown key, and a revoked session
// returning to sign-in. The server, the nginx vhost and the client are the real ones.
import test from 'node:test'
import assert from 'node:assert/strict'
import { sleep } from '../../tools/lib.mjs'
import { openAs } from '../../tools/withserver.mjs'
import {
launchBrowser,
makePlayer,
newPage,
signIn,
waitForText,
waitForVisible,
withStack,
} from './stack.mjs'
const KEY_REFUSED = 'Key not recognised.'
async function canvasAndRoster(page, expectedNames) {
await waitForVisible(page, '#stage canvas')
await waitForVisible(page, '#hud')
const roster = await waitForText(page, '#roster', new RegExp(expectedNames[0]))
for (const name of expectedNames) assert.match(roster, new RegExp(name))
return roster
}
test('no session: only the sign-in page, and a wrong and an unknown key look identical', { timeout: 120000 }, async () => {
await withStack(async ({ origin }) => {
const browser = await launchBrowser()
try {
const { page } = await newPage(browser)
const joins = []
page.on('response', response => {
if (new URL(response.url()).pathname === '/join') joins.push(response.status())
})
await page.goto(`${origin}/`)
await waitForVisible(page, '#signin')
// Story 1: a stranger gets the door and no game data.
assert.equal(await page.locator('#stage').isVisible(), false)
assert.equal(await page.locator('#hud').isVisible(), false)
assert.equal(await page.locator('#roster li').count(), 0)
// Story 3: the same answer for a well-formed but wrong key and for an unknown one.
await signIn(page, 'ABCD-EFGH-JKMN-PQRS')
await waitForVisible(page, '#signin-error')
const wrong = await page.textContent('#signin-error')
await signIn(page, 'not-a-key')
await waitForVisible(page, '#signin-error')
const unknown = await page.textContent('#signin-error')
assert.equal(wrong, KEY_REFUSED)
assert.equal(unknown, KEY_REFUSED)
assert.deepEqual(joins, [401, 401])
// No map request was made before a session existed.
assert.equal(await page.locator('#stage canvas').count(), 0)
} finally {
await browser.close()
}
})
})
test('GM and player: join -> canvas -> hello and roster; revoked returns to sign-in', { timeout: 120000 }, async () => {
await withStack(async ({ origin, gmKey }) => {
const player = await makePlayer(origin, gmKey, 'Alice')
const browser = await launchBrowser()
try {
const gmView = await newPage(browser)
await gmView.page.goto(`${origin}/`)
await waitForVisible(gmView.page, '#signin')
await signIn(gmView.page, gmKey)
const gmRoster = await canvasAndRoster(gmView.page, ['GM', 'Alice'])
assert.equal(await gmView.page.textContent('#role'), 'GM')
assert.match(gmRoster, /connected/)
const playerView = await newPage(browser)
await playerView.page.goto(`${origin}/`)
await waitForVisible(playerView.page, '#signin')
await signIn(playerView.page, player.key)
await canvasAndRoster(playerView.page, ['GM', 'Alice'])
assert.equal(await playerView.page.textContent('#role'), 'Player')
assert.equal(await playerView.page.textContent('#me'), 'Alice')
// Story 10: the GM replaces the key, the server revokes the session, and the browser stops
// at the sign-in door instead of hammering a dead socket.
const gm = await openAs(origin, gmKey)
await gm.ws.waitText('hello')
const ack = await gm.ws.request({ t: 'key.replace', id: player.id })
assert.equal(ack.ok, true)
gm.ws.close()
await waitForVisible(playerView.page, '#signin')
await waitForText(playerView.page, '#signin-notice', /session has ended/i)
assert.equal(await playerView.page.locator('#stage canvas').count(), 0)
assert.equal(await playerView.page.locator('#roster li').count(), 0)
// No automatic reconnection: still on the sign-in page a moment later.
await sleep(300)
assert.equal(await playerView.page.locator('#signin').isVisible(), true)
} finally {
await browser.close()
}
})
})
+96
View File
@@ -0,0 +1,96 @@
// Shared stack for the client e2e (TESTING 10.3): the real client build served by the TLS/HTTP2
// test nginx in front of the real server binary. Never a fixture, never a mocked protocol.
import assert from 'node:assert/strict'
import fs from 'node:fs'
import path from 'node:path'
import { chromium } from 'playwright-core'
import { createPlayer, freePort, httpsBaseUrl, namePlayer, projectRoot, sleep } from '../../tools/lib.mjs'
import { gmKeyOf, makeStateDir, openAs, startServer, stopServer } from '../../tools/withserver.mjs'
import { startTestNginx, stopTestNginx } from '../../tools/nginx.mjs'
export const CHROMIUM = process.env.CHROMIUM ?? 'chromium'
export const LAUNCH_ARGS = [
'--no-sandbox',
'--use-angle=swiftshader',
'--enable-unsafe-swiftshader',
'--ignore-gpu-blocklist',
]
export const CLIENT_DIST = path.join(projectRoot, 'client', 'dist')
export function assertClientBuild() {
assert.ok(
fs.existsSync(path.join(CLIENT_DIST, 'index.html')),
`client build missing at ${CLIENT_DIST}: run \`npm run build\` in client/ (client/e2e/run.sh does)`,
)
}
export async function withStack(fn) {
assertClientBuild()
const stateDir = makeStateDir()
const gmKey = gmKeyOf(stateDir)
const nginxPort = await freePort()
const server = await startServer({ stateDir, publicOrigin: httpsBaseUrl(nginxPort) })
let nginx
try {
nginx = await startTestNginx({
backendPort: server.port,
stateDir,
port: nginxPort,
distDir: CLIENT_DIST,
})
return await fn({ stateDir, server, nginx, origin: nginx.origin, gmKey })
} finally {
if (nginx) await stopTestNginx(nginx)
await stopServer(server)
fs.rmSync(stateDir, { recursive: true, force: true })
}
}
export async function launchBrowser() {
return chromium.launch({ executablePath: CHROMIUM, args: LAUNCH_ARGS })
}
export async function newPage(browser) {
// The certificate is generated per run by tools/tlsdev.mjs; trusting it in the browser is the
// one concession, the rest of the page is the real https/h2 path.
const context = await browser.newContext({ ignoreHTTPSErrors: true, viewport: { width: 1000, height: 700 } })
return { context, page: await context.newPage() }
}
/** A named player created the way the product creates one: a GM key.create, then player.setname. */
export async function makePlayer(origin, gmKey, name) {
const gm = await openAs(origin, gmKey)
await gm.ws.waitText('hello')
const created = await createPlayer(gm.ws)
await namePlayer(origin, created.key, name)
gm.ws.close()
await gm.ws.closed
return { id: created.id, key: created.key, name }
}
export async function signIn(page, key) {
await page.fill('#key', key)
await page.click('#signin-submit')
}
export async function waitForVisible(page, selector, timeout = 20000) {
await page.locator(selector).waitFor({ state: 'visible', timeout })
}
export async function waitForHidden(page, selector, timeout = 20000) {
await page.locator(selector).waitFor({ state: 'hidden', timeout })
}
export async function waitForText(page, selector, pattern, timeout = 20000) {
const deadline = Date.now() + timeout
let last = ''
while (Date.now() < deadline) {
last = (await page.locator(selector).textContent()) ?? ''
if (pattern.test(last)) return last
await sleep(50)
}
throw new Error(`${selector} never matched ${pattern}: last was ${JSON.stringify(last)}`)
}
export { sleep }