summaryrefslogtreecommitdiff
path: root/server/lib/net
diff options
context:
space:
mode:
authorJoel Klinghed <the_jk@spawned.biz>2026-11-13 00:04:16 +0100
committerJoel Klinghed <the_jk@spawned.biz>2026-11-13 00:04:16 +0100
commit3ebbdf6ffa16f751c82e3bd2e74294f4fe843155 (patch)
treedb4c92ce26f274073453e2a085af3105be823f74 /server/lib/net
parent808294adad3f378ad8d66b698acf8df7f49c2302 (diff)
Phase 2: networking, sessions, secrets over WebSocket (M2)
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.
Diffstat (limited to 'server/lib/net')
-rw-r--r--server/lib/net/app.dart146
-rw-r--r--server/lib/net/game_server.dart567
-rw-r--r--server/lib/net/protocol.dart66
-rw-r--r--server/lib/net/seat_store.dart79
-rw-r--r--server/lib/net/sessions.dart134
-rw-r--r--server/lib/net/visibility.dart116
-rw-r--r--server/lib/net/ws_upgrade.dart138
7 files changed, 1140 insertions, 106 deletions
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<String, String> 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<HttpServer> 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<String, dynamic>? 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<int>) return utf8.decode(raw, allowMalformed: true);
- return null;
+Future<HttpServer> 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<String, dynamic>? _decodeMessage(String text) {
- try {
- final dynamic decoded = jsonDecode(text);
- return decoded is Map<String, dynamic> ? 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<String, dynamic> 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<String, dynamic> 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<String, List<_Connection>> _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<int>(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<String, dynamic>? 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<int>) return utf8.decode(raw, allowMalformed: true);
+ return null;
+ }
+
+ Map<String, dynamic>? _decodeMessage(String text) {
+ try {
+ final dynamic decoded = jsonDecode(text);
+ return decoded is Map<String, dynamic> ? 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<String, dynamic> 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<String, dynamic> _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<String, dynamic> 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<String, dynamic> 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<String, dynamic>
+ ? rawArgs
+ : const <String, dynamic>{};
+
+ 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<String, dynamic> _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<Character>()
+ .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 = <String, List<String>>{};
+ 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<Character>()
+ .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<String, dynamic> 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<String, dynamic> 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<String, dynamic> commandMessage(
+ String name, [
+ Map<String, dynamic> 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<String, dynamic> 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<String, dynamic> updateMessage({
+ required int index,
+ required String description,
+ required Object? event,
+ required Map<String, dynamic> 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<String, dynamic> seatsMessage(Map<String, String?> seatsTable) => {
+ 't': seats,
+ 'seats': seatsTable,
+ };
+
static Map<String, dynamic> 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<String, List<String>>? read();
+
+ /// Writes the full seat table.
+ void write(Map<String, List<String>> seats);
+
+ /// Removes the stored seat table.
+ void clear();
+}
+
+/// In-memory [SeatStore] — used by tests.
+class InMemorySeatStore implements SeatStore {
+ Map<String, List<String>>? _seats;
+
+ @override
+ Map<String, List<String>>? read() => _seats;
+
+ @override
+ void write(Map<String, List<String>> seats) =>
+ _seats = Map<String, List<String>>.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<String, List<String>>? read() {
+ if (!_file.existsSync()) return null;
+ try {
+ final data = jsonDecode(_file.readAsStringSync()) as Map<String, dynamic>;
+ 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<String, List<String>> 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<String> 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<String, SessionRecord> _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<String> release(String id) {
+ final record = _sessions[id];
+ if (record == null) return const {};
+ final released = Set<String>.of(record.ownedCharacters);
+ record.ownedCharacters.clear();
+ return released;
+ }
+
+ /// character id → owning session id (owned characters only).
+ Map<String, String> seats() {
+ final result = <String, String>{};
+ 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<String, String?> seatsForState(GameState state) {
+ final owned = seats();
+ final result = <String, String?>{};
+ 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<SessionRecord> 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<String, String> 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<String, dynamic> 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<VisibilityRule> 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<String, dynamic> 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<Object?, Object?>)['initiative'] = null;
+ }
+ }
+}
+
+/// Serializes [state] for the [context] connection: a deep copy of
+/// `state.toJson()` with every not-yet-revealed visibility rule applied.
+Map<String, dynamic> serializeState(
+ GameState state,
+ SessionContext context, {
+ List<VisibilityRule>? 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<String, dynamic>;
+ 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<String>? 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: '''
+<!doctype html>
+<html>
+ <head><title>${htmlEscape.convert(title)}</title></head>
+ <body>
+ <h1>${htmlEscape.convert(title)}</h1>
+ <p>${htmlEscape.convert(message)}</p>
+ </body>
+</html>
+''',
+);