diff options
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> +''', +); |
