diff options
| author | Joel Klinghed <the_jk@spawned.biz> | 2026-11-13 00:04:16 +0100 |
|---|---|---|
| committer | Joel Klinghed <the_jk@spawned.biz> | 2026-11-13 00:04:16 +0100 |
| commit | 3ebbdf6ffa16f751c82e3bd2e74294f4fe843155 (patch) | |
| tree | db4c92ce26f274073453e2a085af3105be823f74 /server/lib/net/ws_upgrade.dart | |
| parent | 808294adad3f378ad8d66b698acf8df7f49c2302 (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/ws_upgrade.dart')
| -rw-r--r-- | server/lib/net/ws_upgrade.dart | 138 |
1 files changed, 138 insertions, 0 deletions
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> +''', +); |
