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/lib/net/sessions.dart | 134 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 134 insertions(+) create mode 100644 server/lib/net/sessions.dart (limited to 'server/lib/net/sessions.dart') 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); +} -- cgit v1.3.1