From 3ebbdf6ffa16f751c82e3bd2e74294f4fe843155 Mon Sep 17 00:00:00 2001 From: Joel Klinghed Date: Fri, 13 Nov 2026 00:04:16 +0100 Subject: Phase 2: networking, sessions, secrets over WebSocket (M2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Server owns all state; browsers send input only. New server/lib/net/ layer on top of the Phase 1 engine: - protocol.dart: JSON wire protocol (v1) — hello/welcome handshake, claim, cmd, undo/redo, ping/pong, update, seats, error - sessions.dart: 32-hex session ids carried in the x-haven-session cookie; role derived from seat ownership (player vs spectator); resolve() adopts a well-formed cookie id so a seat survives restarts - seat_store.dart: seat table persisted to saves/seats.json beside the state snapshot; restored on startup - visibility.dart: per-connection state serialization; the initiative rule masks every non-owned character's initiative to null until the round is drawn — the server never sends a secret to a non-owner - game_server.dart: the command execution path (role check → game-rule guard → registry build → execute → per-connection update broadcast); seat assign/claim/release with seats broadcasts; heartbeat sweep closes dead connections and releases their seats - ws_upgrade.dart: custom WS upgrade handler so the server reads the session cookie (shelf_web_socket hides the Request); app.dart wires shelf + static SPA; bin/main.dart starts the server - game_state.dart: onAction setter so the network layer installs its broadcast hook; save_store.dart / seat_store.dart writes made synchronous (writeAsStringSync) so a snapshot/seat table is on disk when write() returns — the kill -9 persistence test exposed the async write race Server-side guards replace the reference app's 300 ms draw-button lockout: sequential execution makes a duplicate draw deterministically lose, with a clear error to the sender only. The session that adds a character owns it and becomes a player; spectators may only claim/ addCharacter. Command index resets to -1 on restart (the snapshot carries state, not undo history). Tests: 34 new network tests over a real WS stack on an ephemeral port (sessions 9, visibility 5, app 9, multiplayer 9, persistence 2) — secret initiative never reaches non-owners, reveal on draw, reconnect resync, rejected duplicate draw, claim/lose/re-claim seats, undo/redo broadcast to every screen, dead-connection cleanup, snapshot + seat file restored across a restart. Replaces the Phase 0 smoke test. dart analyze warning-free; dart test 591/591; scripts/ci.sh green. --- server/bin/main.dart | 19 +- server/lib/core/save_store.dart | 4 +- server/lib/core/state/game_state.dart | 9 +- server/lib/net/app.dart | 146 +++------ server/lib/net/game_server.dart | 567 ++++++++++++++++++++++++++++++++++ server/lib/net/protocol.dart | 66 +++- server/lib/net/seat_store.dart | 79 +++++ server/lib/net/sessions.dart | 134 ++++++++ server/lib/net/visibility.dart | 116 +++++++ server/lib/net/ws_upgrade.dart | 138 +++++++++ server/test/net/app_test.dart | 140 +++++++++ server/test/net/multiplayer_test.dart | 461 +++++++++++++++++++++++++++ server/test/net/persistence_test.dart | 224 ++++++++++++++ server/test/net/sessions_test.dart | 107 +++++++ server/test/net/visibility_test.dart | 143 +++++++++ server/test/net/ws_test_helpers.dart | 246 +++++++++++++++ server/test/smoke_test.dart | 115 ------- 17 files changed, 2488 insertions(+), 226 deletions(-) create mode 100644 server/lib/net/game_server.dart create mode 100644 server/lib/net/seat_store.dart create mode 100644 server/lib/net/sessions.dart create mode 100644 server/lib/net/visibility.dart create mode 100644 server/lib/net/ws_upgrade.dart create mode 100644 server/test/net/app_test.dart create mode 100644 server/test/net/multiplayer_test.dart create mode 100644 server/test/net/persistence_test.dart create mode 100644 server/test/net/sessions_test.dart create mode 100644 server/test/net/visibility_test.dart create mode 100644 server/test/net/ws_test_helpers.dart delete mode 100644 server/test/smoke_test.dart (limited to 'server') diff --git a/server/bin/main.dart b/server/bin/main.dart index ef0c7c5..7571960 100644 --- a/server/bin/main.dart +++ b/server/bin/main.dart @@ -13,6 +13,9 @@ import 'package:x_haven_server/core/save_store.dart'; import 'package:x_haven_server/core/service_locator.dart'; import 'package:x_haven_server/core/state/game_state.dart'; import 'package:x_haven_server/net/app.dart'; +import 'package:x_haven_server/net/game_server.dart'; +import 'package:x_haven_server/net/seat_store.dart'; +import 'package:x_haven_server/net/sessions.dart'; final _log = Logger('main'); @@ -23,11 +26,21 @@ Future main(List args) async { 4567; final staticDir = _parseString(args, 'static-dir') ?? '../web/dist'; - // Phase 1: boot the game engine (single save in saves/, game data from - // assets/data/). The WebSocket layer starts serving real state in Phase 2. + // Boot the game engine (single save in saves/, game data from + // assets/data/), then attach the network layer: the WebSocket game + // server, with seat ownership persisted next to the game state. await _bootGameCore(); + final gameServer = GameServer( + gameState: getIt(), + sessions: SessionManager(), + seatStore: FileSeatStore('saves'), + ); - final server = await startServer(port: port, staticDir: staticDir); + final server = await startServer( + port: port, + staticDir: staticDir, + gameServer: gameServer, + ); stdout ..writeln('X-Haven server listening on http://localhost:${server.port}') ..writeln('WebSocket endpoint: ws://localhost:${server.port}/ws'); diff --git a/server/lib/core/save_store.dart b/server/lib/core/save_store.dart index 5ffdc36..25b4136 100644 --- a/server/lib/core/save_store.dart +++ b/server/lib/core/save_store.dart @@ -46,7 +46,9 @@ class FileSaveStore implements SaveStore { void write(String data) { final dir = _file.parent; if (!dir.existsSync()) dir.createSync(recursive: true); - _file.writeAsString(data, flush: true); + // Synchronous write: "save on every action" must be on disk when + // [write] returns, or a crash in between loses the snapshot. + _file.writeAsStringSync(data, flush: true); } @override diff --git a/server/lib/core/state/game_state.dart b/server/lib/core/state/game_state.dart index a6884cc..23666fe 100644 --- a/server/lib/core/state/game_state.dart +++ b/server/lib/core/state/game_state.dart @@ -152,10 +152,17 @@ class GameState { List get commandDescriptions => _actionHandler.commandDescriptions; List get gameSaveStates => _actionHandler.gameSaveStates; - /// The Phase 2 broadcast hook is reachable through the action handler. + /// The Phase 2 broadcast hook, reachable through the action handler: set + /// by the network layer, null in headless tests. void Function(int index, String description, String eventJson)? get onAction => _actionHandler.onAction; + set onAction( + void Function(int index, String description, String eventJson)? value, + ) { + _actionHandler.onAction = value; + } + // Minimal observer hook — replaces the reference app's ChangeNotifier // notifications. The network layer (Phase 2) subscribes; unused in Phase 1. final List _listeners = []; diff --git a/server/lib/net/app.dart b/server/lib/net/app.dart index 4d36f15..21a1b81 100644 --- a/server/lib/net/app.dart +++ b/server/lib/net/app.dart @@ -1,16 +1,9 @@ -/// The X-Haven web server: static file serving for the built SPA plus the -/// game WebSocket endpoint at `/ws`. -/// -/// Phase 0 scope: serve the SPA (or a stub page), answer the `hello` -/// handshake with `welcome`, ping/pong, and error responses for malformed -/// input. Game state, sessions, seats and secret gating land in later phases -/// (see PLAN.md). +/// The X-Haven web server: static file serving for the built SPA, the +/// session endpoint, and the game WebSocket endpoint at `/ws`. library; -import 'dart:async'; import 'dart:convert'; import 'dart:io'; -import 'dart:math'; import 'package:logging/logging.dart'; import 'package:path/path.dart' as p; @@ -18,111 +11,64 @@ import 'package:shelf/shelf.dart'; import 'package:shelf/shelf_io.dart' as shelf_io; import 'package:shelf_router/shelf_router.dart'; import 'package:shelf_static/shelf_static.dart'; -import 'package:shelf_web_socket/shelf_web_socket.dart'; -import 'package:web_socket_channel/web_socket_channel.dart'; -import 'protocol.dart'; +import 'game_server.dart'; +import 'sessions.dart'; +import 'ws_upgrade.dart'; final _log = Logger('server'); /// Builds the HTTP handler for the game server. -Handler createHandler({required String staticDir}) { +Handler createHandler({required String staticDir, required GameServer gameServer}) { final router = Router(); - router.get('/ws', webSocketHandler(_handleConnection)); - router.get( - '/healthz', - (Request request) => Response.ok( - jsonEncode({'status': 'ok'}), - headers: {'content-type': 'application/json; charset=utf-8'}, - ), - ); + router.get('/ws', createWebSocketUpgradeHandler(gameServer)); + router.get('/healthz', (Request request) => Response.ok( + jsonEncode({'status': 'ok'}), + headers: {'content-type': 'application/json; charset=utf-8'}, + )); + // Session endpoint (PLAN.md section 3.3): returns the caller's persistent + // session id, setting the `x-haven-session` cookie when the caller has + // none yet. Browsers then carry the cookie on every same-origin request, + // including the `/ws` upgrade — so a player keeps their seat across page + // refreshes. + router.get('/session', (Request request) { + final existing = _validSessionIdFrom(request); + final Map headers = { + 'content-type': 'application/json; charset=utf-8', + }; + if (existing != null) { + return Response.ok(jsonEncode({'session': existing}), headers: headers); + } + final id = SessionManager.newSessionId(); + headers['set-cookie'] = + '$sessionCookieName=$id; Path=/; HttpOnly; SameSite=Lax'; + return Response.ok(jsonEncode({'session': id}), headers: headers); + }); router.mount('/', _createStaticHandler(staticDir)); return const Pipeline().addMiddleware(_logRequests()).addHandler(router); } /// Starts the server on [port] (0 for an ephemeral port). -Future startServer({required int port, required String staticDir}) { - return shelf_io.serve(createHandler(staticDir: staticDir), '0.0.0.0', port); -} - -void _handleConnection(WebSocketChannel channel, Object? encodable) { - final session = _newSessionId(); - channel.stream.listen( - (Object? raw) { - final String? text = _coerceText(raw); - if (text == null) { - _send( - channel, - Protocol.errorMessage( - Protocol.errBadRequest, - 'expected a UTF-8 JSON message', - ), - ); - return; - } - final Map? message = _decodeMessage(text); - if (message == null) { - _send( - channel, - Protocol.errorMessage(Protocol.errBadRequest, 'malformed JSON'), - ); - return; - } - final type = message['t']; - if (type == Protocol.hello) { - _send( - channel, - Protocol.welcomeMessage( - session: session, - role: Protocol.roleSpectator, - index: 0, - state: const {}, - seats: const {}, - ), - ); - } else if (type == Protocol.ping) { - _send(channel, Protocol.pongMessage()); - } else { - _send( - channel, - Protocol.errorMessage( - Protocol.errUnknownMessage, - 'unknown message type: $type', - ), - ); - } - }, - onDone: () { - _log.info('session $session closed'); - }, - onError: (Object error) { - _log.warning('session $session connection error: $error'); - }, - ); -} - -String? _coerceText(Object? raw) { - if (raw is String) return raw; - if (raw is List) return utf8.decode(raw, allowMalformed: true); - return null; +Future startServer({ + required int port, + required String staticDir, + required GameServer gameServer, +}) { + return shelf_io.serve(createHandler(staticDir: staticDir, gameServer: gameServer), '0.0.0.0', port); } -Map? _decodeMessage(String text) { - try { - final dynamic decoded = jsonDecode(text); - return decoded is Map ? decoded : null; - } catch (_) { - return null; +/// The session id from [request]'s cookie, when well-formed. +String? _validSessionIdFrom(Request request) { + final cookie = request.headers['Cookie']; + if (cookie == null) return null; + for (final part in cookie.split(';')) { + final trimmed = part.trim(); + if (trimmed.startsWith('$sessionCookieName=')) { + final value = trimmed.substring(sessionCookieName.length + 1).trim(); + if (SessionManager.isKnownFormat(value)) return value; + } } -} - -void _send(WebSocketChannel channel, Map message) { - channel.sink.add(jsonEncode(message)); -} - -String _newSessionId() { - final random = Random.secure(); - return List.generate(16, (_) => random.nextInt(16).toRadixString(16)).join(); + return null; } Handler _createStaticHandler(String staticDir) { diff --git a/server/lib/net/game_server.dart b/server/lib/net/game_server.dart new file mode 100644 index 0000000..aa9aee3 --- /dev/null +++ b/server/lib/net/game_server.dart @@ -0,0 +1,567 @@ +/// The server-side game: connections, sessions, secrets and the command +/// execution path (PLAN.md sections 3.3–3.6). +/// +/// One [GameServer] serves one game (the reference app's deployment model). +/// It is the conceptual successor of the reference app's `Server extends +/// GameServer`: same concepts — monotonic command index, full-state push on +/// every action, full resync on reconnect, ping — native to WebSocket, and +/// with the server as the only executor (clients send input only). +library; + +import 'dart:async'; +import 'dart:convert'; + +import 'package:collection/collection.dart'; +import 'package:logging/logging.dart'; +import 'package:web_socket_channel/web_socket_channel.dart'; + +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/command_registry.dart'; +import 'package:x_haven_server/core/enums.dart'; +import 'package:x_haven_server/core/game_methods.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; + +import 'protocol.dart'; +import 'seat_store.dart'; +import 'sessions.dart'; +import 'visibility.dart'; + +final _log = Logger('GameServer'); + +/// One live connection: the channel, its session, and activity tracking. +class _Connection { + _Connection(this.channel, this.session) : lastActivityAt = DateTime.now(); + + final WebSocketChannel channel; + final SessionRecord session; + + /// Last time anything was received on this connection (connect time + /// initially). The heartbeat sweep closes connections quiet longer than + /// the server's dead timeout. + DateTime lastActivityAt; + + /// Whether the `hello` handshake completed. + bool handshaken = false; + + /// Whether this connection has been detached (idempotent-cleanup guard). + bool closed = false; + + void send(Map message) => + channel.sink.add(jsonEncode(message)); +} + +/// The game server bound to one [GameState]. +class GameServer { + GameServer({ + required GameState gameState, + required SessionManager sessions, + required SeatStore seatStore, + Duration heartbeatInterval = const Duration(seconds: 20), + Duration deadTimeout = const Duration(seconds: 90), + }) : _gameState = gameState, + _sessions = sessions, + _seatStore = seatStore, + _deadTimeout = deadTimeout { + // The action handler's broadcast hook: after every action/undo/redo the + // index, description and event arrive here; the per-connection state + // push happens in [_onAction]. + gameState.onAction = _onAction; + _restoreSeats(); + _heartbeat = Timer.periodic(heartbeatInterval, (_) => _sweepDeadConnections()); + } + + final GameState _gameState; + final SessionManager _sessions; + final SeatStore _seatStore; + final Duration _deadTimeout; + final Map> _connections = {}; + late final Timer _heartbeat; + + SessionManager get sessions => _sessions; + GameState get gameState => _gameState; + + /// Number of live connections (diagnostics/tests). + int get connectionCount => + _connections.values.fold(0, (sum, list) => sum + list.length); + + /// Attaches a live WebSocket channel. + /// + /// [cookieSessionId] comes from the `x-haven-session` cookie (or the + /// `?session=` query parameter) of the upgrade request; null (or unknown) + /// mints a new session. + void attach(WebSocketChannel channel, {String? cookieSessionId}) { + final session = _sessions.resolve(cookieSessionId); + final connection = _Connection(channel, session); + _connections.putIfAbsent(session.id, () => []).add(connection); + _log.info( + 'session ${session.id} connected ' + '($connectionCount connection(s) live)', + ); + + channel.stream.listen( + (Object? raw) { + connection.lastActivityAt = DateTime.now(); + _onMessage(connection, raw); + }, + onDone: () => _detach(connection), + onError: (Object error) { + _log.warning('session ${session.id} connection error: $error'); + _detach(connection); + }, + ); + } + + /// Stops the heartbeat sweep. Does not close connections — the caller + /// closes them (e.g. when the HTTP server shuts down, or to simulate a + /// crash in tests). + void dispose() { + _heartbeat.cancel(); + } + + // --- connection lifecycle ------------------------------------------------- + + void _detach(_Connection connection) { + if (connection.closed) return; + connection.closed = true; + final list = _connections[connection.session.id]; + list?.remove(connection); + if (list != null && list.isEmpty) { + _connections.remove(connection.session.id); + _onSessionDisconnected(connection.session); + } + } + + /// The session's last connection is gone: its characters become unclaimed + /// (PLAN.md section 3.3), the seat table is persisted, and the `seats` + /// broadcast goes out so every screen can update its inputs. + void _onSessionDisconnected(SessionRecord session) { + _log.info('session ${session.id} left'); + final released = _sessions.release(session.id); + if (released.isNotEmpty) { + _log.info('session ${session.id} released seats: $released'); + _persistSeats(); + } + _broadcastSeats(); + } + + /// Closes connections quiet longer than [_deadTimeout] (half-open + /// connections the OS never reported). The sweep is the safety net; normal + /// disconnects are handled by the socket's done/error events. + void _sweepDeadConnections() { + final now = DateTime.now(); + for (final connection in _activeConnections().toList()) { + final quietFor = now.difference(connection.lastActivityAt); + if (quietFor > _deadTimeout) { + _log.info( + 'closing dead connection for session ${connection.session.id} ' + '(no activity for ${quietFor.inSeconds}s)', + ); + unawaited(connection.channel.sink.close()); + // onDone fires → _detach runs the seat release + broadcast. + } + } + } + + List<_Connection> _activeConnections() { + final result = <_Connection>[]; + for (final list in _connections.values) { + result.addAll(list); + } + return result; + } + + // --- message dispatch ----------------------------------------------------- + + void _onMessage(_Connection connection, Object? raw) { + final String? text = _coerceText(raw); + if (text == null) { + connection.send( + Protocol.errorMessage( + Protocol.errBadRequest, + 'expected a UTF-8 JSON message', + ), + ); + return; + } + final Map? message = _decodeMessage(text); + if (message == null) { + connection.send( + Protocol.errorMessage(Protocol.errBadRequest, 'malformed JSON'), + ); + return; + } + final type = message['t']; + switch (type) { + case Protocol.hello: + _handleHello(connection, message); + case Protocol.ping: + // Allowed before the handshake — a keepalive is harmless. + connection.send(Protocol.pongMessage()); + case Protocol.claim: + _handleClaim(connection, message); + case Protocol.cmd: + _handleCmd(connection, message); + case Protocol.undo: + _handleUndoRedo(connection, undo: true); + case Protocol.redo: + _handleUndoRedo(connection, undo: false); + default: + connection.send( + Protocol.errorMessage( + Protocol.errUnknownMessage, + 'unknown message type: $type', + ), + ); + } + } + + String? _coerceText(Object? raw) { + if (raw is String) return raw; + if (raw is List) return utf8.decode(raw, allowMalformed: true); + return null; + } + + Map? _decodeMessage(String text) { + try { + final dynamic decoded = jsonDecode(text); + return decoded is Map ? decoded : null; + } catch (_) { + return null; + } + } + + void _notHandshaken(_Connection connection) { + connection.send( + Protocol.errorMessage(Protocol.errBadRequest, 'send hello first'), + ); + } + + /// The handshake: checks the protocol version, then answers with a full + /// `welcome` (current state, role, seats). Re-sending `hello` re-answers + /// with a fresh `welcome` — the client's resync tool. + void _handleHello(_Connection connection, Map message) { + final version = message['v']; + if (version is! int || version != Protocol.version) { + connection.send( + Protocol.errorMessage( + Protocol.errProtocol, + 'protocol version mismatch: client $version, ' + 'server ${Protocol.version}. Please update.', + ), + ); + unawaited(connection.channel.sink.close()); + return; + } + connection.handshaken = true; + connection.send(_welcomeFor(connection)); + } + + Map _welcomeFor(_Connection connection) { + final session = connection.session; + final index = _gameState.commandIndex; + final descriptions = _gameState.commandDescriptions; + final String? description = + index >= 0 && index < descriptions.length + ? descriptions[index] + : null; + return Protocol.welcomeMessage( + session: session.id, + role: session.role, + index: index, + description: description, + event: null, + state: _serializeFor(connection), + seats: _sessions.seatsForState(_gameState), + ); + } + + // --- claims --------------------------------------------------------------- + + /// `{t: claim, characterId}` — any session may claim an unclaimed + /// character; that is also how a session becomes a player. + void _handleClaim(_Connection connection, Map message) { + if (!connection.handshaken) { + _notHandshaken(connection); + return; + } + final characterId = message['characterId']; + if (characterId is! String || characterId.isEmpty) { + connection.send( + Protocol.errorMessage( + Protocol.errBadRequest, + 'claim requires a non-empty "characterId" string', + ), + ); + return; + } + final character = _gameState.currentList.firstWhereOrNull( + (item) => item is Character && item.id == characterId, + ); + if (character == null) { + connection.send( + Protocol.errorMessage( + Protocol.errRejected, + 'no character with id "$characterId" in the current list', + ), + ); + return; + } + final session = connection.session; + final owner = _sessions.ownerOf(characterId); + if (owner != null && owner.id != session.id) { + connection.send( + Protocol.errorMessage( + Protocol.errRejected, + 'character "$characterId" is already claimed', + ), + ); + return; + } + if (owner == null) { + _sessions.assign(session, characterId); + _persistSeats(); + } + _broadcastSeats(); + } + + // --- command execution path ------------------------------------------------ + + /// `{t: cmd, name, args}` — role check → game-rule guard → args + /// validation (registry) → execute → per-connection `update` broadcast + /// (via the action handler hook) → seat sync. + /// + /// A rejected command answers the sender with an `error` only — no + /// broadcast, no index change. + void _handleCmd(_Connection connection, Map message) { + if (!connection.handshaken) { + _notHandshaken(connection); + return; + } + final name = message['name']; + if (name is! String || name.isEmpty) { + connection.send( + Protocol.errorMessage( + Protocol.errBadRequest, + 'cmd requires a non-empty "name" string', + ), + ); + return; + } + final rawArgs = message['args']; + if (rawArgs != null && rawArgs is! Map) { + connection.send( + Protocol.errorMessage( + Protocol.errBadRequest, + 'cmd "args" must be an object', + ), + ); + return; + } + final args = + rawArgs is Map + ? rawArgs + : const {}; + + final session = connection.session; + // Role gate: spectators cannot run commands — except `addCharacter`, + // which is the way a session becomes a player (the session that adds a + // character owns it, PLAN.md section 3.3). + if (!session.isPlayer && name != 'addCharacter') { + connection.send( + Protocol.errorMessage( + Protocol.errForbidden, + 'spectators cannot run commands — claim a character first', + ), + ); + return; + } + + final String? guardMessage = _guard(name); + if (guardMessage != null) { + connection.send(Protocol.errorMessage(Protocol.errRejected, guardMessage)); + return; + } + + final Command command; + try { + command = buildCommand(name, args, _gameState); + } on CommandRegistryError catch (error) { + connection.send(Protocol.errorMessage(Protocol.errRejected, error.message)); + return; + } + + try { + _gameState.action(command); + } on Exception catch (error) { + _log.warning('command "$name" failed during execution: $error'); + connection.send( + Protocol.errorMessage(Protocol.errRejected, 'command "$name" failed: $error'), + ); + return; + } + + // Seat bookkeeping: a newly added character belongs to the session that + // added it. + if (name == 'addCharacter') { + final character = (command as AddCharacterCommand).character; + if (character != null) { + _sessions.assign(session, character.id); + _persistSeats(); + _broadcastSeats(); + } + } + // Other actions may have removed characters (undo, removeCharacter, + // loadSave) — prune stale seats and broadcast if anything changed. + _syncSeats(); + } + + /// The preconditions the reference app enforced in its UI (the + /// `runDrawOrNextRoundAction` gate): commands whose `execute()` would run + /// outside their round phase are rejected here. This is the server-side + /// replacement for the reference app's 300 ms draw-button lockout — + /// sequential server execution makes a second draw deterministically + /// lose, and the loser gets a clear `error`. + String? _guard(String name) { + if (name == 'draw') { + if (_gameState.roundState != RoundState.chooseInitiative) { + return 'the round has already been drawn'; + } + if (_gameState.currentList.isEmpty) { + return 'add characters before drawing'; + } + if (!GameMethods.canDraw()) { + return 'player initiative values must be set before drawing'; + } + } + if (name == 'nextRound') { + if (_gameState.roundState != RoundState.playTurns) { + return 'the round has not started yet'; + } + } + return null; + } + + void _handleUndoRedo(_Connection connection, {required bool undo}) { + if (!connection.handshaken) { + _notHandshaken(connection); + return; + } + if (!connection.session.isPlayer) { + connection.send( + Protocol.errorMessage( + Protocol.errForbidden, + 'spectators cannot undo or redo — claim a character first', + ), + ); + return; + } + if (undo) { + _gameState.undo(); + } else { + _gameState.redo(); + } + } + + // --- broadcasts ----------------------------------------------------------- + + /// The action handler's hook (set in the constructor): after every + /// action/undo/redo, push the new index + description + event plus a + /// full state snapshot serialized for each connection. + void _onAction(int index, String description, String eventJson) { + final Object? event = _decodeEvent(eventJson); + for (final connection in _activeConnections()) { + connection.send( + Protocol.updateMessage( + index: index, + description: description, + event: event, + state: _serializeFor(connection), + ), + ); + } + } + + Object? _decodeEvent(String eventJson) { + try { + return jsonDecode(eventJson); + } catch (_) { + return const {'type': 'none'}; + } + } + + Map _serializeFor(_Connection connection) => + serializeState( + _gameState, + SessionContext( + sessionId: connection.session.id, + seats: _sessions.seats(), + ), + ); + + /// Broadcasts the current seat table to every connection. + void _broadcastSeats() { + final seats = _sessions.seatsForState(_gameState); + for (final connection in _activeConnections()) { + connection.send(Protocol.seatsMessage(seats)); + } + } + + /// Prunes seats for characters no longer in the current list (undo, + /// removeCharacter, loadSave, …); persists and broadcasts when the table + /// changed. + void _syncSeats() { + final characterIds = _gameState.currentList + .whereType() + .map((c) => c.id) + .toSet(); + var changed = false; + for (final session in _sessions.all) { + final stale = session.ownedCharacters + .where((id) => !characterIds.contains(id)) + .toList(); + if (stale.isNotEmpty) { + session.ownedCharacters.removeAll(stale); + changed = true; + } + } + if (changed) { + _persistSeats(); + _broadcastSeats(); + } + } + + // --- seat persistence ------------------------------------------------------ + + void _persistSeats() { + // The store format is session id → character ids (a session may own + // several characters). + final bySession = >{}; + for (final entry in _sessions.seats().entries) { + bySession.putIfAbsent(entry.value, () => []).add(entry.key); + } + _seatStore.write(bySession); + } + + /// At startup: restore persisted seats onto the (lazily created) session + /// records, keeping only characters that are actually in the restored + /// list. + void _restoreSeats() { + final stored = _seatStore.read(); + if (stored == null || stored.isEmpty) return; + final characterIds = _gameState.currentList + .whereType() + .map((c) => c.id) + .toSet(); + for (final entry in stored.entries) { + final session = _sessions.resolveOrCreate(entry.key); + for (final characterId in entry.value) { + if (characterIds.contains(characterId)) { + session.ownedCharacters.add(characterId); + } + } + } + if (stored.isNotEmpty) { + _log.info('restored seats for ${stored.length} session(s)'); + } + } +} diff --git a/server/lib/net/protocol.dart b/server/lib/net/protocol.dart index 54328fc..c3030e1 100644 --- a/server/lib/net/protocol.dart +++ b/server/lib/net/protocol.dart @@ -1,12 +1,10 @@ /// JSON wire protocol for X-Haven, shared by the server, its tests and (via /// mirrored types) the web client. /// -/// See PLAN.md section 3.5 for the protocol design. Phase 0 implements the -/// handshake (hello/welcome/ping/pong/error); the rest of the message types -/// are declared here and added to in later phases. +/// See PLAN.md section 3.5 for the protocol design. library; -/// Protocol message type identifiers. +/// Protocol message type identifiers and builders. abstract class Protocol { Protocol._(); @@ -32,18 +30,48 @@ abstract class Protocol { static const String rolePlayer = 'player'; /// Error codes. + /// + /// * [errBadRequest] — malformed JSON or a message with missing/wrong fields + /// * [errUnknownMessage] — unknown `t` value + /// * [errRejected] — the command was not executed (unknown name, invalid + /// args, or a game-rule guard such as a duplicate draw) + /// * [errForbidden] — the session's role does not allow the message + /// (spectator sending a gated command, undo/redo as a spectator) + /// * [errProtocol] — protocol version mismatch (the connection is closed) static const String errBadRequest = 'badRequest'; static const String errUnknownMessage = 'unknownMessage'; static const String errRejected = 'rejected'; + static const String errForbidden = 'forbidden'; static const String errProtocol = 'protocol'; - /// First client message: the handshake. The session id rides in a cookie - /// (Phase 2); in Phase 0 the server assigns a throwaway session. + /// First client message: the handshake. The session id rides in the + /// `x-haven-session` cookie (or the `?session=` query parameter) of the + /// upgrade request, so it is not part of the message. static Map helloMessage() => {'t': hello, 'v': version}; + /// Client message claiming a character seat (or re-asserting an existing + /// ownership). [characterId] is the character's id in the current list. + static Map claimMessage(String characterId) => { + 't': claim, + 'characterId': characterId, + }; + + /// Client message asking the server to execute a registered command + /// (players only — see PLAN.md section 3.3 for the role rules). + static Map commandMessage( + String name, [ + Map args = const {}, + ]) => { + 't': cmd, + 'name': name, + 'args': args, + }; + /// Full state snapshot for a new (or reconnecting) connection. [state] is /// already serialized for this connection, i.e. with that connection's /// secrets included and everyone else's masked (PLAN.md section 3.4). + /// [seats] maps every character in the current list to its owning session + /// id, or null when unclaimed. static Map welcomeMessage({ required String session, required String role, @@ -66,6 +94,32 @@ abstract class Protocol { }; } + /// Full-state push sent to every connection after a command, undo or redo + /// (the equivalent of the reference app's `{i, d, e, s}` envelope). + /// [state] is serialized per connection by the server. + static Map updateMessage({ + required int index, + required String description, + required Object? event, + required Map state, + }) { + return { + 't': update, + 'index': index, + 'description': description, + 'event': event, + 'state': state, + }; + } + + /// Seat-ownership broadcast: every character in the current list mapped to + /// its owning session id, or null when unclaimed. The UI enables inputs + /// only on the owning player's screen from this map. + static Map seatsMessage(Map seatsTable) => { + 't': seats, + 'seats': seatsTable, + }; + static Map errorMessage(String code, String message) => { 't': error, 'code': code, diff --git a/server/lib/net/seat_store.dart b/server/lib/net/seat_store.dart new file mode 100644 index 0000000..cd34bc4 --- /dev/null +++ b/server/lib/net/seat_store.dart @@ -0,0 +1,79 @@ +/// Persistent store for seat ownership (PLAN.md section 3.6). +/// +/// The authoritative snapshot includes which session owns which character, +/// so a player reconnecting with the same cookie after a server restart +/// keeps their seat. Written through on every ownership change; the game +/// state itself lives in the [SaveStore] alongside it. +library; + +import 'dart:convert'; +import 'dart:io'; + +import 'package:path/path.dart' as p; + +abstract class SeatStore { + /// Returns session id → character ids, or null when nothing is stored. + Map>? read(); + + /// Writes the full seat table. + void write(Map> seats); + + /// Removes the stored seat table. + void clear(); +} + +/// In-memory [SeatStore] — used by tests. +class InMemorySeatStore implements SeatStore { + Map>? _seats; + + @override + Map>? read() => _seats; + + @override + void write(Map> seats) => + _seats = Map>.from(seats); + + @override + void clear() => _seats = null; +} + +/// File-backed [SeatStore] writing a single JSON snapshot into [directory] +/// (next to the game state snapshot of [FileSaveStore]). +class FileSeatStore implements SeatStore { + final File _file; + + FileSeatStore(String directory) + : _file = File(p.join(directory, 'seats.json')); + + @override + Map>? read() { + if (!_file.existsSync()) return null; + try { + final data = jsonDecode(_file.readAsStringSync()) as Map; + return data.map( + (String sessionId, Object? value) => MapEntry( + sessionId, + (value as List).map((e) => e as String).toList(), + ), + ); + } catch (_) { + // Corrupt seat file: treat as "no seats" — the game state itself is + // still restored, characters are simply unclaimed. + return null; + } + } + + @override + void write(Map> seats) { + final dir = _file.parent; + if (!dir.existsSync()) dir.createSync(recursive: true); + // Synchronous write: the seat table must be on disk when [write] + // returns, so a crash or reboot never observes a half-written table. + _file.writeAsStringSync(jsonEncode(seats), flush: true); + } + + @override + void clear() { + if (_file.existsSync()) _file.deleteSync(); + } +} diff --git a/server/lib/net/sessions.dart b/server/lib/net/sessions.dart new file mode 100644 index 0000000..ae999ae --- /dev/null +++ b/server/lib/net/sessions.dart @@ -0,0 +1,134 @@ +/// Sessions and seat ownership (PLAN.md section 3.3). +/// +/// Every browser session has a persistent id (the `x-haven-session` cookie, +/// or the `?session=` query parameter) that survives page refreshes, so a +/// player keeps their seat. A session owning at least one character is a +/// *player*; any other session is a *spectator*. A character has at most one +/// owning session; when the owner's session disconnects, the character +/// becomes unclaimed and any session may claim it. +library; + +import 'dart:math'; + +import 'package:x_haven_server/core/state/game_state.dart'; + +import 'protocol.dart'; + +/// A persistent session: one browser (cookie) connecting to the game. +class SessionRecord { + SessionRecord(this.id); + + final String id; + + /// The ids of the characters this session owns. A character has at most + /// one owning session; a session may own several characters. + final Set ownedCharacters = {}; + + bool get isPlayer => ownedCharacters.isNotEmpty; + + String get role => isPlayer ? Protocol.rolePlayer : Protocol.roleSpectator; +} + +/// The in-memory session table: session id → [SessionRecord]. +/// +/// Records are kept even after a session disconnects — its id may come back +/// on the next connection (cookie), and persisted seats (see +/// `seat_store.dart`) may be restored onto it. +class SessionManager { + final Map _sessions = {}; + + /// Resolves [existingId] to its record. A well-formed but unknown id is + /// adopted as-is (the client presents its own session id via the cookie; + /// after a restart it must keep landing on the same session — including + /// any seats restored onto it). A malformed value is ignored and a fresh + /// id is minted. + SessionRecord resolve(String? existingId) { + if (existingId != null && isKnownFormat(existingId)) { + return _sessions[existingId] ?? resolveOrCreate(existingId); + } + return create(); + } + + /// Resolves [id], creating the record with exactly that id when it is not + /// known yet — used when restoring persisted seats at startup. + SessionRecord resolveOrCreate(String id) { + final existing = _sessions[id]; + if (existing != null) return existing; + final record = SessionRecord(id); + _sessions[id] = record; + return record; + } + + SessionRecord create() { + final record = SessionRecord(newSessionId()); + _sessions[record.id] = record; + return record; + } + + SessionRecord? lookup(String id) => _sessions[id]; + + /// Grants ownership of [characterId] to [session]. + /// + /// A character has at most one owning session, so any previous owner is + /// stripped first; callers should only assign characters that are + /// unclaimed (or that [session] already owns). + void assign(SessionRecord session, String characterId) { + for (final record in _sessions.values) { + record.ownedCharacters.remove(characterId); + } + session.ownedCharacters.add(characterId); + } + + /// The owning session of [characterId], if any. + SessionRecord? ownerOf(String characterId) { + for (final record in _sessions.values) { + if (record.ownedCharacters.contains(characterId)) return record; + } + return null; + } + + /// Releases every seat owned by session [id] (called when the session's + /// last connection is lost). Returns the released character ids. + Set release(String id) { + final record = _sessions[id]; + if (record == null) return const {}; + final released = Set.of(record.ownedCharacters); + record.ownedCharacters.clear(); + return released; + } + + /// character id → owning session id (owned characters only). + Map seats() { + final result = {}; + for (final record in _sessions.values) { + for (final characterId in record.ownedCharacters) { + result[characterId] = record.id; + } + } + return result; + } + + /// Every character in [state]'s current list mapped to its owning session + /// id, or null when unclaimed — the payload of `seats` messages. + Map seatsForState(GameState state) { + final owned = seats(); + final result = {}; + for (final item in state.currentList) { + if (item is Character) result[item.id] = owned[item.id]; + } + return result; + } + + /// All known session records, including disconnected ones. + Iterable get all => _sessions.values; + + /// A new session id: 32 lowercase hex characters. + static String newSessionId() { + final random = Random.secure(); + return List.generate(32, (_) => random.nextInt(16).toRadixString(16)).join(); + } + + /// Whether [id] is a well-formed session id (32 lowercase hex characters). + static bool isKnownFormat(String id) => + id.length == 32 && RegExp(r'^[0-9a-f]{32}$').hasMatch(id); +} diff --git a/server/lib/net/visibility.dart b/server/lib/net/visibility.dart new file mode 100644 index 0000000..ba53c08 --- /dev/null +++ b/server/lib/net/visibility.dart @@ -0,0 +1,116 @@ +/// The server-side visibility layer: per-connection state serialization with +/// secret gating (PLAN.md section 3.4). +/// +/// The state is serialized **per connection**: `serializeState(state, +/// context)` deep-copies the live state JSON and applies each visibility +/// rule that is not yet revealed. Secrets never exist on any connection +/// other than the owner's — a strict improvement over the reference app, +/// whose `??` mask was UI-only (every device held all values). +/// +/// Rules are data, not special cases: the list of rules is passed to +/// [serializeState], and a future secret is added as a new [VisibilityRule] +/// entry rather than a branch in the serializer. +library; + +import 'dart:convert'; + +import 'package:x_haven_server/core/enums.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; + +/// The connection a state snapshot is being serialized for. +class SessionContext { + const SessionContext({required this.sessionId, required this.seats}); + + /// The receiving connection's session id. + final String sessionId; + + /// character id → owning session id (owned characters only) — used by the + /// rules to tell the owner connection from everyone else. + final Map seats; +} + +/// One rule of the visibility layer: `(secret, owner, revealed-when)`. +class VisibilityRule { + const VisibilityRule({ + required this.name, + required this.revealed, + required this.mask, + }); + + /// Human-readable rule name (e.g. `'initiative'`). + final String name; + + /// Whether the secret is public for everyone right now — when true the + /// serializer includes the real values in every serialization. For the + /// initiative rule this flips when the draw action transitions the round + /// to [RoundState.playTurns]. + final bool Function(GameState state) revealed; + + /// Replaces the secret fields in [json] (a deep copy of the live state — + /// never mutate [state]) with masked values for the [context] connection. + /// Called only when [revealed] is false; the rule itself must keep the + /// secret visible to the owning connection and mask it for everyone else. + final void Function( + GameState state, + Map json, + SessionContext context, + ) mask; +} + +/// Rule #1: a character's initiative value is visible only to the session +/// that owns the character while the round is in +/// [RoundState.chooseInitiative]. Once [RoundState.playTurns] starts (the +/// draw action) the values are public in every serialization. +final VisibilityRule kInitiativeRule = VisibilityRule( + name: 'initiative', + revealed: (GameState state) => state.roundState == RoundState.playTurns, + mask: _maskInitiative, +); + +/// The default rule set. Future secrets are appended here. +final List kDefaultVisibilityRules = [kInitiativeRule]; + +/// Masks every character item that [context]'s session does not own. +/// +/// Character items are the only items carrying a `characterClass` key (the +/// same discriminator [GameSaveState.load] uses); the initiative value is +/// nested under their `characterState` key. +void _maskInitiative( + GameState state, + Map json, + SessionContext context, +) { + final list = json['currentList']; + if (list is! List) return; + for (final item in list) { + if (item is! Map) continue; + if (item['characterClass'] == null) continue; + final String? characterId = item['id'] is String ? item['id'] as String : null; + if (characterId != null && context.seats[characterId] == context.sessionId) { + continue; // the owner sees their own value + } + final characterState = item['characterState']; + if (characterState is Map) { + (characterState as Map)['initiative'] = null; + } + } +} + +/// Serializes [state] for the [context] connection: a deep copy of +/// `state.toJson()` with every not-yet-revealed visibility rule applied. +Map serializeState( + GameState state, + SessionContext context, { + List? rules, +}) { + // json round-trip = deep copy: each connection gets its own mutable tree + // so masking one serialization cannot leak into another. State is a few + // KB, so the copy is cheap. + final json = jsonDecode(jsonEncode(state.toJson())) as Map; + for (final rule in rules ?? kDefaultVisibilityRules) { + if (!rule.revealed(state)) { + rule.mask(state, json, context); + } + } + return json; +} diff --git a/server/lib/net/ws_upgrade.dart b/server/lib/net/ws_upgrade.dart new file mode 100644 index 0000000..18e2f5e --- /dev/null +++ b/server/lib/net/ws_upgrade.dart @@ -0,0 +1,138 @@ +/// WebSocket upgrade handling for the game endpoint. +/// +/// The stock `shelf_web_socket` handler never receives the upgrade +/// `Request` (only the channel and the subprotocol), so the +/// `x-haven-session` cookie — which carries the player's persistent +/// session id (PLAN.md section 3.3) — would be unreachable. This handler +/// performs the same RFC 6455 upgrade validation `shelf_web_socket` does +/// and hands the channel plus the session id from the request to the +/// [GameServer]. +library; + +import 'dart:convert'; +import 'dart:io'; + +import 'package:shelf/shelf.dart'; +import 'package:web_socket_channel/io.dart'; +import 'package:web_socket_channel/web_socket_channel.dart'; + +import 'game_server.dart'; +import 'sessions.dart'; + +/// The cookie carrying a session's persistent id. +const String sessionCookieName = 'x-haven-session'; + +/// Creates the shelf handler for `GET /ws`. +Handler createWebSocketUpgradeHandler( + GameServer gameServer, { + Iterable? allowedOrigins, +}) { + return (Request request) { + if (request.method != 'GET') { + return _html(404, '404 Not Found', 'Only WebSocket connections are supported.'); + } + final connection = request.headers['Connection']; + if (connection == null) { + return _html(404, '404 Not Found', 'Only WebSocket connections are supported.'); + } + final tokens = + connection + .toLowerCase() + .split(',') + .map((token) => token.trim()) + .toList(); + if (!tokens.contains('upgrade')) { + return _html(404, '404 Not Found', 'Only WebSocket connections are supported.'); + } + + final upgrade = request.headers['Upgrade']; + if (upgrade == null || upgrade.toLowerCase() != 'websocket') { + return _html(404, '404 Not Found', 'Only WebSocket connections are supported.'); + } + final version = request.headers['Sec-WebSocket-Version']; + if (version == null || version != '13') { + return _html(404, '404 Not Found', 'Only WebSocket connections are supported.'); + } + if (request.protocolVersion != '1.1') { + return _html( + 400, + '400 Bad Request', + 'Unexpected HTTP version "${request.protocolVersion}".', + ); + } + final key = request.headers['Sec-WebSocket-Key']; + if (key == null) { + return _html(400, '400 Bad Request', 'Missing Sec-WebSocket-Key header.'); + } + if (!request.canHijack) { + throw ArgumentError('The WebSocket endpoint needs a hijack-capable server.'); + } + + // Browsers always send Origin; when [allowedOrigins] is set, refuse + // cross-origin pages. Left open by default, as the reference app is a + // local-LAN game where any device may join the table. + final origin = request.headers['Origin']; + if (origin != null && + allowedOrigins != null && + !allowedOrigins.contains(origin.toLowerCase())) { + return _html(403, '403 Forbidden', 'Invalid origin "$origin".'); + } + + final String? cookieSessionId = _sessionIdFromRequest(request); + + request.hijack((channel) { + utf8.encoder + .startChunkedConversion(channel.sink) + .add('HTTP/1.1 101 Switching Protocols\r\n' + 'Upgrade: websocket\r\n' + 'Connection: Upgrade\r\n' + 'Sec-WebSocket-Accept: ${WebSocketChannel.signKey(key)}\r\n' + '\r\n'); + if (channel.sink is! Socket) { + throw ArgumentError('channel.sink must be a dart:io `Socket`.'); + } + final webSocket = WebSocket.fromUpgradedSocket( + channel.sink as Socket, + serverSide: true, + ); + gameServer.attach(IOWebSocketChannel(webSocket), cookieSessionId: cookieSessionId); + }); + // Unreachable: Request.hijack throws the HijackException shelf_io + // swallows (same contract shelf_web_socket relies on). + }; +} + +/// The session id from the upgrade request: the `x-haven-session` cookie +/// first, then the `?session=` query parameter (non-browser clients). +/// Malformed values (not 32 lowercase hex characters) are ignored — the +/// [GameServer] will mint a fresh session instead. +String? _sessionIdFromRequest(Request request) { + final cookie = request.headers['Cookie']; + if (cookie != null) { + for (final part in cookie.split(';')) { + final trimmed = part.trim(); + if (trimmed.startsWith('$sessionCookieName=')) { + final value = trimmed.substring(sessionCookieName.length + 1).trim(); + if (SessionManager.isKnownFormat(value)) return value; + } + } + } + final query = request.url.queryParameters['session']; + if (query != null && SessionManager.isKnownFormat(query)) return query; + return null; +} + +Response _html(int statusCode, String title, String message) => Response( + statusCode, + headers: {'content-type': 'text/html'}, + body: ''' + + + ${htmlEscape.convert(title)} + +

${htmlEscape.convert(title)}

+

${htmlEscape.convert(message)}

+ + +''', +); diff --git a/server/test/net/app_test.dart b/server/test/net/app_test.dart new file mode 100644 index 0000000..4a02c15 --- /dev/null +++ b/server/test/net/app_test.dart @@ -0,0 +1,140 @@ +/// Phase 2: HTTP endpoints (healthz, session, static) and the WS protocol +/// basics — handshake, version check, ping/pong, error responses. +library; + +import 'dart:convert'; +import 'dart:io'; + +import 'package:test/test.dart'; +import 'package:x_haven_server/net/protocol.dart'; +import 'package:x_haven_server/net/sessions.dart'; + +import 'ws_test_helpers.dart'; + +void main() { + late TestGameServer server; + + setUp(() async { + server = await TestGameServer.boot(); + }); + + tearDown(() async { + await server.shutdown(); + }); + + Future httpGet(Uri url, {Map headers = const {}}) async { + final client = HttpClient(); + addTearDown(client.close); + final request = await client.getUrl(url); + headers.forEach(request.headers.set); + final response = await request.close(); + final body = await response.transform(utf8.decoder).join(); + return body; + } + + test('serves a stub page at / when the static dir is missing', () async { + final body = await httpGet(server.httpUrl.replace(path: '/')); + expect(body, contains('X-Haven server')); + }); + + test('answers healthz', () async { + final body = await httpGet(server.httpUrl.replace(path: '/healthz')); + expect(jsonDecode(body), {'status': 'ok'}); + }); + + test('session endpoint mints a session and sets the cookie', () async { + final client = HttpClient(); + addTearDown(client.close); + final request = await client.getUrl(server.httpUrl.replace(path: '/session')); + final response = await request.close(); + expect(response.statusCode, 200); + final setCookie = response.headers.value('set-cookie'); + expect(setCookie, isNotNull); + expect(setCookie, startsWith('x-haven-session=')); + final id = setCookie!.substring('x-haven-session='.length).split(';').first; + expect(SessionManager.isKnownFormat(id), isTrue); + expect( + jsonDecode(await response.transform(utf8.decoder).join()), + {'session': id}, + ); + + // Same cookie in → same session out, no new cookie. + final request2 = await client.getUrl( + server.httpUrl.replace(path: '/session'), + ); + request2.headers.set('Cookie', 'x-haven-session=$id'); + final response2 = await request2.close(); + expect(response2.headers.value('set-cookie'), isNull); + expect( + jsonDecode(await response2.transform(utf8.decoder).join()), + {'session': id}, + ); + }); + + test('answers hello with a welcome carrying the real state', () async { + final client = await TestClient.connect(server.wsUrl); + client.sendHello(); + final welcome = await client.nextOf('welcome'); + + expect(welcome['v'], Protocol.version); + expect(welcome['session'], isA()); + expect(SessionManager.isKnownFormat(welcome['session'] as String), isTrue); + expect(welcome['role'], Protocol.roleSpectator); + expect(welcome['index'], -1, reason: 'no actions executed yet'); + expect(welcome['description'], isNull); + final state = welcome['state'] as Map; + expect(state['roundState'], 0, reason: 'chooseInitiative'); + expect(state['currentList'], isEmpty); + expect(welcome['seats'], isEmpty); + }); + + test('a re-sent hello re-answers with a fresh welcome', () async { + final client = await TestClient.connect(server.wsUrl); + client.sendHello(); + await client.nextOf('welcome'); + client.sendHello(); + expect((await client.nextOf('welcome'))['t'], 'welcome'); + }); + + test('answers ping with pong', () async { + final client = await TestClient.connect(server.wsUrl); + client.send({'t': 'ping'}); + expect(await client.next(), {'t': 'pong'}); + }); + + test('rejects messages sent before hello with badRequest', () async { + final client = await TestClient.connect(server.wsUrl); + client.send(Protocol.commandMessage('draw')); + final error = await client.nextOf('error'); + expect(error['code'], Protocol.errBadRequest); + expect(error['message'], 'send hello first'); + }); + + test('rejects a protocol version mismatch and closes the connection', + () async { + final client = await TestClient.connect(server.wsUrl); + client.send({'t': 'hello', 'v': 999}); + final error = await client.nextOf('error'); + expect(error['code'], Protocol.errProtocol); + expect(error['message'], contains('version mismatch')); + await client.closedFuture.timeout( + const Duration(seconds: 5), + onTimeout: () => fail('the connection was not closed'), + ); + expect(client.closed, isTrue, reason: 'the connection is closed'); + }); + + test('rejects malformed and unknown messages with error', () async { + final client = await TestClient.connect(server.wsUrl); + client.sendHello(); + await client.nextOf('welcome'); + + client.sendRaw('this is not json'); + expect((await client.nextOf('error'))['code'], Protocol.errBadRequest); + + client.send({'t': 'warpSpeed'}); + final error = await client.nextOf('error'); + expect(error['code'], Protocol.errUnknownMessage); + expect(error['message'], contains('warpSpeed')); + }); +} diff --git a/server/test/net/multiplayer_test.dart b/server/test/net/multiplayer_test.dart new file mode 100644 index 0000000..e3bb225 --- /dev/null +++ b/server/test/net/multiplayer_test.dart @@ -0,0 +1,461 @@ +/// Phase 2 / Milestone M2: the full multiplayer + secrets scenario over a +/// real WebSocket — two players (alice, bob) and one spectator (carol): +/// +/// * secret initiative never reaches non-owners; reveal on draw +/// * rejected duplicate draw (error to the sender only) +/// * draw blocked until all initiative values are entered +/// * spectator role gating (commands forbidden, claim allowed) +/// * claim / release / re-claim of seats +/// * reconnect resync with per-connection masking +/// * undo/redo requested by players, broadcast to everyone +/// * dead-connection cleanup with seat release +library; + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/service_locator.dart'; +import 'package:x_haven_server/core/settings.dart'; +import 'package:x_haven_server/net/protocol.dart'; + +import 'ws_test_helpers.dart'; + +/// A table with two players and one spectator, mid-setup. +class Table { + late TestGameServer server; + late TestClient alice; // will own 'Blinkblade' + late TestClient bob; // will own 'Banner Spear' + late TestClient carol; // spectator + String aliceId = ''; + String bobId = ''; + String carolId = ''; + + List get everyone => [alice, bob, carol]; + + Future setup() async { + server = await TestGameServer.boot(); + try { + getIt().noInit = false; // exercise the initiative gate + + alice = await TestClient.connect(server.wsUrl); + bob = await TestClient.connect(server.wsUrl); + carol = await TestClient.connect(server.wsUrl); + alice.sendHello(); + bob.sendHello(); + carol.sendHello(); + aliceId = (await alice.nextOf('welcome'))['session'] as String; + bobId = (await bob.nextOf('welcome'))['session'] as String; + carolId = (await carol.nextOf('welcome'))['session'] as String; + + // Each player adds their own character: the session that adds a + // character owns it and becomes a player. + alice.sendCmd( + 'addCharacter', + {'id': 'Blinkblade', 'edition': 'Frosthaven', 'display': 'Blinky', 'level': 1}, + ); + bob.sendCmd( + 'addCharacter', + {'id': 'Banner Spear', 'edition': 'Frosthaven', 'display': 'Spear', 'level': 1}, + ); + for (final client in everyone) { + await client.nextOf('update'); + await client.nextOf('seats'); + await client.nextOf('update'); + await client.nextOf('seats'); + } + return this; + } catch (_) { + await server.shutdown(); + rethrow; + } + } + + Future teardown() async { + for (final client in everyone) { + await client.close(); + } + await server.shutdown(); + } + + /// Both players enter initiative: alice 5, bob 3. Consumes the updates. + Future enterInitiative() async { + alice.sendCmd('setInit', {'characterId': 'Blinkblade', 'init': 5}); + bob.sendCmd('setInit', {'characterId': 'Banner Spear', 'init': 3}); + for (final client in everyone) { + await client.nextOf('update'); + await client.nextOf('update'); + } + } + + /// alice taps the draw button; consumes the updates on all three screens. + Future draw() async { + alice.sendCmd('draw'); + for (final client in everyone) { + await client.nextOf('update'); + } + } +} + +void main() { + late Table table; + var tableBuilt = false; + + setUp(() async { + table = await Table().setup(); + tableBuilt = true; + }); + + tearDown(() async { + // When setUp failed before the table was built, setup() has already + // shut the server down — nothing to tear down. + if (tableBuilt) { + await table.teardown(); + } + }); + + Map stateOf(Map message) => + Map.from(message['state'] as Map); + + test('secret initiative never reaches non-owners; reveal on draw', () async { + // --- bob enters 3 ------------------------------------------------------ + table.bob.sendCmd('setInit', {'characterId': 'Banner Spear', 'init': 3}); + + // The owner sees their own value; the other player's value is masked. + expect( + TestClient.initiativeIn(stateOf(await table.bob.nextOf('update')), 'Banner Spear'), + 3, + reason: 'bob sees his own initiative', + ); + expect( + TestClient.initiativeIn(stateOf(await table.alice.nextOf('update')), 'Banner Spear'), + null, + reason: 'bob\'s value is masked for alice', + ); + expect( + TestClient.initiativeIn( + stateOf(await table.carol.nextOf('update')), + 'Banner Spear', + ), + null, + reason: 'the spectator sees no initiative at all', + ); + + // --- alice enters 5 ---------------------------------------------------- + table.alice.sendCmd('setInit', {'characterId': 'Blinkblade', 'init': 5}); + + expect( + TestClient.initiativeIn(stateOf(await table.alice.nextOf('update')), 'Blinkblade'), + 5, + ); + expect( + TestClient.initiativeIn( + stateOf(await table.bob.nextOf('update')), + 'Blinkblade', + ), + null, + ); + expect( + TestClient.initiativeIn( + stateOf(await table.carol.nextOf('update')), + 'Blinkblade', + ), + null, + ); + + // --- draw: initiative becomes public to everyone ----------------------- + await table.draw(); + + for (final client in table.everyone) { + // The draw update was consumed; resync via a fresh welcome to assert + // the revealed state on every screen. + client.sendHello(); + final state = stateOf(await client.nextOf('welcome')); + expect( + state['roundState'], + 1, + reason: 'playTurns on every screen', + ); + expect( + TestClient.initiativeIn(state, 'Blinkblade'), + 5, + reason: '${client == table.alice ? 'alice' : client == table.bob ? 'bob' : 'carol'} sees the public value', + ); + expect(TestClient.initiativeIn(state, 'Banner Spear'), 3); + } + + // Lower initiative acts first. + table.alice.sendHello(); + final state = stateOf(await table.alice.nextOf('welcome')); + expect( + TestClient.characterIn(state, 'Banner Spear'), + isNotNull, + ); + final list = state['currentList'] as List; + final spearIndex = list.indexWhere((item) => item is Map && item['id'] == 'Banner Spear'); + final blinkIndex = list.indexWhere((item) => item is Map && item['id'] == 'Blinkblade'); + expect(spearIndex, lessThan(blinkIndex), reason: '3 < 5'); + }); + + test('duplicate draw is rejected; the error goes to the sender only', + () async { + await table.enterInitiative(); + await table.draw(); + + table.alice.sendCmd('draw'); + final error = await table.alice.nextOf('error'); + expect(error['code'], Protocol.errRejected); + expect(error['message'], 'the round has already been drawn'); + + // No update, no seats: the other screens never heard about the + // rejected command. + await Future.delayed(const Duration(milliseconds: 200)); + expect(table.bob.flush(), isEmpty); + expect(table.carol.flush(), isEmpty); + }); + + test('draw is blocked until every player has entered initiative', () async { + table.alice.sendCmd('setInit', {'characterId': 'Blinkblade', 'init': 5}); + for (final client in table.everyone) { + await client.nextOf('update'); + } + + table.alice.sendCmd('draw'); + final error = await table.alice.nextOf('error'); + expect(error['code'], Protocol.errRejected); + expect(error['message'], contains('initiative')); + + await Future.delayed(const Duration(milliseconds: 200)); + expect(table.bob.flush(), isEmpty); + + table.bob.sendCmd('setInit', {'characterId': 'Banner Spear', 'init': 3}); + for (final client in table.everyone) { + await client.nextOf('update'); + } + + table.alice.sendCmd('draw'); + final update = await table.alice.nextOf('update'); + expect(stateOf(update)['roundState'], 1); + }); + + test('spectator commands are forbidden; claiming is how they join', () async { + // A gated command as a spectator: rejected with a role error. + table.carol.sendCmd( + 'changeHealth', + {'change': -1, 'figureId': 'Blinkblade'}, + ); + final error = await table.carol.nextOf('error'); + expect(error['code'], Protocol.errForbidden); + expect(error['message'], contains('claim a character')); + + // Undo/redo are player-only too. + table.carol.send({'t': 'undo'}); + expect((await table.carol.nextOf('error'))['code'], Protocol.errForbidden); + + // Claiming a character is allowed for spectators — but only if it is + // unclaimed. + table.carol.sendClaim('Blinkblade'); + final rejected = await table.carol.nextOf('error'); + expect(rejected['code'], Protocol.errRejected); + expect(rejected['message'], contains('already claimed')); + + // Unknown character. + table.carol.sendClaim('Nyx'); + final noSuch = await table.carol.nextOf('error'); + expect(noSuch['code'], Protocol.errRejected); + expect(noSuch['message'], contains('Nyx')); + }); + + test('nextRound is rejected before the round has started', () async { + table.alice.sendCmd('nextRound'); + final error = await table.alice.nextOf('error'); + expect(error['code'], Protocol.errRejected); + expect(error['message'], 'the round has not started yet'); + }); + + test('claim flow: disconnect releases the seat; re-claim works', () async { + // carol cannot claim a character bob owns. + table.carol.sendClaim('Banner Spear'); + expect((await table.carol.nextOf('error'))['code'], Protocol.errRejected); + + // bob leaves: his character becomes unclaimed. + await table.bob.close(); + final seatsForAlice = await table.alice.nextOf('seats'); + expect(TestClient.seatsOf(seatsForAlice)['Banner Spear'], null); + expect(TestClient.seatsOf(seatsForAlice)['Blinkblade'], table.aliceId); + final seatsForCarol = await table.carol.nextOf('seats'); + expect(TestClient.seatsOf(seatsForCarol)['Banner Spear'], null); + + // carol claims the freed character and becomes its owner. + table.carol.sendClaim('Banner Spear'); + final seats2 = await table.carol.nextOf('seats'); + expect(TestClient.seatsOf(seats2)['Banner Spear'], table.carolId); + final seats2ForAlice = await table.alice.nextOf('seats'); + expect(TestClient.seatsOf(seats2ForAlice)['Banner Spear'], table.carolId); + + // Re-asserting an existing ownership is a no-op (no error, same table). + table.carol.sendClaim('Banner Spear'); + final seats3 = await table.carol.nextOf('seats'); + expect(TestClient.seatsOf(seats3)['Banner Spear'], table.carolId); + expect(TestClient.seatsOf(seats3)['Blinkblade'], table.aliceId); + + // carol still cannot claim alice's character. + table.carol.sendClaim('Blinkblade'); + expect((await table.carol.nextOf('error'))['code'], Protocol.errRejected); + }); + + test('reconnect resync: full welcome, released seat, re-claim', () async { + table.alice.sendCmd('setInit', {'characterId': 'Blinkblade', 'init': 5}); + table.bob.sendCmd('setInit', {'characterId': 'Banner Spear', 'init': 3}); + + // The last update on every screen carries the index to expect in a + // fresh welcome. + var lastUpdateIndex = -1; + for (final client in table.everyone) { + await client.nextOf('update'); + final second = await client.nextOf('update'); + lastUpdateIndex = second['index'] as int; + } + + // alice leaves; her seat is released. + await table.alice.close(); + final seats = await table.bob.nextOf('seats'); + expect(TestClient.seatsOf(seats)['Blinkblade'], null); + + // Reconnect with the same session id (the cookie's job). + final alice2 = await TestClient.connect( + table.server.wsUrl, + session: table.aliceId, + ); + alice2.sendHello(); + final welcome = await alice2.nextOf('welcome'); + expect(welcome['session'], table.aliceId); + expect(welcome['role'], Protocol.roleSpectator, reason: 'seat was released'); + expect(welcome['index'], lastUpdateIndex, reason: 'full resync, same index'); + + // While the seat is free, even her own old value is masked for her. + final welcomeState = stateOf(welcome); + expect(welcomeState['roundState'], 0, reason: 'still choosing initiative'); + expect(TestClient.initiativeIn(welcomeState, 'Blinkblade'), null); + expect(TestClient.initiativeIn(welcomeState, 'Banner Spear'), null); + + // Re-claim her character, then resync: the value is hers to see again. + alice2.sendClaim('Blinkblade'); + await alice2.nextOf('seats'); + await table.bob.nextOf('seats'); + alice2.sendHello(); + final welcome2 = await alice2.nextOf('welcome'); + expect(welcome2['role'], Protocol.rolePlayer); + expect( + TestClient.initiativeIn(stateOf(welcome2), 'Blinkblade'), + 5, + reason: 'the owner sees their own secret again', + ); + expect(TestClient.initiativeIn(stateOf(welcome2), 'Banner Spear'), null); + await alice2.close(); + }); + + test('undo/redo: player requests, every screen resyncs', () async { + await table.enterInitiative(); + await table.draw(); + // Initiative order: 'Banner Spear' (3) first, then 'Blinkblade' (5). + + table.bob.sendCmd('turnDone', {'id': 'Banner Spear'}); + final turnDone = await table.bob.nextOf('update'); + // The other screens carry the same update too — drain them so the + // undo/redo updates below are the only ones queued. + await table.alice.nextOf('update'); + await table.carol.nextOf('update'); + final indexAtTurnDone = turnDone['index'] as int; + var state = stateOf(turnDone); + expect( + TestClient.characterIn(state, 'Banner Spear')?['turnState'], + 2, + reason: 'done', + ); + expect( + TestClient.characterIn(state, 'Blinkblade')?['turnState'], + 1, + reason: 'current', + ); + + // undo: the state rolls back (the index carries the undone action's + // index, exactly like the reference app's server-side send). + table.bob.send({'t': 'undo'}); + for (final client in table.everyone) { + final update = await client.nextOf('update'); + state = stateOf(update); + expect(update['index'], indexAtTurnDone); + expect( + TestClient.characterIn(state, 'Banner Spear')?['turnState'], + 1, + reason: 'current again', + ); + expect( + TestClient.characterIn(state, 'Blinkblade')?['turnState'], + 0, + reason: 'waiting again', + ); + expect(update['event'], {'type': 'none'}); + } + + // redo: forward again. + table.bob.send({'t': 'redo'}); + for (final client in table.everyone) { + final update = await client.nextOf('update'); + state = stateOf(update); + expect(update['index'], indexAtTurnDone); + expect( + TestClient.characterIn(state, 'Banner Spear')?['turnState'], + 2, + ); + expect(TestClient.characterIn(state, 'Blinkblade')?['turnState'], 1); + } + }); + + test('dead connection cleanup: a quiet socket is closed, the seat released', + () async { + // Short timeouts: the sweep runs every 100 ms, dead after 400 ms quiet. + await table.teardown(); + table.server = await TestGameServer.boot( + heartbeatInterval: const Duration(milliseconds: 100), + deadTimeout: const Duration(milliseconds: 400), + ); + getIt().noInit = false; + table.alice = await TestClient.connect(table.server.wsUrl); + table.bob = await TestClient.connect(table.server.wsUrl); + table.carol = await TestClient.connect(table.server.wsUrl); + table.alice.sendHello(); + table.bob.sendHello(); + table.carol.sendHello(); + table.aliceId = (await table.alice.nextOf('welcome'))['session'] as String; + table.bobId = (await table.bob.nextOf('welcome'))['session'] as String; + table.carolId = (await table.carol.nextOf('welcome'))['session'] as String; + + table.alice.sendCmd( + 'addCharacter', + {'id': 'Blinkblade', 'edition': 'Frosthaven', 'display': 'Blinky', 'level': 1}, + ); + for (final client in [table.alice, table.bob, table.carol]) { + await client.nextOf('update'); + await client.nextOf('seats'); + } + + // Keep bob and carol alive so only alice is swept. + table.bob.send({'t': 'ping'}); + table.carol.send({'t': 'ping'}); + await table.bob.nextOf('pong'); + await table.carol.nextOf('pong'); + + // alice goes quiet (no pings) — the sweep must close her and release + // the seat so the others can re-claim. + await table.alice.closedFuture.timeout( + const Duration(seconds: 5), + ); + final seats = await table.bob.nextOf('seats'); + expect(TestClient.seatsOf(seats)['Blinkblade'], null); + final seatsForCarol = await table.carol.nextOf('seats'); + expect(TestClient.seatsOf(seatsForCarol)['Blinkblade'], null); + + await table.bob.close(); + await table.carol.close(); + await table.server.shutdown(); + }); +} diff --git a/server/test/net/persistence_test.dart b/server/test/net/persistence_test.dart new file mode 100644 index 0000000..6626840 --- /dev/null +++ b/server/test/net/persistence_test.dart @@ -0,0 +1,224 @@ +/// Phase 2 / Milestone M2: persistence across a server restart +/// (PLAN.md section 3.6) — the state snapshot is saved on every action and +/// restored on startup; seat ownership is restored from `seats.json`. +/// +/// The in-process "crash" here is a clean disconnect: the clients close, +/// the disconnect handlers run (seats released, seat file finalized), and +/// only then is the server killed. A real kill -9 would skip the handlers +/// and leave the last seat write behind — test 2 simulates that case by +/// restoring the pre-crash seat file before the reboot. +library; + +import 'dart:io'; + +import 'package:path/path.dart' as p; +import 'package:test/test.dart'; +import 'package:x_haven_server/core/save_store.dart'; +import 'package:x_haven_server/core/service_locator.dart'; +import 'package:x_haven_server/net/protocol.dart'; +import 'package:x_haven_server/net/seat_store.dart'; + +import 'ws_test_helpers.dart'; + +/// The two players' clients and alice's session id. +class Players { + Players(this.aliceId, this.alice, this.bob); + + final String aliceId; + final TestClient alice; + final TestClient bob; + + List get clients => [alice, bob]; +} + +void main() { + late Directory dir; + + setUp(() { + dir = Directory.systemTemp.createTempSync('x-haven-persist-'); + }); + + tearDown(() { + if (dir.existsSync()) dir.deleteSync(recursive: true); + }); + + /// Two players add characters and enter initiative (optionally draw). + Future setupPlayers( + TestGameServer server, { + required bool draw, + }) async { + final alice = await TestClient.connect(server.wsUrl); + final bob = await TestClient.connect(server.wsUrl); + alice.sendHello(); + bob.sendHello(); + final aliceId = (await alice.nextOf('welcome'))['session'] as String; + await bob.nextOf('welcome'); + + alice.sendCmd( + 'addCharacter', + {'id': 'Blinkblade', 'edition': 'Frosthaven', 'display': 'Blinky', 'level': 1}, + ); + bob.sendCmd( + 'addCharacter', + {'id': 'Banner Spear', 'edition': 'Frosthaven', 'display': 'Spear', 'level': 1}, + ); + for (final client in [alice, bob]) { + await client.nextOf('update'); + await client.nextOf('seats'); + await client.nextOf('update'); + await client.nextOf('seats'); + } + + alice.sendCmd('setInit', {'characterId': 'Blinkblade', 'init': 5}); + for (final client in [alice, bob]) { + await client.nextOf('update'); + } + bob.sendCmd('setInit', {'characterId': 'Banner Spear', 'init': 3}); + for (final client in [alice, bob]) { + await client.nextOf('update'); + } + + if (draw) { + alice.sendCmd('draw'); + for (final client in [alice, bob]) { + await client.nextOf('update'); + } + } + return Players(aliceId, alice, bob); + } + + /// Kills the server after the clients have disconnected cleanly, so the + /// disconnect handlers (seat release + seat-file write) have run and the + /// on-disk state is final before the reboot. + Future crash(TestGameServer server, List clients) async { + for (final client in clients) { + await client.close(); + } + server.gameServer.dispose(); + await server.server.close(force: true); + // Give the disconnect handlers a bounded time to drain; the seat file + // is final by the time the connection table empties. + for (var i = 0; i < 500 && server.gameServer.connectionCount > 0; i++) { + await Future.delayed(const Duration(milliseconds: 10)); + } + await getIt.reset(); + } + + test('state snapshot restored after a server restart', () async { + final serverA = await TestGameServer.boot( + saveStore: FileSaveStore(dir.path), + seatStore: FileSeatStore(dir.path), + ); + final players = await setupPlayers(serverA, draw: true); + + // Both snapshots exist on disk. + expect(File(p.join(dir.path, 'game.json')).existsSync(), isTrue); + expect(File(p.join(dir.path, 'seats.json')).existsSync(), isTrue); + + await crash(serverA, players.clients); + + // Reboot on the same stores. + final serverB = await TestGameServer.boot( + saveStore: FileSaveStore(dir.path), + seatStore: FileSeatStore(dir.path), + ); + addTearDown(serverB.shutdown); + + // The same cookie (session id) reconnects. + final alice2 = + await TestClient.connect(serverB.wsUrl, session: players.aliceId); + alice2.sendHello(); + final welcome = await alice2.nextOf('welcome'); + expect(welcome['session'], players.aliceId); + final state = welcome['state'] as Map; + expect(state['roundState'], 1, reason: 'mid playTurns, as before the crash'); + expect( + TestClient.initiativeIn(state, 'Blinkblade'), + 5, + reason: 'initiative was public after the draw', + ); + expect(TestClient.initiativeIn(state, 'Banner Spear'), 3); + + // The command index is per server lifetime: a restored game starts a + // fresh sequence at -1 (the snapshot carries state, not undo history). + expect(welcome['index'], -1); + + // The in-process crash ran the disconnect handlers, so the seat was + // released and the role is back to spectator — re-claim to join again. + expect(welcome['role'], Protocol.roleSpectator); + alice2.sendClaim('Blinkblade'); + final seats = await alice2.nextOf('seats'); + expect(TestClient.seatsOf(seats)['Blinkblade'], players.aliceId); + + // The restored game is playable: a new action executes on top of it. + alice2.sendCmd('turnDone', {'id': 'Banner Spear'}); + final update = await alice2.nextOf('update'); + expect(update['index'], 0, reason: 'fresh server lifetime'); + expect( + TestClient.characterIn( + update['state'] as Map, + 'Banner Spear', + )?['turnState'], + 2, + ); + await alice2.close(); + }); + + test('crash-time seat file is restored at startup (kill -9 semantics)', + () async { + final serverA = await TestGameServer.boot( + saveStore: FileSaveStore(dir.path), + seatStore: FileSeatStore(dir.path), + ); + final players = await setupPlayers(serverA, draw: false); + + await crash(serverA, players.clients); + + // A real kill -9 leaves the last pre-crash seat write behind (the + // disconnect handler never runs). The in-process crash above ran it, + // so restore that last write before the reboot. + FileSeatStore(dir.path).write({players.aliceId: ['Blinkblade']}); + + final serverB = await TestGameServer.boot( + saveStore: FileSaveStore(dir.path), + seatStore: FileSeatStore(dir.path), + ); + addTearDown(serverB.shutdown); + + final alice2 = + await TestClient.connect(serverB.wsUrl, session: players.aliceId); + alice2.sendHello(); + final welcome = await alice2.nextOf('welcome'); + + // The seat survived the restart: she is a player again. + expect(welcome['role'], Protocol.rolePlayer); + final seats = TestClient.seatsOf(welcome); + expect(seats['Blinkblade'], players.aliceId); + expect(seats['Banner Spear'], null, reason: 'bob did not re-claim'); + + // Her secret is hers to see again — still masked for the others. + final state = welcome['state'] as Map; + expect(state['roundState'], 0, reason: 'still choosing initiative'); + expect( + TestClient.initiativeIn(state, 'Blinkblade'), + 5, + reason: 'the restored owner sees their own value', + ); + expect( + TestClient.initiativeIn(state, 'Banner Spear'), + null, + reason: 'bob\'s value is masked for everyone', + ); + + // And a spectator on the same server sees neither value. + final carol = await TestClient.connect(serverB.wsUrl); + carol.sendHello(); + final carolWelcome = await carol.nextOf('welcome'); + expect(carolWelcome['role'], Protocol.roleSpectator); + final carolState = carolWelcome['state'] as Map; + expect(TestClient.initiativeIn(carolState, 'Blinkblade'), null); + expect(TestClient.initiativeIn(carolState, 'Banner Spear'), null); + await carol.close(); + await alice2.close(); + }); +} diff --git a/server/test/net/sessions_test.dart b/server/test/net/sessions_test.dart new file mode 100644 index 0000000..c2d5d8f --- /dev/null +++ b/server/test/net/sessions_test.dart @@ -0,0 +1,107 @@ +/// Phase 2: SessionManager unit tests — session resolution, seat +/// assignment, release, and role derivation (PLAN.md section 3.3). +library; + +import 'package:test/test.dart'; +import 'package:x_haven_server/net/protocol.dart'; +import 'package:x_haven_server/net/sessions.dart'; + +void main() { + test('resolve mints a fresh session for a null or unknown id', () { + final manager = SessionManager(); + final first = manager.resolve(null); + expect(SessionManager.isKnownFormat(first.id), isTrue); + + final second = manager.resolve('0123456789abcdef0123456789abcdef'); + expect(second.id, '0123456789abcdef0123456789abcdef'); + expect(second, isNot(same(first))); + }); + + test('resolve returns the existing record for a known id', () { + final manager = SessionManager(); + final created = manager.resolve(null); + final resolved = manager.resolve(created.id); + expect(resolved, same(created)); + }); + + test('a session is a spectator until it owns a character', () { + final manager = SessionManager(); + final session = manager.resolve(null); + expect(session.isPlayer, isFalse); + expect(session.role, Protocol.roleSpectator); + + manager.assign(session, 'Blinkblade'); + expect(session.isPlayer, isTrue); + expect(session.role, Protocol.rolePlayer); + }); + + test('a character has at most one owning session', () { + final manager = SessionManager(); + final alice = manager.resolve(null); + final bob = manager.resolve(null); + + manager.assign(alice, 'Blinkblade'); + expect(manager.ownerOf('Blinkblade'), same(alice)); + + // Re-assigning to another session strips the first owner. + manager.assign(bob, 'Blinkblade'); + expect(manager.ownerOf('Blinkblade'), same(bob)); + expect(alice.ownedCharacters, isEmpty); + expect(bob.ownedCharacters, {'Blinkblade'}); + }); + + test('a session may own several characters', () { + final manager = SessionManager(); + final alice = manager.resolve(null); + manager.assign(alice, 'Blinkblade'); + manager.assign(alice, 'Banner Spear'); + expect( + manager.seats(), + {'Blinkblade': alice.id, 'Banner Spear': alice.id}, + ); + }); + + test('release empties the session\'s seats and returns them', () { + final manager = SessionManager(); + final alice = manager.resolve(null); + manager.assign(alice, 'Blinkblade'); + + final released = manager.release(alice.id); + expect(released, {'Blinkblade'}); + expect(alice.ownedCharacters, isEmpty); + expect(alice.role, Protocol.roleSpectator); + expect(manager.ownerOf('Blinkblade'), isNull); + }); + + test('release of an unknown session is a no-op', () { + final manager = SessionManager(); + expect(manager.release('0123456789abcdef0123456789abcdef'), isEmpty); + }); + + test('seats lists owned characters with their owning session id', () { + final manager = SessionManager(); + final alice = manager.resolve(null); + final bob = manager.resolve(null); + manager.assign(alice, 'Blinkblade'); + manager.assign(bob, 'Banner Spear'); + manager.assign(bob, 'Soul Slayer'); + + expect( + manager.seats(), + { + 'Blinkblade': alice.id, + 'Banner Spear': bob.id, + 'Soul Slayer': bob.id, + }, + ); + }); + + test('session id format validation', () { + expect(SessionManager.isKnownFormat('a' * 32), isTrue); + expect(SessionManager.isKnownFormat('0123456789abcdef0123456789abcdef'), isTrue); + expect(SessionManager.isKnownFormat('A' * 32), isFalse, reason: 'uppercase rejected'); + expect(SessionManager.isKnownFormat('abc'), isFalse); + expect(SessionManager.isKnownFormat('g' * 32), isFalse, reason: 'non-hex rejected'); + expect(SessionManager.isKnownFormat(''), isFalse); + }); +} diff --git a/server/test/net/visibility_test.dart b/server/test/net/visibility_test.dart new file mode 100644 index 0000000..47fddd5 --- /dev/null +++ b/server/test/net/visibility_test.dart @@ -0,0 +1,143 @@ +/// Phase 2: the server-side visibility layer — per-connection state +/// serialization with the initiative rule (PLAN.md section 3.4). +library; + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/commands/add_standee_command.dart'; +import 'package:x_haven_server/core/commands/draw_command.dart'; +import 'package:x_haven_server/core/commands/set_init_command.dart'; +import 'package:x_haven_server/core/commands/set_scenario_command.dart'; +import 'package:x_haven_server/core/enums.dart'; +import 'package:x_haven_server/core/game_data.dart'; +import 'package:x_haven_server/core/save_store.dart'; +import 'package:x_haven_server/core/service_locator.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/net/visibility.dart'; + +import 'ws_test_helpers.dart' show TestClient; + +void main() { + late GameState gs; + + /// Boots the engine and moves it to a two-character round in + /// [RoundState.chooseInitiative], with both initiative values entered. + Future bootChooseInitiative() async { + setupCore(saveStore: InMemorySaveStore()); + gs = getIt(); + gs.init(); + await getIt().loadData('assets/testData/'); + gs.load(); + gs.clearList(); + + gs.action(SetScenarioCommand('custom', false, gameState: gs)); + gs.action(AddCharacterCommand('Blinkblade', 'Frosthaven', 'Blinky', 1)); + gs.action(AddCharacterCommand('Banner Spear', 'Frosthaven', 'Spear', 1)); + gs.action( + AddMonsterCommand('Ancient Artillery (FH)', 2, false, gameState: gs), + ); + gs.action( + AddStandeeCommand( + 1, + null, + 'Ancient Artillery (FH)', + MonsterType.normal, + false, + gameState: gs, + ), + ); + gs.action(SetInitCommand('Blinkblade', 5, gameState: gs)); + gs.action(SetInitCommand('Banner Spear', 3, gameState: gs)); + addTearDown(getIt.reset); + } + + SessionContext context(String sessionId, Map seats) => + SessionContext(sessionId: sessionId, seats: seats); + + test('during chooseInitiative the owner sees their own initiative only', + () async { + await bootChooseInitiative(); + expect(gs.roundState, RoundState.chooseInitiative); + + final seats = {'Blinkblade': 'alice', 'Banner Spear': 'bob'}; + + final aliceView = serializeState(gs, context('alice', seats)); + expect(TestClient.initiativeIn(aliceView, 'Blinkblade'), 5); + expect( + TestClient.initiativeIn(aliceView, 'Banner Spear'), + null, + reason: 'bob\'s value is masked for alice', + ); + + final bobView = serializeState(gs, context('bob', seats)); + expect(TestClient.initiativeIn(bobView, 'Banner Spear'), 3); + expect(TestClient.initiativeIn(bobView, 'Blinkblade'), null); + + // Non-owner sessions — players and spectators alike — see no values. + final carolView = serializeState(gs, context('carol', seats)); + expect(TestClient.initiativeIn(carolView, 'Blinkblade'), null); + expect(TestClient.initiativeIn(carolView, 'Banner Spear'), null); + }); + + test('unclaimed characters are masked for everyone', () async { + await bootChooseInitiative(); + + final aliceView = serializeState(gs, context('alice', {})); + expect(TestClient.initiativeIn(aliceView, 'Blinkblade'), null); + expect(TestClient.initiativeIn(aliceView, 'Banner Spear'), null); + }); + + test('once playTurns starts, initiative is public in every serialization', + () async { + await bootChooseInitiative(); + gs.action(DrawCommand(gameState: gs)); + expect(gs.roundState, RoundState.playTurns); + + final seats = {'Blinkblade': 'alice', 'Banner Spear': 'bob'}; + for (final sessionId in ['alice', 'bob', 'carol']) { + final view = serializeState(gs, context(sessionId, seats)); + expect(TestClient.initiativeIn(view, 'Blinkblade'), 5, reason: sessionId); + expect( + TestClient.initiativeIn(view, 'Banner Spear'), + 3, + reason: sessionId, + ); + } + }); + + test('serializations are independent — masking one cannot leak into another', + () async { + await bootChooseInitiative(); + final seats = {'Blinkblade': 'alice'}; + + final aliceView = serializeState(gs, context('alice', seats)); + final spectatorView = serializeState(gs, context('carol', seats)); + + // Mask the spectator copy after the fact: the owner copy is untouched. + final reMasked = serializeState(gs, context('carol', seats)); + expect(TestClient.initiativeIn(reMasked, 'Blinkblade'), null); + expect(TestClient.initiativeIn(aliceView, 'Blinkblade'), 5); + expect( + TestClient.initiativeIn(spectatorView, 'Blinkblade'), + null, + reason: 'the spectator copy is not affected by re-serializing', + ); + // The live state is never mutated by serialization. + expect(gs.currentList.firstWhere((i) => i.id == 'Blinkblade'), isA()); + }); + + test('non-initiative fields are never masked', () async { + await bootChooseInitiative(); + final seats = {'Blinkblade': 'alice', 'Banner Spear': 'bob'}; + + final carolView = serializeState(gs, context('carol', seats)); + final blinkblade = + TestClient.characterIn(carolView, 'Blinkblade') + as Map; + final characterState = blinkblade['characterState'] as Map; + expect(characterState['health'], isA()); + expect(characterState['maxHealth'], isA()); + expect(blinkblade['characterClass'], 'Blinkblade'); + }); +} diff --git a/server/test/net/ws_test_helpers.dart b/server/test/net/ws_test_helpers.dart new file mode 100644 index 0000000..cb8af67 --- /dev/null +++ b/server/test/net/ws_test_helpers.dart @@ -0,0 +1,246 @@ +// ignore_for_file: avoid-late-keyword, avoid-top-level-members-in-tests + +/// Shared helpers for the Phase 2 network tests: a [TestGameServer] that +/// boots the real engine + real HTTP/WebSocket stack on an ephemeral port, +/// and a [TestClient] that drives a real WebSocket connection with a +/// message queue. +library; + +import 'dart:async'; +import 'dart:collection'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:collection/collection.dart'; +import 'package:web_socket_channel/web_socket_channel.dart'; +import 'package:x_haven_server/core/game_data.dart'; +import 'package:x_haven_server/core/save_store.dart'; +import 'package:x_haven_server/core/service_locator.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/net/app.dart'; +import 'package:x_haven_server/net/game_server.dart'; +import 'package:x_haven_server/net/protocol.dart'; +import 'package:x_haven_server/net/seat_store.dart'; +import 'package:x_haven_server/net/sessions.dart'; + +/// Boots the engine (test data) and a [GameServer] on an ephemeral port. +class TestGameServer { + TestGameServer._(); + + /// The Dart [HttpServer] on an ephemeral port (port 0). + late HttpServer server; + late GameServer gameServer; + late GameState gameState; + late SessionManager sessions; + late SeatStore seatStore; + + static Future boot({ + SaveStore? saveStore, + SeatStore? seatStore, + Duration heartbeatInterval = const Duration(seconds: 20), + Duration deadTimeout = const Duration(seconds: 90), + String dataDir = 'assets/testData/', + }) async { + // Same bootstrap as test/command/test_helpers.dart's setUpGame(), but + // with the caller's [saveStore] (persistence tests pass a FileSaveStore). + setupCore(saveStore: saveStore ?? InMemorySaveStore()); + final gs = getIt(); + gs.init(); + await getIt().loadData(dataDir); + gs.load(); + final instance = TestGameServer._(); + instance.gameState = gs; + instance.sessions = SessionManager(); + instance.seatStore = seatStore ?? InMemorySeatStore(); + instance.gameServer = GameServer( + gameState: gs, + sessions: instance.sessions, + seatStore: instance.seatStore, + heartbeatInterval: heartbeatInterval, + deadTimeout: deadTimeout, + ); + instance.server = await startServer( + port: 0, + staticDir: 'nonexistent-static-dir', + gameServer: instance.gameServer, + ); + return instance; + } + + /// The `ws://` base url for [TestClient.connect]. + Uri get wsUrl => Uri.parse('ws://localhost:${server.port}/ws'); + + /// The `http://` base url for HTTP helpers. + Uri get httpUrl => Uri.parse('http://localhost:${server.port}'); + + /// Stops the heartbeat, closes the HTTP server, and resets the DI + /// container so the next test can boot a fresh engine. + Future shutdown() async { + gameServer.dispose(); + await server.close(force: true); + await getIt.reset(); + } +} + +/// A fake WS client: a real [WebSocketChannel] with a message queue and +/// typed send helpers. +class TestClient { + TestClient._(this.channel); + + final WebSocketChannel channel; + final Queue> _queue = Queue(); + final List>> _waiters = []; + Completer? _closedCompleter; + bool closed = false; + + static Future connect(Uri url, {String? session}) async { + final uri = + session == null + ? url + : url.replace(queryParameters: {'session': session}); + final channel = WebSocketChannel.connect(uri); + final client = TestClient._(channel); + channel.stream.listen( + (Object? raw) { + final dynamic decoded = jsonDecode(raw as String); + if (decoded is Map) client._deliver(decoded); + }, + onDone: client._markClosed, + onError: (Object _) => client._markClosed(), + ); + await channel.ready; + return client; + } + + void _deliver(Map message) { + final waiter = _waiters.isNotEmpty ? _waiters.removeAt(0) : null; + if (waiter != null) { + waiter.complete(message); + } else { + _queue.add(message); + } + } + + void _markClosed() { + if (closed) return; + closed = true; + _closedCompleter?.complete(); + for (final waiter in _waiters) { + waiter.completeError(StateError('connection closed')); + } + _waiters.clear(); + } + + // --- sending ------------------------------------------------------------- + + void send(Map message) => + channel.sink.add(jsonEncode(message)); + + void sendHello({int version = Protocol.version}) => + send(Protocol.helloMessage()); + + void sendCmd(String name, [Map args = const {}]) => + send(Protocol.commandMessage(name, args)); + + void sendClaim(String characterId) => send(Protocol.claimMessage(characterId)); + + void sendRaw(String raw) => channel.sink.add(raw); + + /// Closes the socket from the client side. + Future close() => channel.sink.close(); + + /// Completes when the connection is closed (by either side). + Future get closedFuture => (_closedCompleter ??= Completer()).future; + + // --- receiving ----------------------------------------------------------- + + /// The next message, with a timeout. + Future> next({ + Duration timeout = const Duration(seconds: 10), + }) async { + if (_queue.isNotEmpty) return _queue.removeFirst(); + final completer = Completer>(); + _waiters.add(completer); + return completer.future.timeout( + timeout, + onTimeout: () => + throw TimeoutException('waiting for a message', timeout), + ); + } + + /// The next message satisfying [test]; earlier non-matching messages are + /// kept (in order) for later [next] calls. + Future> nextWhere( + bool Function(Map) test, { + Duration timeout = const Duration(seconds: 10), + String why = '', + }) async { + final skipped = >[]; + while (true) { + final Map message; + if (_queue.isNotEmpty) { + message = _queue.removeFirst(); + } else { + final completer = Completer>(); + _waiters.add(completer); + try { + message = await completer.future.timeout( + timeout, + onTimeout: () => + throw TimeoutException('nextWhere($why)', timeout), + ); + } catch (_) { + _waiters.remove(completer); + rethrow; + } + } + if (test(message)) { + _queue.addAll(skipped); + return message; + } + skipped.add(message); + } + } + + /// The next message of type [type] (e.g. `'update'`, `'seats'`). + Future> nextOf( + String type, { + Duration timeout = const Duration(seconds: 10), + }) => + nextWhere((m) => m['t'] == type, timeout: timeout, why: type); + + /// Drains and returns all messages currently buffered. + List> flush() { + final result = _queue.toList(); + _queue.clear(); + return result; + } + + // --- convenience ----------------------------------------------------------- + + /// The character entry of [characterId] in a state payload. + static Map? characterIn( + Map state, + String characterId, + ) { + final list = state['currentList']; + if (list is! List) return null; + return list.firstWhereOrNull( + (item) => item is Map && item['id'] == characterId, + ) as Map?; + } + + /// The initiative value as delivered on the wire for [characterId] + /// (null = masked or absent). + static int? initiativeIn(Map state, String characterId) { + final character = characterIn(state, characterId); + final characterState = character?['characterState']; + if (characterState is! Map) return null; + final initiative = characterState['initiative']; + return initiative is int ? initiative : null; + } + + /// The seats payload of a `seats` (or `welcome`) message. + static Map seatsOf(Map message) => + Map.from(message['seats'] as Map); +} diff --git a/server/test/smoke_test.dart b/server/test/smoke_test.dart deleted file mode 100644 index 2ac745e..0000000 --- a/server/test/smoke_test.dart +++ /dev/null @@ -1,115 +0,0 @@ -import 'dart:async'; -import 'dart:convert'; -import 'dart:io'; - -import 'package:test/test.dart'; -import 'package:web_socket_channel/web_socket_channel.dart'; -import 'package:x_haven_server/net/app.dart'; - -/// Reads messages from a [WebSocketChannel] one at a time. The channel's -/// stream is single-subscription, so this reader holds the one subscription -/// for the test's lifetime. -class _MessageReader { - final WebSocketChannel channel; - final StreamIterator> _iterator; - - _MessageReader(this.channel) - : _iterator = StreamIterator( - channel.stream.map( - (Object? raw) => jsonDecode(raw as String) as Map, - ), - ); - - Future> next() async { - final advanced = await _iterator.moveNext().timeout( - const Duration(seconds: 5), - ); - if (!advanced) { - fail('connection closed before the expected message arrived'); - } - return _iterator.current; - } - - Future dispose() => _iterator.cancel(); -} - -void main() { - late HttpServer server; - - setUp(() async { - server = await startServer(port: 0, staticDir: 'nonexistent-static-dir'); - }); - - tearDown(() async { - await server.close(force: true); - }); - - WebSocketChannel connect() { - final channel = WebSocketChannel.connect( - Uri.parse('ws://localhost:${server.port}/ws'), - ); - addTearDown(() => unawaited(channel.sink.close())); - return channel; - } - - test('serves a stub page at / when the static dir is missing', () async { - final client = HttpClient(); - addTearDown(client.close); - final request = await client.getUrl( - Uri.parse('http://localhost:${server.port}/'), - ); - final response = await request.close(); - expect(response.statusCode, 200); - final body = await response.transform(utf8.decoder).join(); - expect(body, contains('X-Haven server')); - }); - - test('answers healthz', () async { - final client = HttpClient(); - addTearDown(client.close); - final request = await client.getUrl( - Uri.parse('http://localhost:${server.port}/healthz'), - ); - final response = await request.close(); - expect(response.statusCode, 200); - final body = jsonDecode(await response.transform(utf8.decoder).join()); - expect(body, {'status': 'ok'}); - }); - - test('answers hello with welcome', () async { - final channel = connect(); - final reader = _MessageReader(channel); - addTearDown(reader.dispose); - - channel.sink.add(jsonEncode({'t': 'hello', 'v': 1})); - final welcome = await reader.next(); - expect(welcome['t'], 'welcome'); - expect(welcome['v'], 1); - expect(welcome['role'], 'spectator'); - expect(welcome['index'], 0); - expect(welcome['state'], isEmpty); - expect(welcome['seats'], isEmpty); - expect(welcome['session'], isNotEmpty); - }); - - test('answers ping with pong', () async { - final channel = connect(); - final reader = _MessageReader(channel); - addTearDown(reader.dispose); - - channel.sink.add(jsonEncode({'t': 'ping'})); - expect(await reader.next(), {'t': 'pong'}); - }); - - test('rejects malformed and unknown messages with error', () async { - final channel = connect(); - final reader = _MessageReader(channel); - addTearDown(reader.dispose); - - channel.sink.add('this is not json'); - expect((await reader.next())['code'], 'badRequest'); - - channel.sink.add(jsonEncode({'t': 'warpSpeed'})); - expect((await reader.next())['code'], 'unknownMessage'); - }); -} -- cgit v1.3.1