From f6955e34489c79f6d5b764cb6a39b1387366b433 Mon Sep 17 00:00:00 2001 From: Joel Klinghed Date: Sun, 8 Nov 2026 21:56:29 +0100 Subject: Phase 0: project scaffolding - server/: Dart game-server package (shelf + WebSocket) with the hello/welcome handshake, ping/pong, error responses, healthz, static SPA serving with SPA fallback, and smoke tests (5/5) - web/: Svelte 5 + TypeScript SPA with the protocol client, connection-status page, vitest and svelte-check; Vite dev server proxies /ws to the Dart server - game data assets copied from the read-only reference app into server/assets/ (data, images, i18n, fonts, testData) - PLAN.md implementation plan and progress tracker; README rewritten for the web app; AGPLv3 LICENSE inherited from the reference app; .gitignore; scripts/ci.sh (full pipeline) - CLAUDE.md project guidance Verified: scripts/ci.sh passes end-to-end; live smoke confirms the server serves the built SPA at / and answers a WebSocket hello with a welcome message. --- server/lib/net/app.dart | 154 +++++++++++++++++++++++++++++++++++++++++++ server/lib/net/protocol.dart | 73 ++++++++++++++++++++ 2 files changed, 227 insertions(+) create mode 100644 server/lib/net/app.dart create mode 100644 server/lib/net/protocol.dart (limited to 'server/lib') diff --git a/server/lib/net/app.dart b/server/lib/net/app.dart new file mode 100644 index 0000000..db501e4 --- /dev/null +++ b/server/lib/net/app.dart @@ -0,0 +1,154 @@ +/// 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). +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; +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'; + +final _log = Logger('server'); + +/// Builds the HTTP handler for the game server. +Handler createHandler({required String staticDir}) { + 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.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; +} + +Map? _decodeMessage(String text) { + try { + final dynamic decoded = jsonDecode(text); + return decoded is Map ? decoded : null; + } catch (_) { + return null; + } +} + +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(); +} + +Handler _createStaticHandler(String staticDir) { + final directory = Directory(staticDir); + if (!directory.existsSync()) { + _log.info('static dir $staticDir not found; serving stub page'); + return (Request request) => Response.ok( + '' + 'X-Haven' + '' + '

X-Haven server

' + '

Running, but the web app is not built yet. ' + 'Run npm run build in web/ and restart ' + 'with --static-dir ../web/dist.

'); + } + final staticHandler = + createStaticHandler(directory.path, defaultDocument: 'index.html'); + return (Request request) async { + final response = await staticHandler(request); + if (response.statusCode == 404 && + request.method == 'GET' && + !request.url.path.contains('.')) { + // SPA fallback: routes without a file extension get index.html. + final indexFile = File(p.join(directory.path, 'index.html')); + if (await indexFile.exists()) { + return Response.ok(await indexFile.readAsString(), + headers: {'content-type': 'text/html; charset=utf-8'}); + } + } + return response; + }; +} + +Middleware _logRequests() { + return (Handler inner) { + return (Request request) async { + final stopwatch = Stopwatch()..start(); + final response = await inner(request); + stopwatch.stop(); + _log.info( + '${request.method} ${request.requestedUri.path} -> ' + '${response.statusCode} (${stopwatch.elapsedMilliseconds}ms)'); + return response; + }; + }; +} diff --git a/server/lib/net/protocol.dart b/server/lib/net/protocol.dart new file mode 100644 index 0000000..e8135e9 --- /dev/null +++ b/server/lib/net/protocol.dart @@ -0,0 +1,73 @@ +/// JSON wire protocol for X-Haven, shared by the server, its tests and (via +/// mirrored types) the web client. +/// +/// See PLAN.md section 3.5 for the protocol design. Phase 0 implements the +/// handshake (hello/welcome/ping/pong/error); the rest of the message types +/// are declared here and added to in later phases. +library; + +/// Protocol message type identifiers. +abstract class Protocol { + Protocol._(); + + static const int version = 1; + + // Client -> server message types. + static const String hello = 'hello'; + static const String claim = 'claim'; + static const String cmd = 'cmd'; + static const String undo = 'undo'; + static const String redo = 'redo'; + static const String ping = 'ping'; + + // Server -> client message types. + static const String welcome = 'welcome'; + static const String update = 'update'; + static const String seats = 'seats'; + static const String error = 'error'; + static const String pong = 'pong'; + + // Roles. + static const String roleSpectator = 'spectator'; + static const String rolePlayer = 'player'; + + /// Error codes. + static const String errBadRequest = 'badRequest'; + static const String errUnknownMessage = 'unknownMessage'; + static const String errRejected = 'rejected'; + static const String errProtocol = 'protocol'; + + /// First client message: the handshake. The session id rides in a cookie + /// (Phase 2); in Phase 0 the server assigns a throwaway session. + static Map helloMessage() => {'t': hello, 'v': version}; + + /// Full state snapshot for a new (or reconnecting) connection. [state] is + /// already serialized for this connection, i.e. with that connection's + /// secrets included and everyone else's masked (PLAN.md section 3.4). + static Map welcomeMessage({ + required String session, + required String role, + required int index, + required Map state, + required Map seats, + String? description, + Object? event, + }) { + return { + 't': welcome, + 'v': version, + 'session': session, + 'role': role, + 'index': index, + 'description': description, + 'event': event, + 'state': state, + 'seats': seats, + }; + } + + static Map errorMessage(String code, String message) => + {'t': error, 'code': code, 'message': message}; + + static Map pongMessage() => {'t': pong}; +} -- cgit v1.3.1