Phase 18: internet realtime collaboration (GM-authoritative) + server

- Shared Zod wire protocol (src/lib/sync/messages.ts): hosted/joined/snapshot/
  mapImage/error; player-safe projections only (enemy HP masked on the GM before
  broadcast via src/lib/combat/playerProjection.ts).
- wsSync adapter (src/lib/sync/wsSync.ts) behind the existing SyncAdapter seam:
  GM hostSession + debounced snapshot broadcast (useSessionBroadcaster), player
  joinSession into an ephemeral playerSessionStore, exponential-backoff reconnect
  with seamless room resume (GM secret). localSync remains the offline default.
- buildSnapshot (src/lib/sync/snapshot.ts) reuses the same projection as the local
  /play view, guaranteeing parity. Player view refactored into shared PlayerBoards;
  /play?room=CODE = networked read-only mode.
- SessionControl in the header: Host (optional password) → shareable room code/link.
- Server (server/): Fastify + @fastify/websocket + @fastify/static, in-memory
  GM-authoritative rooms (crypto room id/secret hashed, optional join password,
  TTL sweep, players strictly read-only), origin allowlist, per-frame size cap +
  rate limit, Zod validation. esbuild bundle (server/build.mjs), tsconfig.server.json.
- Dockerfile (multi-stage) + deploy/ttrpg.compose.yml (own project on external
  'proxy' net, Traefik labels for ttrpg.briggen.dev, non-root, no-new-privileges).
  CSP connect-src now allows same-origin wss:.

Tests: protocol round-trip, room hub (auth/password/resume/TTL/read-only), enemy
masking, Fastify+ws integration (host→join→snapshot, player push rejected), and a
two-context Playwright realtime spec (separate config) — GM hosts, player device
sees live combat with masked enemy HP.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-08 10:49:31 +02:00
parent fb459ad92c
commit a8cb7d65f4
31 changed files with 1304 additions and 118 deletions
+82
View File
@@ -0,0 +1,82 @@
import { describe, it, expect } from 'vitest';
import { RoomHub, type Sender } from './rooms';
import type { ServerMessage, Snapshot } from '@/lib/sync/messages';
function fake(): Sender & { msgs: ServerMessage[] } {
const msgs: ServerMessage[] = [];
return { msgs, send: (m) => msgs.push(m) };
}
const snap: Snapshot = { campaignName: 'C', calendarDay: null, party: [], encounter: null, map: null, mapImageId: null };
function lastOf<T extends ServerMessage['t']>(s: ReturnType<typeof fake>, t: T): Extract<ServerMessage, { t: T }> | undefined {
return [...s.msgs].reverse().find((m): m is Extract<ServerMessage, { t: T }> => m.t === t);
}
describe('RoomHub', () => {
it('hosts a room and lets a player join + receive snapshots; GM is authoritative', () => {
const hub = new RoomHub();
const gm = fake();
hub.host(gm);
const hosted = lastOf(gm, 'hosted')!;
expect(hosted).toBeTruthy();
const code = (hosted as Extract<ServerMessage, { t: 'hosted' }>).joinCode;
const secret = (hosted as Extract<ServerMessage, { t: 'hosted' }>).gmSecret;
const player = fake();
hub.join(player, code);
expect(lastOf(player, 'joined')).toBeTruthy();
hub.state(gm, secret, snap);
expect(lastOf(player, 'snapshot')).toMatchObject({ snapshot: { campaignName: 'C' } });
});
it('rejects state from a non-GM and from a wrong secret', () => {
const hub = new RoomHub();
const gm = fake(); hub.host(gm);
const player = fake();
const code = (lastOf(gm, 'hosted') as Extract<ServerMessage, { t: 'hosted' }>).joinCode;
hub.join(player, code);
hub.state(player, 'whatever', snap);
expect(lastOf(player, 'error')?.code).toBe('forbidden');
hub.state(gm, 'wrong-secret', snap);
expect(lastOf(gm, 'error')?.code).toBe('forbidden');
});
it('enforces an optional join password', () => {
const hub = new RoomHub();
const gm = fake(); hub.host(gm, 'sesame');
const code = (lastOf(gm, 'hosted') as Extract<ServerMessage, { t: 'hosted' }>).joinCode;
const p1 = fake(); hub.join(p1, code, 'nope');
expect(lastOf(p1, 'error')?.code).toBe('bad-password');
const p2 = fake(); hub.join(p2, code, 'sesame');
expect(lastOf(p2, 'joined')).toBeTruthy();
});
it('reports no-room for a bad code, and resumes a room by GM secret', () => {
const hub = new RoomHub();
const stray = fake(); hub.join(stray, 'ZZZZZZ');
expect(lastOf(stray, 'error')?.code).toBe('no-room');
const gm = fake(); hub.host(gm);
const hosted = lastOf(gm, 'hosted') as Extract<ServerMessage, { t: 'hosted' }>;
const gm2 = fake(); hub.host(gm2, undefined, hosted.gmSecret);
const resumed = lastOf(gm2, 'hosted') as Extract<ServerMessage, { t: 'hosted' }>;
expect(resumed.roomId).toBe(hosted.roomId);
expect(hub.roomCount()).toBe(1);
});
it('caches + serves images and evicts idle rooms on sweep', () => {
let t = 0;
const hub = new RoomHub(() => t);
const gm = fake(); hub.host(gm);
const hosted = lastOf(gm, 'hosted') as Extract<ServerMessage, { t: 'hosted' }>;
hub.image(gm, hosted.gmSecret, 'map1', 'data:abc');
const player = fake(); hub.join(player, hosted.joinCode);
hub.requestImage(player, 'map1');
expect(lastOf(player, 'mapImage')).toMatchObject({ id: 'map1', dataUrl: 'data:abc' });
t += 7 * 60 * 60 * 1000; // past TTL
hub.sweep();
expect(hub.roomCount()).toBe(0);
});
});