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:
@@ -0,0 +1,137 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
CLOSE_REASONS,
|
||||
PROTO,
|
||||
closeOutcome,
|
||||
encodeIntent,
|
||||
isAck,
|
||||
isClosing,
|
||||
isHello,
|
||||
parseServerFrame,
|
||||
wsUrl,
|
||||
} from '../src/protocol.ts'
|
||||
|
||||
const scene = {
|
||||
id: 1,
|
||||
name: 'Cellar',
|
||||
w: 4096,
|
||||
h: 4096,
|
||||
tile_size: 32,
|
||||
cell: 32,
|
||||
grid_size: 64,
|
||||
vision_radius_default: 320,
|
||||
token_radius_default: 20,
|
||||
art_version: 1,
|
||||
}
|
||||
|
||||
describe('server envelope', () => {
|
||||
it('parses a JSON object with a string t and an integer n >= 1', () => {
|
||||
const frame = parseServerFrame(JSON.stringify({ t: 'roster', n: 3, players: [] }))
|
||||
expect(frame).toEqual({ t: 'roster', n: 3, players: [] })
|
||||
})
|
||||
|
||||
it('ignores unknown frame types without dropping them (6.2: additive only)', () => {
|
||||
const frame = parseServerFrame(JSON.stringify({ t: 'future_frame', n: 2, x: 1 }))
|
||||
expect(frame?.t).toBe('future_frame')
|
||||
})
|
||||
|
||||
it.each([
|
||||
['binary', new Uint8Array([1, 2, 3])],
|
||||
['non-JSON', '{not json'],
|
||||
['array', '[]'],
|
||||
['null', 'null'],
|
||||
['no t', JSON.stringify({ n: 1 })],
|
||||
['empty t', JSON.stringify({ t: '', n: 1 })],
|
||||
['no n', JSON.stringify({ t: 'hello' })],
|
||||
['n = 0', JSON.stringify({ t: 'hello', n: 0 })],
|
||||
['fractional n', JSON.stringify({ t: 'hello', n: 1.5 })],
|
||||
['string n', JSON.stringify({ t: 'hello', n: '1' })],
|
||||
])('rejects %s', (_name, raw) => {
|
||||
expect(parseServerFrame(raw)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('hello', () => {
|
||||
it('accepts the DESIGN 6.1 shape and carries the scene block', () => {
|
||||
const frame = parseServerFrame(
|
||||
JSON.stringify({ t: 'hello', n: 1, proto: 2, role: 'player', me: { id: 4, name: 'Ann' }, scene }),
|
||||
)
|
||||
expect(frame && isHello(frame)).toBe(true)
|
||||
if (frame && isHello(frame)) {
|
||||
expect(frame.proto).toBe(2)
|
||||
expect(frame.scene?.w).toBe(4096)
|
||||
}
|
||||
})
|
||||
|
||||
it('accepts the unnamed-player minimum (proto, role, me only)', () => {
|
||||
const frame = parseServerFrame(
|
||||
JSON.stringify({ t: 'hello', n: 1, proto: 2, role: 'player', me: { id: 4, name: null } }),
|
||||
)
|
||||
expect(frame && isHello(frame)).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects a wrong role or proto', () => {
|
||||
const badRole = parseServerFrame(
|
||||
JSON.stringify({ t: 'hello', n: 1, proto: 2, role: 'admin', me: { id: 1, name: null } }),
|
||||
)
|
||||
const badProto = parseServerFrame(
|
||||
JSON.stringify({ t: 'hello', n: 1, proto: '2', role: 'gm', me: { id: 1, name: null } }),
|
||||
)
|
||||
expect(badRole && isHello(badRole)).toBe(false)
|
||||
expect(badProto && isHello(badProto)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('ack', () => {
|
||||
it('is the envelope plus reqId and ok', () => {
|
||||
const frame = parseServerFrame(JSON.stringify({ t: 'ack', n: 2, reqId: 7, ok: true, pos: [1, 2] }))
|
||||
expect(frame && isAck(frame)).toBe(true)
|
||||
if (frame && isAck(frame)) expect(frame.pos).toEqual([1, 2])
|
||||
})
|
||||
|
||||
it('is not an ack without an integer reqId or a boolean ok', () => {
|
||||
for (const body of [
|
||||
{ t: 'ack', n: 1, ok: true },
|
||||
{ t: 'ack', n: 1, reqId: '7', ok: true },
|
||||
{ t: 'ack', n: 1, reqId: 7, ok: 'yes' },
|
||||
]) {
|
||||
const frame = parseServerFrame(JSON.stringify(body))
|
||||
expect(frame && isAck(frame)).toBe(false)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('closing and outcomes', () => {
|
||||
it('accepts every static reason of DESIGN 6.5', () => {
|
||||
for (const reason of CLOSE_REASONS) {
|
||||
const frame = parseServerFrame(
|
||||
JSON.stringify({ t: 'closing', n: 9, reason, code: 4001 }),
|
||||
)
|
||||
expect(frame && isClosing(frame)).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
it('maps reasons to the shell outcome', () => {
|
||||
expect(closeOutcome('proto-mismatch')).toBe('reload')
|
||||
expect(closeOutcome('revoked')).toBe('signin')
|
||||
expect(closeOutcome('evicted')).toBe('offline')
|
||||
expect(closeOutcome('malformed-flood')).toBe('offline')
|
||||
expect(closeOutcome(null)).toBe('offline')
|
||||
})
|
||||
})
|
||||
|
||||
describe('intents', () => {
|
||||
it('always carry t and reqId and nothing secret', () => {
|
||||
const raw = encodeIntent('conn.ping', 3, { ts: 99 })
|
||||
expect(JSON.parse(raw)).toEqual({ t: 'conn.ping', reqId: 3, ts: 99 })
|
||||
})
|
||||
|
||||
it('builds the /ws URL with the required proto parameter', () => {
|
||||
expect(wsUrl({ protocol: 'https:', host: 'table.example' })).toBe(
|
||||
`wss://table.example/ws?proto=${PROTO}`,
|
||||
)
|
||||
expect(wsUrl({ protocol: 'http:', host: '127.0.0.1:8080' })).toBe(
|
||||
`ws://127.0.0.1:8080/ws?proto=${PROTO}`,
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,184 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { SLICES, initialState, reduce, rosterOf } from '../src/reducer.ts'
|
||||
import type { ReducerEvent, RootState } from '../src/reducer.ts'
|
||||
import { parseServerFrame } from '../src/protocol.ts'
|
||||
import type { RosterEntry } from '../src/protocol.ts'
|
||||
|
||||
const scene = (name: string) => ({
|
||||
id: 1,
|
||||
name,
|
||||
w: 4096,
|
||||
h: 4096,
|
||||
tile_size: 32,
|
||||
cell: 32,
|
||||
grid_size: 64,
|
||||
vision_radius_default: 320,
|
||||
token_radius_default: 20,
|
||||
art_version: 1,
|
||||
})
|
||||
|
||||
const frame = (body: Record<string, unknown>): ReducerEvent => {
|
||||
const parsed = parseServerFrame(JSON.stringify(body))
|
||||
if (!parsed) throw new Error(`bad test frame ${JSON.stringify(body)}`)
|
||||
return { type: 'frame', frame: parsed }
|
||||
}
|
||||
|
||||
const hello = (n: number, extra: Record<string, unknown> = {}): ReducerEvent =>
|
||||
frame({
|
||||
t: 'hello',
|
||||
n,
|
||||
proto: 2,
|
||||
role: 'player',
|
||||
me: { id: 2, name: 'Ann' },
|
||||
scene: scene('Cellar'),
|
||||
...extra,
|
||||
})
|
||||
|
||||
const roster = (n: number, players: RosterEntry[]): ReducerEvent =>
|
||||
frame({ t: 'roster', n, players })
|
||||
|
||||
const run = (...events: ReducerEvent[]): RootState =>
|
||||
events.reduce((state, event) => reduce(state, event), initialState())
|
||||
|
||||
describe('hello resets the whole view (6.1/6.3)', () => {
|
||||
it('clears every slice and replaces session fields on a second hello', () => {
|
||||
const first = run(
|
||||
{ type: 'connecting' },
|
||||
hello(1),
|
||||
roster(2, [
|
||||
{ id: 2, name: 'Ann', role: 'player', colour: '#f00', connected: true },
|
||||
{ id: 1, name: 'GM', role: 'gm', colour: '#0f0', connected: true },
|
||||
]),
|
||||
)
|
||||
expect(first.connection.phase).toBe('live')
|
||||
expect(first.session.role).toBe('player')
|
||||
expect(first.session.me).toEqual({ id: 2, name: 'Ann' })
|
||||
expect(first.session.scene?.name).toBe('Cellar')
|
||||
expect(rosterOf(first)).toHaveLength(2)
|
||||
|
||||
// Reconnect: the server sends hello first, then the resync. Nothing from the old connection
|
||||
// may survive, otherwise a token that left the view would stay on screen.
|
||||
const second = reduce(first, hello(9, { role: 'gm', me: { id: 1, name: 'GM' }, scene: scene('Attic') }))
|
||||
expect(rosterOf(second)).toEqual([])
|
||||
expect(second.session.role).toBe('gm')
|
||||
expect(second.session.scene?.name).toBe('Attic')
|
||||
expect(second.connection.phase).toBe('live')
|
||||
expect(second.connection.frames).toBe(3)
|
||||
expect(second.connection.lastN).toBe(9)
|
||||
})
|
||||
|
||||
it('stays on the other slices while a hello resets them', () => {
|
||||
const state = run(
|
||||
{ type: 'connecting' },
|
||||
hello(1),
|
||||
roster(2, [{ id: 2, name: 'Ann', role: 'player', colour: '#f00', connected: true }]),
|
||||
hello(3),
|
||||
)
|
||||
expect(Object.keys(state.slices).sort()).toEqual(SLICES.map(slice => slice.name).sort())
|
||||
expect(rosterOf(state)).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('no data before join', () => {
|
||||
it('connecting clears session and slices, so a stranger is shown nothing', () => {
|
||||
const live = run(
|
||||
{ type: 'connecting' },
|
||||
hello(1),
|
||||
roster(2, [{ id: 1, name: 'GM', role: 'gm', colour: '#0f0', connected: true }]),
|
||||
)
|
||||
const cleared = reduce(live, { type: 'connecting' })
|
||||
expect(cleared.connection.phase).toBe('connecting')
|
||||
expect(cleared.session).toEqual({ role: null, me: null, proto: null, scene: null })
|
||||
expect(rosterOf(cleared)).toEqual([])
|
||||
})
|
||||
|
||||
it('a refused upgrade (close before hello) lands on sign-in', () => {
|
||||
const state = run({ type: 'connecting' }, { type: 'close', reason: null, code: 1006 })
|
||||
expect(state.connection.phase).toBe('signin')
|
||||
expect(state.session.me).toBeNull()
|
||||
})
|
||||
|
||||
it('a failed key shows a sign-in error and no session', () => {
|
||||
const state = run({ type: 'connecting' }, { type: 'signin-failed', message: 'Key not recognised.' })
|
||||
expect(state.connection.phase).toBe('signin')
|
||||
expect(state.connection.error).toBe('Key not recognised.')
|
||||
expect(state.session.me).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('connection outcomes (6.5)', () => {
|
||||
it('proto-mismatch asks for a reload', () => {
|
||||
const state = run(
|
||||
{ type: 'connecting' },
|
||||
hello(1),
|
||||
frame({ t: 'closing', n: 2, reason: 'proto-mismatch', code: 4003 }),
|
||||
{ type: 'close', reason: 'proto-mismatch', code: 4003 },
|
||||
)
|
||||
expect(state.connection.phase).toBe('reload')
|
||||
})
|
||||
|
||||
it('revoked returns to sign-in and clears the view', () => {
|
||||
const state = run(
|
||||
{ type: 'connecting' },
|
||||
hello(1),
|
||||
roster(2, [{ id: 2, name: 'Ann', role: 'player', colour: '#f00', connected: true }]),
|
||||
frame({ t: 'closing', n: 3, reason: 'revoked', code: 4001 }),
|
||||
{ type: 'close', reason: 'revoked', code: 4001 },
|
||||
)
|
||||
expect(state.connection.phase).toBe('signin')
|
||||
expect(state.connection.notice).toMatch(/session has ended/i)
|
||||
expect(state.session.me).toBeNull()
|
||||
expect(rosterOf(state)).toEqual([])
|
||||
})
|
||||
|
||||
it('evicted goes offline but keeps the tab usable', () => {
|
||||
const state = run(
|
||||
{ type: 'connecting' },
|
||||
hello(1),
|
||||
frame({ t: 'closing', n: 2, reason: 'evicted', code: 4002 }),
|
||||
)
|
||||
expect(state.connection.phase).toBe('offline')
|
||||
})
|
||||
|
||||
it('a transport close while live is offline, not a silent sign-out', () => {
|
||||
const state = run({ type: 'connecting' }, hello(1), { type: 'close', reason: null, code: 1006 })
|
||||
expect(state.connection.phase).toBe('offline')
|
||||
})
|
||||
})
|
||||
|
||||
describe('frames', () => {
|
||||
it('ignores an unknown server message type (6.2) without touching the view', () => {
|
||||
const state = run(
|
||||
{ type: 'connecting' },
|
||||
hello(1),
|
||||
frame({ t: 'future_frame', n: 2, payload: 42 }),
|
||||
)
|
||||
expect(state.connection.phase).toBe('live')
|
||||
expect(state.connection.lastN).toBe(2)
|
||||
})
|
||||
|
||||
it('a roster frame replaces the list instead of merging', () => {
|
||||
const a: RosterEntry = { id: 1, name: 'GM', role: 'gm', colour: '#0f0', connected: true }
|
||||
const b: RosterEntry = { id: 2, name: 'Ann', role: 'player', colour: '#f00', connected: true }
|
||||
const state = run({ type: 'connecting' }, hello(1), roster(2, [a, b]), roster(3, [b]))
|
||||
expect(rosterOf(state)).toEqual([b])
|
||||
})
|
||||
|
||||
it('keeps the session intact when a non-hello frame arrives', () => {
|
||||
const state = run({ type: 'connecting' }, hello(1), frame({ t: 'error', n: 2, code: 'malformed' }))
|
||||
expect(state.session.me).toEqual({ id: 2, name: 'Ann' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('registry', () => {
|
||||
it('registers the roster slice without an import list', () => {
|
||||
expect(SLICES.map(slice => slice.name)).toContain('roster')
|
||||
})
|
||||
|
||||
it('rotates every server frame through the slice too', () => {
|
||||
const state = run({ type: 'connecting' }, hello(1))
|
||||
const withRoster = reduce(state, roster(2, [{ id: 1, name: 'GM', role: 'gm', colour: '#0f0', connected: true }]))
|
||||
expect(rosterOf(withRoster)).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { ProtocolClient } from '../src/ws.ts'
|
||||
import type { ClientEvent, SocketLike } from '../src/ws.ts'
|
||||
|
||||
class FakeSocket implements SocketLike {
|
||||
onopen: (() => void) | null = null
|
||||
onmessage: ((event: { data: unknown }) => void) | null = null
|
||||
onclose: ((event: { code: number; reason: string }) => void) | null = null
|
||||
onerror: ((event: unknown) => void) | null = null
|
||||
sent: string[] = []
|
||||
closed = false
|
||||
|
||||
send(data: string): void {
|
||||
if (this.closed) throw new Error('socket is closed')
|
||||
this.sent.push(data)
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.closed = true
|
||||
}
|
||||
|
||||
open(): void {
|
||||
this.onopen?.()
|
||||
}
|
||||
|
||||
receive(body: unknown): void {
|
||||
this.onmessage?.({ data: typeof body === 'string' ? body : JSON.stringify(body) })
|
||||
}
|
||||
|
||||
serverClose(code = 1005, reason = ''): void {
|
||||
this.closed = true
|
||||
this.onclose?.({ code, reason })
|
||||
}
|
||||
}
|
||||
|
||||
function connect(): {
|
||||
client: ProtocolClient
|
||||
socket: FakeSocket
|
||||
events: ClientEvent[]
|
||||
} {
|
||||
const socket = new FakeSocket()
|
||||
const events: ClientEvent[] = []
|
||||
const client = new ProtocolClient({
|
||||
url: 'wss://test/ws?proto=2',
|
||||
createSocket: () => socket,
|
||||
onEvent: event => events.push(event),
|
||||
})
|
||||
client.connect()
|
||||
socket.open()
|
||||
return { client, socket, events }
|
||||
}
|
||||
|
||||
describe('protocol client', () => {
|
||||
it('parses text frames and ignores binary or unreadable ones', () => {
|
||||
const { socket, events } = connect()
|
||||
socket.receive({ t: 'hello', n: 1, proto: 2, role: 'player', me: { id: 1, name: null } })
|
||||
socket.receive('not json')
|
||||
socket.onmessage?.({ data: new Uint8Array([1, 2]) })
|
||||
expect(events.filter(event => event.type === 'frame')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('correlates one ack per reqId and ignores an unknown ack', async () => {
|
||||
const { client, socket } = connect()
|
||||
const first = client.send('conn.ping', { ts: 11 })
|
||||
const second = client.send('conn.ping', { ts: 12 })
|
||||
expect(client.pendingCount).toBe(2)
|
||||
const sent = socket.sent.map(raw => JSON.parse(raw) as { t: string; reqId: number; ts: number })
|
||||
expect(sent.map(intent => intent.t)).toEqual(['conn.ping', 'conn.ping'])
|
||||
expect(sent[0]?.reqId).toBe(1)
|
||||
expect(sent[1]?.reqId).toBe(2)
|
||||
|
||||
socket.receive({ t: 'ack', n: 1, reqId: 2, ok: true, ts: 12 })
|
||||
socket.receive({ t: 'ack', n: 2, reqId: 99, ok: true })
|
||||
expect(client.pendingCount).toBe(1)
|
||||
await expect(second).resolves.toMatchObject({ reqId: 2, ok: true })
|
||||
|
||||
socket.receive({ t: 'ack', n: 3, reqId: 1, ok: false, code: 'invalid' })
|
||||
await expect(first).resolves.toMatchObject({ reqId: 1, ok: false, code: 'invalid' })
|
||||
expect(client.pendingCount).toBe(0)
|
||||
})
|
||||
|
||||
it('keeps pending requests across a hello on a live connection (6.3)', async () => {
|
||||
const { client, socket } = connect()
|
||||
const pending = client.send('player.setname', { name: 'Ann' })
|
||||
socket.receive({ t: 'hello', n: 1, proto: 2, role: 'player', me: { id: 1, name: 'Ann' } })
|
||||
expect(client.pendingCount).toBe(1)
|
||||
socket.receive({ t: 'ack', n: 2, reqId: 1, ok: true })
|
||||
await expect(pending).resolves.toMatchObject({ ok: true })
|
||||
})
|
||||
|
||||
it('drops pending requests with the connection (6.3)', async () => {
|
||||
const { client, socket } = connect()
|
||||
const pending = client.send('conn.ping', { ts: 1 })
|
||||
socket.serverClose(1006)
|
||||
expect(client.pendingCount).toBe(0)
|
||||
await expect(pending).rejects.toThrow(/closed/)
|
||||
})
|
||||
|
||||
it('reads a server close reason from the last closing frame (6.5, FIXED #18)', () => {
|
||||
const { socket, events } = connect()
|
||||
socket.receive({ t: 'closing', n: 2, reason: 'revoked', code: 4001 })
|
||||
socket.serverClose(1005)
|
||||
expect(events.at(-1)).toEqual({ type: 'close', reason: 'revoked', code: 4001 })
|
||||
})
|
||||
|
||||
it('treats a close without a closing frame as a transport failure', () => {
|
||||
const { socket, events } = connect()
|
||||
socket.serverClose(1006)
|
||||
expect(events.at(-1)).toEqual({ type: 'close', reason: null, code: 1006 })
|
||||
})
|
||||
|
||||
it('does not reconnect to a terminal outcome (single connect)', () => {
|
||||
const socket = new FakeSocket()
|
||||
const sockets: FakeSocket[] = [socket]
|
||||
const client = new ProtocolClient({
|
||||
url: 'wss://test/ws?proto=2',
|
||||
createSocket: () => socket,
|
||||
onEvent: () => {},
|
||||
})
|
||||
client.connect()
|
||||
socket.open()
|
||||
socket.receive({ t: 'closing', n: 1, reason: 'proto-mismatch', code: 4003 })
|
||||
socket.serverClose(1005)
|
||||
client.connect() // a no-op once closed
|
||||
expect(sockets).toHaveLength(1)
|
||||
expect(client.state).toBe('closed')
|
||||
})
|
||||
|
||||
it('ignores a frame that arrives after the client closed the socket', () => {
|
||||
const { client, socket, events } = connect()
|
||||
client.close()
|
||||
const before = events.length
|
||||
socket.receive({ t: 'hello', n: 1, proto: 2, role: 'player', me: { id: 1, name: null } })
|
||||
expect(events).toHaveLength(before)
|
||||
})
|
||||
|
||||
it('refuses to send before the socket opens', async () => {
|
||||
const socket = new FakeSocket()
|
||||
const client = new ProtocolClient({
|
||||
url: 'wss://test/ws?proto=2',
|
||||
createSocket: () => socket,
|
||||
onEvent: () => {},
|
||||
})
|
||||
client.connect()
|
||||
await expect(client.send('conn.ping', { ts: 1 })).rejects.toThrow(/not connected/)
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user