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/ws_upgrade.dart | 138 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 138 insertions(+) create mode 100644 server/lib/net/ws_upgrade.dart (limited to 'server/lib/net/ws_upgrade.dart') 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)}

+ + +''', +); -- cgit v1.3.1