summaryrefslogtreecommitdiff
path: root/server/lib/net/ws_upgrade.dart
blob: 18e2f5e967a6290c6f9b7012c1e2950616ee9378 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
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>
''',
);