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/app.dart | 146 +++++++++++++++--------------------------------- 1 file changed, 46 insertions(+), 100 deletions(-) (limited to 'server/lib/net/app.dart') 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) { -- cgit v1.3.1