diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6a03dcc6..26e3da8c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -7,9 +7,10 @@ # 5. pushes ghcr.io//rylween:X.Y.Z and :latest, for linux/amd64 and linux/arm64, # 6. commits X.Y.(Z+1)-SNAPSHOT as "Start X.Y.(Z+1)-SNAPSHOT", and pushes both commits to # main together with the tag, -# 7. publishes the GitHub release vX.Y.Z with the zip and a compose.yaml that runs the image. +# 7. publishes the GitHub release vX.Y.Z with the zip, a compose.yaml that runs the image, and +# a compose.https.yaml that runs it behind Caddy and HTTPS. # A dry run, which works from any branch, does all of that but push and publish, and keeps the -# zip and compose.yaml as workflow artifacts instead. +# zip and compose files as workflow artifacts instead. # # main takes only pull requests, so the release pushes over SSH with a deploy key, kept in the # RELEASE_DEPLOY_KEY secret, that the "Require PRs and CI on main" ruleset lets bypass that. @@ -217,8 +218,8 @@ jobs: run: git push --atomic origin HEAD:refs/heads/main "refs/tags/v$RELEASE" # The checked-in compose.yaml builds the image from a checkout. The release's copy pulls - # this release's image instead. - - name: Write the release's compose.yaml + # this release's image instead, and its compose.https.yaml pins that image too. + - name: Write the release's compose files run: | { echo "# Adventurers of Rylween $RELEASE. \`docker compose up -d\` next to this file pulls" @@ -228,6 +229,12 @@ jobs: '.services.rylween.image = strenv(IMAGE) + ":" + strenv(RELEASE) | del(.services.rylween.build)' \ deploy/compose.yaml } > "$DIST/compose.yaml" + { + echo "# Adventurers of Rylween $RELEASE over HTTPS: runs $IMAGE:$RELEASE behind Caddy." + echo "# Set RYLWEEN_DOMAIN in .env next to this file, then: docker compose -f compose.https.yaml up -d" + echo "#" + yq --indent 4 '.services.rylween.image = strenv(IMAGE) + ":" + strenv(RELEASE)' deploy/compose.https.yaml + } > "$DIST/compose.https.yaml" - name: Publish the GitHub release if: ${{ !inputs.dry-run }} @@ -248,6 +255,13 @@ jobs: Or download \`compose.yaml\` and run \`docker compose up -d\` next to it. Its header lists the settings. + ## Host it on the internet over HTTPS + + Download \`compose.https.yaml\`, set \`RYLWEEN_DOMAIN\` (and \`RYLWEEN_ADMIN_PASSWORD\`) in a \`.env\` file + next to it, and run \`docker compose -f compose.https.yaml up -d\`. Caddy gets the certificate from + Let's Encrypt. [deploy/README.md](https://github.com/lagergren/rylween/blob/v$RELEASE/deploy/README.md#on-the-internet-over-https) + covers what the host needs, from DNS and ports on. + ## Play the ANSI game in a terminal Download \`rylween-terminal-$RELEASE.zip\`, unzip it, and run \`rylween-terminal-$RELEASE/bin/rylween\`. @@ -260,7 +274,8 @@ jobs: --notes-file "$RUNNER_TEMP/notes.md" \ --generate-notes \ "$DIST/rylween-terminal-$RELEASE.zip" \ - "$DIST/compose.yaml" + "$DIST/compose.yaml" \ + "$DIST/compose.https.yaml" - name: Keep the dry run's downloads if: ${{ inputs.dry-run }} diff --git a/README.md b/README.md index 3bc10453..6b8ad414 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,11 @@ style game for BBSes that I wrote in 1992-1993. The same game plays in two ways: as the original ANSI version in a terminal, and as a repainted bitmap version in the browser. +[Play it](#running-the-game) in a browser or a terminal, host it for others +with [`deploy/README.md`](deploy/README.md), change the game with the +[DSL authoring guide](docs/dsl-authoring.md), or start on the code at +[The Code](#the-code). +

The bitmap version in the town of Thord: a painting of the lamplit main street at night next to the town menu, in a carved bronze frame with torches, skulls, and a scorpion

@@ -82,45 +87,21 @@ brew install --cask docker # or Docker Desktop; start i ./deploy.sh ``` -This is the one command for hosting the game. `deploy.sh` is a link to -`deploy/deploy-rylween.sh`, so inside `deploy/` the same command is -`./deploy-rylween.sh`; either works from any directory. It builds the bitmap web -game's image and starts it with Docker Compose (Podman Compose when Docker is -missing), published on this machine's private LAN address, port 8081. After the -build output it waits until the server answers, then prints the address and the -commands for the sysop password, the server log, and stopping the server: - -```text -Rylween is up on http://192.168.1.20:8081/ - Sysop password: docker compose -f /path/to/rylween/deploy/compose.yaml exec rylween cat /data/auth/admin-password.txt - Server log: docker compose -f /path/to/rylween/deploy/compose.yaml logs -f rylween - Stop: docker compose -f /path/to/rylween/deploy/compose.yaml down -``` - -Open the address in a browser on any machine on the network and register an -account. The build runs inside the image, so the host needs only Docker or -Podman, not a JDK. +From a checkout, this builds the bitmap game's image, starts it with Docker +Compose (Podman Compose when Docker is missing) on this machine's LAN address, +port 8081, and waits until it answers. Then it prints the address to open on any +machine on the network, with the commands for the sysop password, the server +log, and stopping it. Saves and accounts survive rebuilds. -Run `./deploy.sh` again after pulling changes to rebuild and restart; a plain -`docker compose up` would publish on 127.0.0.1 only. Saves, accounts, and logs -live on the `rylween_data` volume and survive rebuilds; `down` stops the server -and keeps them. +### On The Internet, Over HTTPS -On first start the server creates the sysop account, `admin`, which gets the -game's secret wilderness keys. Unless `RYLWEEN_ADMIN_PASSWORD` is set, its -password is generated, and the `Sysop password` command prints it. From the -repository root (inside `deploy/`, leave out `-f deploy/compose.yaml`): - -```sh -docker compose -f deploy/compose.yaml exec rylween cat /data/auth/admin-password.txt -``` +On a machine with a public address and a domain name, `./deploy.sh --https`, +or `deploy/compose.https.yaml` on its own, runs the released game behind Caddy, +which gets a Let's Encrypt certificate for the name. -To change the port, the data location, or the accounts, copy -`deploy/.env.example` to `deploy/.env` and edit it. -[`deploy/docker/README.md`](deploy/docker/README.md) covers the settings, -backups, and the production images, and -[`runtimes/runtime-web/README.md`](runtimes/runtime-web/README.md#exposing-a-production-docker-deployment) -covers putting the game on the internet behind an HTTPS reverse proxy. +[`deploy/README.md`](deploy/README.md) covers all three ways: the settings, +data and backups, and the images, and, step by step, everything an HTTPS server +needs, from DNS and ports on. ### In A Terminal: `./bin/run.sh` @@ -130,7 +111,11 @@ covers putting the game on the internet behind an HTTPS reverse proxy. This builds the game and plays the ANSI version in the current terminal. It needs JDK 23 or newer; Gradle downloads the JDK 25 toolchain the modules build -with if none is installed. Size the terminal to at least 80 columns by 25 rows. +with if none is installed. Without a checkout, download +`rylween-terminal-X.Y.Z.zip` from the +[latest release](https://github.com/lagergren/rylween/releases/latest), unzip +it, and run its `bin/rylween`, which takes the same options and needs Java 25 +or newer. Size the terminal to at least 80 columns by 25 rows. At the splash screen press RETURN, then `N` to create a party. Move with the arrow keys or the keypad digits 8, 2, 4, and 6; press `?` in the wilderness for the full list of commands, and `X` to quit. The save and logs go to @@ -189,7 +174,7 @@ Module guides: - [`support/audio`](support/audio) - Python scripts that synthesize the sound effects, music, and ambient loops. - [`build-logic`](build-logic/README.md) - Gradle conventions and custom tasks. - [`bin`](bin/README.md) - local developer/operator launcher scripts. -- [`deploy/docker`](deploy/docker/README.md) - Docker images, compose, the LAN deploy script, and reverse-proxy notes. +- [`deploy`](deploy/README.md) - running the game as a server: compose files, Docker images, the deploy script, and HTTPS. The old interpreted Kotlin ANSI project and the historical C/JSON5 port are no longer part of this repository. The original Amiga release is kept as described diff --git a/deploy/.env.example b/deploy/.env.example index 53bd61e6..89aac834 100644 --- a/deploy/.env.example +++ b/deploy/.env.example @@ -1,7 +1,12 @@ # Example settings for `docker compose` / `podman compose`, described at the top -# of compose.yaml. Copy this file to .env (git-ignored) next to compose.yaml and -# uncomment what you change; commented lines show the defaults. Variables -# exported in the shell take precedence over .env. +# of compose.yaml and compose.https.yaml. Copy this file to .env (git-ignored) +# next to them and uncomment what you change; commented lines show the +# defaults. Variables exported in the shell take precedence over .env. + +# For ./deploy.sh --https and compose.https.yaml only: the name players open, +# whose DNS points at this machine. compose.yaml ignores it. README.md here +# explains what HTTPS needs. +# RYLWEEN_DOMAIN=rylween.example.net # Host address and port to publish on. The root ./deploy.sh detects this # machine's LAN address unless .env sets the address; plain `docker compose up` diff --git a/deploy/README.md b/deploy/README.md new file mode 100644 index 00000000..812850a8 --- /dev/null +++ b/deploy/README.md @@ -0,0 +1,578 @@ +# Deploying Rylween + +`deploy/` holds everything for running the bitmap game as a server, for +players who open it in a browser. The ANSI terminal game needs no server; see +[`bin/README.md`](../bin/README.md). + +## Which Way + +| Players are | Over | Run | The machine needs | +|---|---|---|---| +| On this machine | HTTP | the one `docker run` in the [README](../README.md#with-only-docker-or-podman) | Docker or Podman | +| On your local network | HTTP | `./deploy.sh`, with `compose.yaml` | a checkout, and Docker or Podman | +| On the internet | HTTPS | `compose.https.yaml`, or `./deploy.sh --https` | a public address, a domain name, ports 80 and 443, and Docker or Podman | + +Never put the plain HTTP setups on the internet: passwords and cookies would +cross it in plain text. + +## What Is Here + +- **`compose.yaml`** builds the bitmap game's image from the checkout and runs + it over plain HTTP, with its data on a persistent volume, published on + `127.0.0.1:8081` or, through `./deploy.sh`, on the LAN address. +- **`compose.https.yaml`** runs the released image behind Caddy, which gets the + certificate and serves HTTPS. Each GitHub release attaches a copy pinned to + that release, so an HTTPS server needs no checkout. +- **`deploy-rylween.sh`**, also `./deploy.sh` in the repository root, starts + either one and waits until it answers: `--compose`, the default, for the LAN; + `--https` for the internet; `--launcher` for the installed launcher without + Docker. +- **`.env.example`** shows the settings both compose files read from a `.env` + file next to them. +- **`docker/`** holds the Dockerfiles: + - `Dockerfile.bitmap-production` builds the bitmap game, serving port 8081. + Releases publish it as `ghcr.io/lagergren/rylween:X.Y.Z` and `:latest`, + for linux/amd64 and linux/arm64. Its builder stage runs on the build + machine's own platform, so an image for another platform needs no + emulation. + - `Dockerfile.production` builds the ANSI game for the browser, serving port + 8080, and `Dockerfile` the same for `bin/run-server.sh`. + +Build them from the repository root, which Gradle, the sources, and the root +`.dockerignore` need as the build context: + +```sh +docker build -f deploy/docker/Dockerfile.bitmap-production -t rylween-bitmap-prod . +docker build -f deploy/docker/Dockerfile.production -t rylween-web-prod . +``` + +Every image serves plain HTTP inside the container and keeps saves, accounts, +and logs under its `/data` volume. The production images mark the login cookie +`Secure` (`RYLWEEN_AUTH_SECURE_COOKIES=true`), so browsers keep it only over +HTTPS; plain HTTP setups set it to `false`. Run directly, the bitmap image uses +an 8x8 wilderness view at 64 px per tile, while the compose files and the +launcher default to 6x6 at 68 px. Once the bitmap server accepts connections it +prints the link to open, taken from `RYLWEEN_PUBLIC_URL`, or `localhost` and its +port. + +## On Your Network, Over HTTP + +`compose.yaml` builds `Dockerfile.bitmap-production` and runs the game. Run +compose from `deploy/`, or pass `-f deploy/compose.yaml` from the repository +root: + +```sh +cd deploy +docker compose up --build -d # or: podman compose up --build -d +docker compose logs -f rylween +docker compose down # keeps the volume +``` + +On macOS with Podman, start its VM first with `podman machine start`. + +The container publishes on `127.0.0.1:8081` by default. To let other machines +on the local network connect, run it through the deploy script. It builds the +image, detects this machine's private LAN address, publishes on it, waits +until the server answers, and prints the address with the commands for the +sysop password, the log, and `down`: + +```sh +./deploy.sh # from the repository root +./deploy-rylween.sh # from deploy/; the same script +``` + +```text +Rylween is up on http://192.168.1.20:8081/ + Sysop password: docker compose -f /path/to/rylween/deploy/compose.yaml exec rylween cat /data/auth/admin-password.txt + Server log: docker compose -f /path/to/rylween/deploy/compose.yaml logs -f rylween + Stop: docker compose -f /path/to/rylween/deploy/compose.yaml down +``` + +The build runs inside the image, so the host needs only Docker or Podman, not +a JDK. Run `./deploy.sh` again after pulling changes to rebuild and restart; a +plain `docker compose up` would publish on `127.0.0.1` only. + +Or set `RYLWEEN_PUBLISH_HOST` yourself, to a LAN address such as `192.168.x.y` +or to `0.0.0.0`; `RYLWEEN_HOST_PORT` changes the port. When `deploy/.env` sets +`RYLWEEN_PUBLISH_HOST`, the deploy script uses that address instead of +detecting one. Compose sets `RYLWEEN_AUTH_SECURE_COOKIES=false`, so logins work +over plain HTTP. All settings are listed at the top of `compose.yaml` and can +be kept in an uncommitted `deploy/.env`; copy `deploy/.env.example`, which +shows each one at its default. + +Saves, accounts, and logs live on the `rylween_data` volume. They survive +`down`, rebuilds, and image updates; only `down -v` or `volume rm` deletes +them. To keep them in a host directory instead, for example to back them up +with `bin/backup-web-data.sh`, point `RYLWEEN_DATA_VOLUME` at it. A relative +path such as `./data` is relative to `deploy/`. From the repository root: + +```sh +mkdir -p ~/.rylween/compose-data +echo 'RYLWEEN_DATA_VOLUME=~/.rylween/compose-data' >> deploy/.env +./deploy.sh +bin/backup-web-data.sh --data ~/.rylween/compose-data --output rylween-backup.tar.gz +``` + +On first start the server creates the sysop account (`RYLWEEN_ADMIN_ACCOUNT`, +default `admin`), which gets the game's secret wilderness keys and which +players cannot register. Unless `RYLWEEN_ADMIN_PASSWORD` is set, its generated +password is saved in `/data/auth/admin-password.txt`: + +```sh +docker compose exec rylween cat /data/auth/admin-password.txt +``` + +### Without Docker: `--launcher` + +`./deploy.sh --launcher` starts the installed bitmap launcher in the background +instead, with its own data directory, `~/.rylween/deploy`, and its log in +`/tmp/rylween-bitmap-web-deploy.log`. Build the launcher first: + +```sh +./gradlew :runtime-bitmap-web:installRuntimeBitmapWeb --console=plain +./deploy.sh --launcher +``` + +It binds to the private LAN address of the interface carrying the default +route, so other machines on the network can connect without it listening on +every interface, and it refuses to pick a public address on its own. It prints +the address, for example `http://192.168.1.20:8081`. Rerunning it stops the +server it started before, and it refuses to start when the launcher is not +installed. On Linux it uses `ip`, `/proc`, and `setsid`; on macOS, `route`, +`ifconfig`, `ps`, and `nohup`. + +`RYLWEEN_DEPLOY_HOST` sets the bind address instead, such as `127.0.0.1`. Use +`0.0.0.0` only when the server should listen on every IPv4 interface. +`RYLWEEN_DEPLOY_PORT`, `RYLWEEN_DEPLOY_DATA_DIR`, and `RYLWEEN_DEPLOY_LOG_FILE` +set the port (default `8081`), the data directory, and the log file, and +`RYLWEEN_DEPLOY_APP` points the script at another installed launcher. The +sysop account's generated password is in +`~/.rylween/deploy/auth/admin-password.txt`. Without `--launcher`, +`RYLWEEN_DEPLOY_HOST` still picks the address, and compose's +`RYLWEEN_HOST_PORT` and `RYLWEEN_DATA_VOLUME` take the place of the port and +data settings. + +## On The Internet, Over HTTPS + +This puts the game on a machine you control, reachable at a name such as +`https://rylween.example.net/`, with a real certificate and nothing sent in +plain text. `compose.https.yaml` runs two containers: + +```text +players' browsers + │ HTTPS, port 443 (port 80 only redirects to HTTPS + ▼ and answers Let's Encrypt's check) +Caddy ── gets and renews the certificate, adds security headers + │ plain HTTP on a private container network + ▼ +rylween ── the game server, no port published, data on the `data` volume +``` + +The game server only speaks plain HTTP. Caddy, a web server that handles +certificates on its own, terminates HTTPS in front of it. Both run from images, +so the machine needs only Docker or Podman. + +### What Is Already Provided + +The pieces: + +- **`compose.https.yaml`** runs the released game image behind Caddy. The game + publishes no port; only Caddy listens on 80 and 443. Its header lists every + setting. +- **`./deploy.sh --https`**, from a checkout, pulls the latest release, starts + `compose.https.yaml`, waits until the site answers over HTTPS with a valid + certificate, and prints the address and the commands to manage it. +- **A `compose.https.yaml` attached to each release**, pinned to that release's + image: download one file and write a `.env`. + +What the game server does, with the settings `compose.https.yaml` gives it: + +- **Secure cookies.** The login cookie is `HttpOnly`, `SameSite=Lax`, and + `Secure`, so browsers only ever send it over HTTPS. +- **Encrypted game connection.** The page opens the game's WebSocket as + `wss://` whenever it was loaded over HTTPS. +- **Same-origin check.** Any POST, such as a login or a registration, and the + game connection are refused with 403 when another site's page sends them. + The site is `RYLWEEN_PUBLIC_URL`, which the compose file sets from + `RYLWEEN_DOMAIN`. +- **Failed-login limit.** After 10 failed logins from one client within 15 + minutes, that client's logins are refused with 429 and a `Retry-After` header + until 15 minutes after the first failure. A successful login clears the + count. The counts are kept in memory, so restarting the game clears them too. +- **Real client addresses.** The server believes `X-Forwarded-For` only from the + proxies in `RYLWEEN_TRUSTED_PROXIES`. The compose file trusts the private + address ranges, since only Caddy can reach the game. Every request and every + failed login is logged with `client=
`. +- **Passwords** are stored hashed with PBKDF2-HMAC-SHA256. The sysop account is + reserved: players cannot register its name. +- **`GET /healthz`** answers `ok` without a login. + +What Caddy does: + +- Gets a certificate for `RYLWEEN_DOMAIN` from Let's Encrypt the first time it + starts, and renews it on its own well before it expires. +- Redirects every plain HTTP request to HTTPS (308). +- Adds `Strict-Transport-Security`, `X-Content-Type-Options: nosniff`, and + `Referrer-Policy: no-referrer` to every response. +- Serves HTTP/2, and HTTP/3 on UDP 443. +- Passes the game's WebSocket through, and keeps an access log. + +### What You Need + +1. **A machine that stays on.** A Linux server, a rented virtual server (VPS), + or a home server such as a Raspberry Pi 4 or 5. Both amd64 and arm64 work. + The game uses about 250 MB of memory and Caddy about 15 MB, so 1 GB of memory + is plenty. The images take about 1 GB of disk, plus room for saves and logs. + A Mac or Windows machine works for trying it out, but a server should run + Linux. +2. **A public IP address.** A VPS comes with one. At home, your router's + internet-side (WAN) address must be public. Compare the WAN address your + router shows with what `curl -4 https://ifconfig.me` prints on the machine. + If they differ, or the router's starts with `100.64` to `100.127`, your + provider shares one address among many customers (CGNAT). Then nothing from + the internet can reach you; use a VPS, or see + [Tailscale](#without-a-public-address-tailscale). A home address that + changes now and then needs a dynamic DNS name (item 3). +3. **A domain name** for players to open, such as `rylween.example.net`: a name + or subdomain at any domain registrar, or a free dynamic DNS name, such as one + from DuckDNS. Its DNS `A` record must point at the public IPv4 address. Add an + `AAAA` record only if the machine also takes IPv6 connections on ports 80 and + 443. +4. **Ports 80 and 443 open.** TCP 80 and 443, and optionally UDP 443 for + HTTP/3, must reach the machine. At home, forward them on the router. On a VPS, + open them in the provider's firewall. On the machine, allow them in its + firewall. Open nothing else for Rylween, and never port 8081. +5. **Docker or Podman.** Docker Engine with the Compose plugin is the + recommended choice: run as root, it lets the game see players' real + addresses (see [step 9](#9-check-players-addresses)). Podman 4 or newer, with + `podman compose`, works too. git is needed only for `./deploy.sh --https` from + a checkout. +6. **Certificates: nothing to do.** You don't buy, create, or copy any. Caddy + gets them from Let's Encrypt, which first checks that you control the name by + connecting to it on port 80 or 443. That is why DNS and both ports must be + right before the first start. The certificates live on Caddy's `caddy-data` + volume. Keep it: Let's Encrypt issues only a few certificates for the same + name per week. + +### Step By Step + +#### 1. Point the name at the machine + +At your registrar or DNS provider, create an `A` record from +`rylween.example.net` to the machine's public IPv4 address. Wait until it +resolves, ideally checking from another network: + +```sh +dig +short rylween.example.net # prints the public address +``` + +#### 2. Open ports 80 and 443 + +Forward TCP 80 and 443 (and UDP 443) from the router to the machine, or open +them in the VPS provider's firewall. Then allow them on the machine. With `ufw` +on Debian or Ubuntu: + +```sh +sudo ufw allow 80/tcp +sudo ufw allow 443/tcp +sudo ufw allow 443/udp +``` + +[Router and network notes](#router-and-network-notes) shows the forwarding on a +MikroTik (RouterOS) router, and what to do about IPv6. + +#### 3. Install Docker + +On Debian, Ubuntu, Fedora, Raspberry Pi OS, and most other Linux +distributions, Docker's install script sets up Docker Engine with the Compose +plugin: + +```sh +curl -fsSL https://get.docker.com | sudo sh +sudo systemctl enable --now docker +docker compose version +``` + +With Podman instead, rootless Podman may not listen on ports below 1024. +Allow it once: + +```sh +echo 'net.ipv4.ip_unprivileged_port_start=80' | sudo tee /etc/sysctl.d/90-rylween.conf +sudo sysctl --system +``` + +#### 4. Get the compose file + +Without a checkout, download the release's copy into a directory of its own: + +```sh +mkdir -p ~/rylween && cd ~/rylween +curl -fLO https://github.com/lagergren/rylween/releases/latest/download/compose.https.yaml +``` + +Releases attach it from 0.9.3 on. Before that, take it from `main`: +`https://raw.githubusercontent.com/lagergren/rylween/main/deploy/compose.https.yaml`. +From a checkout, it is `deploy/compose.https.yaml`, and the steps below run in +`deploy/`. + +#### 5. Write the settings + +Put a `.env` file next to the compose file, readable only by you. It holds the +sysop password, so keep it out of shell history and version control: + +```sh +umask 077 +cat > .env <<'EOF' +RYLWEEN_DOMAIN=rylween.example.net +RYLWEEN_ADMIN_PASSWORD=replace-with-a-long-unique-secret +EOF +``` + +`RYLWEEN_ADMIN_PASSWORD` applies only when the sysop account is created, on +the first start. Without it, the server generates a password and saves it on +the data volume. The header of `compose.https.yaml` lists the other settings, +such as `RYLWEEN_VERSION` to pin a release. In a checkout, `deploy/.env` serves +both compose files, so a setting both read, such as `RYLWEEN_DATA_VOLUME`, +applies to both. + +#### 6. Start it + +```sh +docker compose -f compose.https.yaml up -d +``` + +Or, from a checkout, `./deploy.sh --https`. It pulls the latest release, +starts both containers, waits up to three minutes for a valid certificate, and +prints: + +```text +Rylween is up on https://rylween.example.net/ + Sysop password: docker compose -f .../deploy/compose.https.yaml exec rylween cat /data/auth/admin-password.txt + Server log: docker compose -f .../deploy/compose.https.yaml logs -f rylween + Proxy log: docker compose -f .../deploy/compose.https.yaml logs -f caddy + Stop: docker compose -f .../deploy/compose.https.yaml down +``` + +#### 7. Watch the certificate arrive + +```sh +docker compose -f compose.https.yaml logs -f caddy +``` + +Within a minute Caddy logs `certificate obtained successfully`. Then check +from any machine: + +```sh +curl -I https://rylween.example.net/healthz # HTTP/2 200 +curl -I http://rylween.example.net/ # 308, to https://rylween.example.net/ +``` + +#### 8. Play + +Open `https://rylween.example.net/` and register an account. The game's log +prints the link too: + +```sh +docker compose -f compose.https.yaml logs rylween | grep -A2 'is up' +``` + +The sysop account is `admin`, unless `RYLWEEN_ADMIN_ACCOUNT` names another, +with the password from `.env`, or the generated one: + +```sh +docker compose -f compose.https.yaml exec rylween cat /data/auth/admin-password.txt +``` + +#### 9. Check players' addresses + +The failed-login limit counts per client address, so the game must see real +ones. Log in from a phone on mobile data, then: + +```sh +docker compose -f compose.https.yaml logs rylween | grep -o 'client=[^ ]*' | sort | uniq -c +``` + +The phone's public address should be listed. If every line shows the same +private address instead (`10.…`, `172.16.…` to `172.31.…`, or `192.168.…`), the +container engine hides where connections come from. Rootless Podman does that, +and so does Docker when its userland proxy handles the ports. The limit then +counts every player as one client, and ten failed logins by anyone lock out +everyone for 15 minutes. Run Docker or Podman as root to fix it. + +### Running It + +- **Upgrades.** Pull and restart. Accounts, saves, and certificates stay on + their volumes: + + ```sh + docker compose -f compose.https.yaml pull + docker compose -f compose.https.yaml up -d + ``` + + `RYLWEEN_VERSION=0.9.3` in `.env` stays on one release until you change it. +- **Restarts.** Both containers restart on their own (`unless-stopped`), + including after a reboot once Docker starts at boot + (`sudo systemctl enable docker`). +- **Logs.** `docker compose -f compose.https.yaml logs rylween` shows the game's + server log. The volume also keeps it, and each session's own log, under + `/data/logs/runtime-bitmap-web/`. `docker compose -f compose.https.yaml logs caddy` + shows Caddy's access log. +- **Backups.** Archive the game's volume, which Compose names + `rylween-https_data`: + + ```sh + docker run --rm -v rylween-https_data:/data:ro -v "$PWD":/backup alpine \ + tar czf /backup/rylween-$(date +%F).tar.gz -C /data . + ``` + +- **Stopping.** `docker compose -f compose.https.yaml down` stops both and keeps + the volumes. `down -v` deletes them, with every account, save, and + certificate. +- **Banning guessers.** For more than the built-in limit, point fail2ban or a + similar tool at the game's `bitmap.auth.login_failed ... client=
` + lines. + +### What This Protects, And What It Does Not + +It protects: + +- Passwords, cookies, and play from being read or changed on the network. +- Players' sessions from other websites' pages. +- Accounts from password guessing from one address. + +It does not cover: + +- Guessing spread over many addresses. The limit is per client, so long, unique + passwords still matter, the sysop's most of all. +- Failed-login counts across restarts. They live in memory. +- A second factor. Accounts are a name, an email, and a password. +- The ANSI game for the browser (`docker/Dockerfile.production`). It has none of + the same-origin check, the login limit, or the proxy trust, so put the bitmap + game on the internet instead. +- The machine itself. Keep it updated, log in with SSH keys, and open no ports + beyond 80 and 443. + +### Troubleshooting + +- **No certificate, or `./deploy.sh --https` times out.** Caddy's log says why: + `docker compose -f compose.https.yaml logs caddy`. Usually DNS does not yet + point at the machine (`dig +short rylween.example.net`), or port 80 or 443 + does not reach it. Check from outside your network, for example + `curl -I http://rylween.example.net/` on a phone's mobile data. After repeated + failures Let's Encrypt refuses for a while; fix the cause and wait an hour. +- **`cannot expose privileged port 80`.** Rootless Podman; see step 3. +- **`cross-origin request refused` when logging in.** `RYLWEEN_DOMAIN` must be + exactly the name in the browser's address bar. +- **Logged in, but sent back to the login page.** The browser used `http://`, + which never gets the secure cookie. Open `https://`; Caddy redirects plain + HTTP there unless something in front of it stops it. +- **`Too many failed logins`.** Wait the time the page names, or clear all + counts by restarting the game: `docker compose -f compose.https.yaml restart rylween`. + +### Router And Network Notes + +On a MikroTik router running RouterOS, with interface lists named `WAN` and +`LAN`, and the machine running the compose file at the LAN address +`192.168.88.20`, forward both ports to it: + +```routeros +/ip firewall nat +add chain=dstnat in-interface-list=WAN protocol=tcp dst-port=443 \ + action=dst-nat to-addresses=192.168.88.20 to-ports=443 \ + comment="Rylween HTTPS to Caddy" +add chain=dstnat in-interface-list=WAN protocol=tcp dst-port=80 \ + action=dst-nat to-addresses=192.168.88.20 to-ports=80 \ + comment="Rylween HTTP redirect and Let's Encrypt to Caddy" +``` + +Many RouterOS default configurations already accept forwarded traffic that +was destination-NATed. If your forward chain ends in a drop rule, add a narrow +accept rule before it, after the `established,related` and `invalid` rules: + +```routeros +/ip firewall filter +add chain=forward action=accept in-interface-list=WAN \ + connection-nat-state=dstnat connection-state=new protocol=tcp \ + dst-address=192.168.88.20 dst-port=80,443 \ + comment="Allow Rylween through to Caddy" +``` + +Do not add a broad rule such as "accept all from WAN to the server", and do not +add `input` rules for Rylween: those are for services on the router itself. + +IPv6 is different from IPv4: a machine with an IPv6 address may be reachable +from the internet with no NAT in between, so IPv4 port forwarding protects +nothing there. If the machine has one, allow only TCP 80 and 443 (and UDP 443) +to it in the router's IPv6 firewall, and add the `AAAA` record only then. + +A separate network, VLAN, or router port for the server makes for a stricter +setup, but a small deployment does without one when: + +- the game is reachable only through Caddy, as `compose.https.yaml` sets it up, +- only Caddy listens on the machine's network address, +- the router forwards only ports 80 and 443 to that machine, +- the machine accepts administrative logins, such as SSH, only from your LAN + or a VPN, +- the machine, Docker, the images, and the router are kept updated, +- the game's data volume is backed up. + +### Behind A Proxy You Already Run + +With nginx, HAProxy, Traefik, or a load balancer already in front, run the +image without Caddy, published only to `127.0.0.1` or a private network, and: + +- forward WebSocket upgrades for `/ws/play`, which nginx, for one, needs told; +- set `RYLWEEN_PUBLIC_URL` to the address players open, such as + `https://rylween.example.net`; +- set `RYLWEEN_TRUSTED_PROXIES` to the proxy's address, as it connects to the + game, so the game believes its `X-Forwarded-For`; +- keep `RYLWEEN_AUTH_SECURE_COOKIES=true`, the image's default. + +### The ANSI Game In The Browser + +`docker/Dockerfile.production` packages the ANSI game for the browser, which +serves port 8080 and lets one player at a time play. It has none of the bitmap +server's same-origin check, failed-login limit, or proxy trust, so keep it to +players you know. Publish it only to `127.0.0.1`, and keep its secrets in a file +rather than on the command line, where shell history and process listings would +keep them: + +```sh +docker build -f deploy/docker/Dockerfile.production -t rylween-web-prod . +sudo install -d -m 700 /etc/rylween +sudo install -m 600 /dev/null /etc/rylween/rylween.env +sudoedit /etc/rylween/rylween.env # RYLWEEN_ADMIN_PASSWORD=... +docker run -d --name rylween-web --restart unless-stopped \ + --env-file /etc/rylween/rylween.env -p 127.0.0.1:8080:8080 \ + -v rylween-web-data:/data rylween-web-prod +``` + +Then serve it over HTTPS from Caddy installed on the machine, with a +`Caddyfile` such as: + +```caddyfile +rylween.example.net { + encode zstd gzip + reverse_proxy 127.0.0.1:8080 + header { + Strict-Transport-Security "max-age=31536000" + X-Content-Type-Options "nosniff" + Referrer-Policy "no-referrer" + } +} +``` + +Its server log is `/data/logs/web-server.log`, and each session writes +`/data/logs/-.log`. Both are echoed to its standard +output, so `docker logs rylween-web` shows them. + +### Without A Public Address: Tailscale + +If the machine cannot be reached from the internet, for example behind CGNAT, +and the players are people you can invite, Tailscale can carry the game +instead. It gives the machine an HTTPS name in your tailnet, such as +`https://rylween-host.example-tailnet.ts.net/`, with a certificate, without a +domain or open ports, and `tailscale serve` forwards it to the game on the +machine. Run the game with `RYLWEEN_AUTH_SECURE_COOKIES=true` and +`RYLWEEN_PUBLIC_URL` set to that name. This repository does not script or test +that setup; see Tailscale's documentation on `tailscale serve`. diff --git a/deploy/compose.https.yaml b/deploy/compose.https.yaml new file mode 100644 index 00000000..46fafa94 --- /dev/null +++ b/deploy/compose.https.yaml @@ -0,0 +1,86 @@ +# Runs the bitmap web game on the internet over HTTPS. Caddy answers on ports 80 +# and 443, gets a certificate for RYLWEEN_DOMAIN from Let's Encrypt and renews +# it, and forwards to the game, which publishes no port of its own. It runs the +# released image, so the host needs only Docker or Podman, this file, and a +# .env file next to it. deploy/README.md walks through it all, from DNS on. +# +# docker compose -f compose.https.yaml up -d # or: podman compose ... +# open https:/// and register an account +# +# From a checkout, ./deploy.sh --https runs it and waits until it answers. +# +# Settings, from the shell environment or .env next to this file: +# RYLWEEN_DOMAIN Required. The name players open, whose DNS points +# at this host, such as rylween.example.net. +# RYLWEEN_ADMIN_PASSWORD Password for a newly created sysop account. When +# unset, the server generates one and saves it in +# /data/auth/admin-password.txt. +# RYLWEEN_ADMIN_ACCOUNT The sysop account. Default: admin +# RYLWEEN_VERSION The release to run. Default: latest +# RYLWEEN_DATA_VOLUME Named volume or host directory for saves, +# accounts, and logs. Default: the `data` volume. +# RYLWEEN_BITMAP_STATE Initial compiled state slug. Default: fresh-replay +# RYLWEEN_BITMAP_MAP_TILES Wilderness viewport edge length. Default: 6 +# RYLWEEN_BITMAP_TILE_SIZE Wilderness tile size in px. Default: 68 +# RYLWEEN_VICTIM_ACCOUNT An account the sysop gods hunt down every 101 +# moves. Default: none + +name: rylween-https + +services: + rylween: + image: ghcr.io/lagergren/rylween:${RYLWEEN_VERSION:-latest} + restart: unless-stopped + environment: + # The link the server prints, and the origin the browser must send. + RYLWEEN_PUBLIC_URL: https://${RYLWEEN_DOMAIN:?set RYLWEEN_DOMAIN, the name players open, in .env} + RYLWEEN_AUTH_SECURE_COOKIES: "true" + # Only Caddy reaches the game, over this project's private network, so + # its X-Forwarded-For is believed: it names the player in logs and in + # the failed-login limit. + RYLWEEN_TRUSTED_PROXIES: 10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,fc00::/7 + RYLWEEN_BITMAP_STATE: ${RYLWEEN_BITMAP_STATE:-fresh-replay} + RYLWEEN_BITMAP_MAP_TILES: ${RYLWEEN_BITMAP_MAP_TILES:-6} + RYLWEEN_BITMAP_TILE_SIZE: ${RYLWEEN_BITMAP_TILE_SIZE:-68} + RYLWEEN_ADMIN_ACCOUNT: ${RYLWEEN_ADMIN_ACCOUNT:-admin} + RYLWEEN_ADMIN_PASSWORD: ${RYLWEEN_ADMIN_PASSWORD:-} + RYLWEEN_VICTIM_ACCOUNT: ${RYLWEEN_VICTIM_ACCOUNT:-} + volumes: + - ${RYLWEEN_DATA_VOLUME:-data}:/data + + caddy: + image: docker.io/library/caddy:2 + restart: unless-stopped + depends_on: + - rylween + ports: + - "80:80" + - "443:443" + # HTTP/3. + - "443:443/udp" + # Caddy's reverse-proxy command needs no Caddyfile. It keeps the Host + # header, passes the game's WebSocket through, and redirects HTTP to HTTPS. + command: + - caddy + - reverse-proxy + - --from + - ${RYLWEEN_DOMAIN} + - --to + - rylween:8081 + - --header-down + - "Strict-Transport-Security: max-age=31536000" + - --header-down + - "X-Content-Type-Options: nosniff" + - --header-down + - "Referrer-Policy: no-referrer" + - --access-log + volumes: + # The certificates and the ACME account, kept across restarts so + # Let's Encrypt is not asked again for every start. + - caddy-data:/data + - caddy-config:/config + +volumes: + data: + caddy-data: + caddy-config: diff --git a/deploy/deploy-rylween.sh b/deploy/deploy-rylween.sh index 94a3a10d..2781c069 100755 --- a/deploy/deploy-rylween.sh +++ b/deploy/deploy-rylween.sh @@ -8,7 +8,9 @@ # same command, and either works from any directory. # # --launcher skips Docker and starts the installed bitmap launcher in the -# background instead. --compose names the default explicitly. +# background instead. --compose names the default explicitly. --https runs the +# released image on the internet behind Caddy and HTTPS instead, with +# compose.https.yaml; deploy/README.md explains what that needs. set -euo pipefail # Follow symlinks such as the root deploy.sh, so DEPLOY_DIR is the directory @@ -35,8 +37,9 @@ MAIN_CLASS="${RYLWEEN_DEPLOY_MAIN_CLASS:-rylween.bitmapweb.RylweenBitmapWebRunti case "$#:${1-}" in 0: | 1:--compose) MODE=compose ;; 1:--launcher) MODE=launcher ;; + 1:--https) MODE=https ;; *) - echo "usage: $0 [--compose | --launcher]" >&2 + echo "usage: $0 [--compose | --launcher | --https]" >&2 exit 2 ;; esac @@ -165,13 +168,14 @@ stop_existing_server() { kill -9 $pids } -# Waits up to a minute for any HTTP answer from the URL in $1; /api/status -# answers 401 without a login, which is enough. `compose up -d` returns as soon +# Waits up to a minute, or $2 seconds, for any HTTP answer from the URL in $1; +# /api/status answers 401 without a login, which is enough. An HTTPS URL counts +# only once its certificate checks out. `compose up -d` returns as soon # as the container starts, seconds before the server in it listens, and the # container port forwarder may accept connections before then, so only an HTTP # response shows the server is up. Without curl it cannot tell and does not wait. wait_for_http() { - local url="$1" deadline=$((SECONDS + 60)) + local url="$1" deadline=$((SECONDS + ${2:-60})) command -v curl >/dev/null 2>&1 || return 0 until curl --noproxy '*' --silent --output /dev/null --max-time 2 "$url"; do [ "$SECONDS" -lt "$deadline" ] || return 1 @@ -179,6 +183,41 @@ wait_for_http() { done } +# HTTPS mode runs compose.https.yaml: the released image, behind Caddy, which +# gets a certificate for RYLWEEN_DOMAIN from Let's Encrypt. It waits until the +# site answers over HTTPS, which includes the time the first certificate takes. +if [ "$MODE" = https ]; then + cd "$DEPLOY_DIR" + domain="${RYLWEEN_DOMAIN-}" + if [ -z "$domain" ] && [ -f .env ]; then + domain="$(sed -n 's/^[[:space:]]*RYLWEEN_DOMAIN=//p' .env | tail -n 1 | tr -d "\"' ")" + fi + if [ -z "$domain" ]; then + echo "Set RYLWEEN_DOMAIN, the name players open, in $DEPLOY_DIR/.env or the shell." >&2 + echo "$DEPLOY_DIR/README.md explains what the name needs." >&2 + exit 2 + fi + engine=(docker compose) + command -v docker >/dev/null 2>&1 || engine=(podman compose) + compose=("${engine[@]}" -f "$DEPLOY_DIR/compose.https.yaml") + "${compose[@]}" pull + "${compose[@]}" up -d + + printf -v manage '%s -f %q' "${engine[*]}" "$DEPLOY_DIR/compose.https.yaml" + if ! wait_for_http "https://$domain/healthz" 180; then + echo "https://$domain/ did not answer within 3 minutes. Check that DNS for $domain" >&2 + echo "points at this host and that ports 80 and 443 reach it. Caddy's log says why:" >&2 + echo " $manage logs caddy" >&2 + exit 1 + fi + echo "Rylween is up on https://$domain/" + echo " Sysop password: $manage exec rylween cat /data/auth/admin-password.txt" + echo " Server log: $manage logs -f rylween" + echo " Proxy log: $manage logs -f caddy" + echo " Stop: $manage down" + exit 0 +fi + # Compose mode builds and runs the image instead of the installed launcher. It # publishes on the detected LAN address unless RYLWEEN_PUBLISH_HOST is set in # the shell or in .env; every other setting comes from compose.yaml and .env, diff --git a/deploy/docker/README.md b/deploy/docker/README.md deleted file mode 100644 index 0cc22c27..00000000 --- a/deploy/docker/README.md +++ /dev/null @@ -1,103 +0,0 @@ -# Docker Deployment - -`deploy/docker/` contains Docker packaging for the web runtimes. - -- `Dockerfile` builds the browser-served ANSI web runtime image used by - `bin/run-server.sh --build`. -- `Dockerfile.production` builds the production-oriented ANSI web runtime image. -- `Dockerfile.bitmap-production` builds the production-oriented bitmap web - runtime image. Each release publishes it as `ghcr.io/lagergren/rylween:X.Y.Z` - and `:latest`, for linux/amd64 and linux/arm64; see Releasing in the root - README. - -`Dockerfile` and `Dockerfile.production` serve the ANSI web runtime on port -8080; `Dockerfile.bitmap-production` serves the bitmap runtime on port 8081. All -keep saves, accounts, and logs under the `/data` volume. Run directly, the -bitmap image uses an 8x8 wilderness view at 64 px per tile, while compose and the -bitmap launcher default to 6x6 at 68 px. - -Build commands still use the repository root as the Docker context so Gradle, -source modules, resources, and `.dockerignore` are all visible: - -```sh -docker build -f deploy/docker/Dockerfile.production -t rylween-web-prod . -docker build -f deploy/docker/Dockerfile.bitmap-production -t rylween-bitmap-prod . -``` - -The production images serve plain HTTP inside the container. Bind the container -to loopback or a private container network and terminate HTTPS at nginx, Caddy, -HAProxy, a platform load balancer, or another reverse proxy. Both production -images set `RYLWEEN_AUTH_SECURE_COOKIES=true`, so browsers keep the login cookie -only over HTTPS; set it to `false` only when players reach the server over plain -HTTP. - -## Compose - -`deploy/compose.yaml` builds `Dockerfile.bitmap-production` from the -repository root and runs the bitmap game with its data directory on a -persistent volume. Run compose from `deploy/`, or pass -`-f deploy/compose.yaml` from the repository root: - -```sh -cd deploy -docker compose up --build -d # or: podman compose up --build -d -docker compose logs -f rylween -docker compose down # keeps the volume -``` - -On macOS with Podman, start the VM first with `podman machine start`. - -Saves, accounts, and logs are written to `/data` in the container, backed by -the `rylween_data` named volume. They survive `down`, rebuilds, and image -updates; only `down -v` or `volume rm` deletes them. To keep the data in a -host directory instead, for example to back it up with -`bin/backup-web-data.sh`, create the directory and point -`RYLWEEN_DATA_VOLUME` at it in `deploy/.env`, so every later deploy uses it -too. From the repository root: - -```sh -mkdir -p ~/.rylween/compose-data -echo 'RYLWEEN_DATA_VOLUME=~/.rylween/compose-data' >> deploy/.env -./deploy.sh -bin/backup-web-data.sh --data ~/.rylween/compose-data --output rylween-backup.tar.gz -``` - -On first start the server creates the sysop account (`RYLWEEN_ADMIN_ACCOUNT`, -default `admin`), which players cannot register. Unless `RYLWEEN_ADMIN_PASSWORD` -is set, its generated password is saved in `/data/auth/admin-password.txt`: - -```sh -docker compose exec rylween cat /data/auth/admin-password.txt -``` - -The container publishes on `127.0.0.1:8081` by default. To let other machines -on the local network connect, run compose through the deploy script, which -builds the image, detects this machine's private LAN address, publishes on it, -waits until the server answers, and prints its address with the commands for -the sysop password, the log, and `down`: - -```sh -./deploy.sh # from the repository root; a link to deploy/deploy-rylween.sh -./deploy-rylween.sh # from deploy/; the same script -``` - -Or set `RYLWEEN_PUBLISH_HOST` yourself, to a LAN address such as `192.168.x.y` -or to `0.0.0.0`. `RYLWEEN_HOST_PORT` changes the port. -Unlike the production image run with `docker run`, compose sets -`RYLWEEN_AUTH_SECURE_COOKIES=false` so logins work over plain HTTP; set it to -`true` behind an HTTPS proxy. When `deploy/.env` sets `RYLWEEN_PUBLISH_HOST`, -the deploy script uses that address instead of detecting the LAN address. All -settings are listed at the top of `compose.yaml` and can be kept in an -uncommitted `deploy/.env` file next to it; copy `deploy/.env.example`, which -shows each one at its default. A relative `RYLWEEN_DATA_VOLUME` such as -`./data` is relative to `deploy/`. - -`./deploy.sh --launcher` skips Docker: it starts the installed bitmap launcher -in the background on the LAN address, port 8081, with its data in -`~/.rylween/deploy` and its log in `/tmp/rylween-bitmap-web-deploy.log`, -stopping a server it started earlier. Build the launcher first with -`./gradlew :runtime-bitmap-web:installRuntimeBitmapWeb`. - -The root `.dockerignore` intentionally remains at the repository root because -Docker reads ignore rules relative to the build context, not relative to the -Dockerfile path. diff --git a/runtimes/runtime-bitmap-web/README.md b/runtimes/runtime-bitmap-web/README.md index b90c14b5..a46a314e 100644 --- a/runtimes/runtime-bitmap-web/README.md +++ b/runtimes/runtime-bitmap-web/README.md @@ -92,49 +92,11 @@ digit keys belong to the game and do not switch views). `/tools/art-gallery` lists every static bitmap asset and compiled game image the server serves. Both require a login unless the server runs with the `--user` development bypass. -## Deploy Script +## Running It As A Server -On Linux and macOS, `./deploy.sh --launcher` (the root `deploy.sh` links to -`deploy/deploy-rylween.sh`) starts the installed bitmap runtime in the -background with an isolated data directory under `~/.rylween/deploy`. By -default it binds to the private LAN IPv4 address of the interface carrying the -default route, so other machines on the local network can reach the server -without it listening on every network interface: - -```sh -./gradlew :runtime-bitmap-web:installRuntimeBitmapWeb --console=plain -./deploy.sh --launcher -``` - -It finds the installed launcher relative to the repository, so it can be run -from any directory, and refuses to start when the launcher is not installed. -Rerunning it stops the server it started -earlier before starting a new one. On Linux it uses `ip`, `/proc`, and -`setsid`; on macOS it falls back to `route`, `ifconfig`, `ps`, and `nohup`. It -prints the detected server URL, for example `http://192.168.1.20:8081`. It -refuses to pick a public address automatically. Override the bind address when -needed: - -```sh -RYLWEEN_DEPLOY_HOST=127.0.0.1 ./deploy.sh --launcher -RYLWEEN_DEPLOY_HOST=192.168.x.y ./deploy.sh --launcher -``` - -`RYLWEEN_DEPLOY_PORT`, `RYLWEEN_DEPLOY_DATA_DIR`, and `RYLWEEN_DEPLOY_LOG_FILE` -override the port (default `8081`), data directory, and log file (default -`/tmp/rylween-bitmap-web-deploy.log`), and `RYLWEEN_DEPLOY_APP` points it at -another installed launcher. On first start the server creates the sysop account -`admin`; unless `RYLWEEN_ADMIN_PASSWORD` is set, its generated password is in -`~/.rylween/deploy/auth/admin-password.txt`. - -Without `--launcher`, `./deploy.sh` runs the production image through -`deploy/compose.yaml` instead, published on the same detected LAN address (see -[`deploy/docker/README.md`](../../deploy/docker/README.md#compose)). There -`RYLWEEN_DEPLOY_HOST` still picks the address; the port, data, and log settings -are replaced by compose's `RYLWEEN_HOST_PORT` and `RYLWEEN_DATA_VOLUME`. - -Do not use `RYLWEEN_DEPLOY_HOST=0.0.0.0` unless the server should listen on all -IPv4 interfaces. +[`deploy/README.md`](../../deploy/README.md) covers running this server for +players: `./deploy.sh` on the local network, its `--launcher` mode, which runs +this launcher without Docker, and HTTPS on the internet. ## Browser Smoke diff --git a/runtimes/runtime-bitmap-web/src/main/kotlin/rylween/bitmapweb/RylweenBitmapWebRuntimeMain.kt b/runtimes/runtime-bitmap-web/src/main/kotlin/rylween/bitmapweb/RylweenBitmapWebRuntimeMain.kt index 600c8711..3ad62a8b 100644 --- a/runtimes/runtime-bitmap-web/src/main/kotlin/rylween/bitmapweb/RylweenBitmapWebRuntimeMain.kt +++ b/runtimes/runtime-bitmap-web/src/main/kotlin/rylween/bitmapweb/RylweenBitmapWebRuntimeMain.kt @@ -22,10 +22,12 @@ import rylween.runtime.RuntimeSessionExitReason import rylween.runtime.RuntimeSessionFactory import rylween.runtime.WorldMap import rylween.runtime.rylweenVersion +import rylween.webcommon.WebHttpHeader import rylween.webcommon.WebHttpRequest import rylween.webcommon.WebServerStatus import rylween.webcommon.WebSocketConnection import rylween.webcommon.WebSocketProtocol +import rylween.webcommon.WebTrustedProxies import rylween.webcommon.auth.WebAccount import rylween.webcommon.auth.WebAuthAvailability import rylween.webcommon.auth.WebAuthBootstrapAccount @@ -34,11 +36,13 @@ import rylween.webcommon.auth.WebAuthCookies import rylween.webcommon.auth.WebAuthFieldAvailability import rylween.webcommon.auth.WebAuthPageMode import rylween.webcommon.auth.WebAuthResult +import rylween.webcommon.auth.WebLoginThrottle import rylween.webcommon.auth.WebSessionStore import rylween.webcommon.auth.WebSysopAccountResult import rylween.webcommon.auth.WebUserStore import rylween.webcommon.auth.slugFrom import rylween.webcommon.auth.webAuthPageHtml +import rylween.webcommon.isSameOrigin import rylween.webcommon.readHttpRequest import rylween.webcommon.redirect import rylween.webcommon.respondBytes @@ -159,6 +163,8 @@ private data class BitmapWebConfig( val tileSize: Int, /** Where players reach the server, ending in `/`: what a link to it starts with. */ val publicUrl: String, + /** The reverse proxies, such as the Caddy that terminates HTTPS, whose `X-Forwarded-For` names the client. */ + val trustedProxies: WebTrustedProxies, ) { val saveDir: File get() = dataDir.resolve("saves") val logDir: File get() = dataDir.resolve("logs/runtime-bitmap-web") @@ -198,6 +204,7 @@ private data class BitmapWebConfig( var mapTiles = envOrDefault("RYLWEEN_BITMAP_MAP_TILES", DEFAULT_BITMAP_VIEWPORT_TILES.toString()).toInt() var tileSize = envOrDefault("RYLWEEN_BITMAP_TILE_SIZE", DEFAULT_BITMAP_TILE_SIZE.toString()).toInt() var publicUrl = optionalEnv("RYLWEEN_PUBLIC_URL") + var trustedProxies = optionalEnv("RYLWEEN_TRUSTED_PROXIES").orEmpty() var index = 0 while (index < args.size) { when (val arg = args[index]) { @@ -269,6 +276,10 @@ private data class BitmapWebConfig( index += 1 publicUrl = requiredValue(args, index, arg) } + "--trusted-proxies" -> { + index += 1 + trustedProxies = requiredValue(args, index, arg) + } "--help", "-h" -> { printUsage() exitProcess(0) @@ -294,6 +305,7 @@ private data class BitmapWebConfig( mapTiles, tileSize, publicUrl?.let { url -> url.trimEnd('/') + "/" } ?: defaultPublicUrl(host, port), + WebTrustedProxies.parse(trustedProxies), ) } @@ -346,7 +358,7 @@ private data class BitmapWebConfig( private fun printUsage() { println( """ - Usage: rylween-bitmap-web [--host HOST] [--port PORT] [--data DIR] [--state SLUG] [--bundle FILE] [--user ID] [--load FILE] [--save FILE] [--account NAME --password PASSWORD [--email EMAIL]] [--secure-cookies] [--title|--no-title] [--debug-secrets] [--map-tiles N] [--tile-size PX] [--public-url URL] + Usage: rylween-bitmap-web [--host HOST] [--port PORT] [--data DIR] [--state SLUG] [--bundle FILE] [--user ID] [--load FILE] [--save FILE] [--account NAME --password PASSWORD [--email EMAIL]] [--secure-cookies] [--title|--no-title] [--debug-secrets] [--map-tiles N] [--tile-size PX] [--public-url URL] [--trusted-proxies RANGES] The bitmap runtime uses the embedded :game bundle by default. --bundle can point at build/compiled/rylween-bundle.json to exercise an emitted artifact instead. @@ -356,6 +368,8 @@ private data class BitmapWebConfig( --debug-secrets enables hidden manual-test wilderness commands, including M for the annotated full map. --public-url (RYLWEEN_PUBLIC_URL) is the address players open, which the server prints once it is up. It defaults to the bind address, with a wildcard read as localhost. + --trusted-proxies (RYLWEEN_TRUSTED_PROXIES) lists the reverse proxies, as addresses or CIDR ranges, + whose X-Forwarded-For names the client in logs and in the failed-login limit. Default: none. Map defaults: ${DEFAULT_BITMAP_VIEWPORT_TILES}x${DEFAULT_BITMAP_VIEWPORT_TILES} tiles at ${DEFAULT_BITMAP_TILE_SIZE}px. """.trimIndent(), ) @@ -402,6 +416,7 @@ private class BitmapWebServer( // Players cannot register the sysop account; the server creates it at startup. private val userStore = WebUserStore(config.authDir, reservedNames = setOf(secretAccounts.admin)) private val sessions = WebSessionStore() + private val loginThrottle = WebLoginThrottle() private val activeUsers = ConcurrentHashMap.newKeySet() private val bitmapImageById = game.systems.presentation.images @@ -429,7 +444,7 @@ private class BitmapWebServer( "devUser=${config.userId.orEmpty()} load=${config.loadFile?.path.orEmpty()} " + "save=${config.worldSaveFile.path} title=${config.showTitleMenu} " + "debugSecrets=${config.debugSecrets} mapTiles=${config.mapTiles} tileSize=${config.tileSize} " + - "bundle=${game.source} url=${config.entryUrl}", + "bundle=${game.source} url=${config.entryUrl} trustedProxies=${serverLogValue(config.trustedProxies.toString())}", ) announceEntry(game.bundle.content.let { content -> content.strings.value(content.universe.nameString) }, config.entryUrl) while (!serverSocket.isClosed) { @@ -499,12 +514,22 @@ private class BitmapWebServer( ) { val input = socket.getInputStream() val request = readHttpRequest(input) ?: return - serverLog.event("bitmap.http.request id=$clientId method=${request.method} path=${request.path}") + val client = config.trustedProxies.clientAddress(socket.inetAddress, request.header("x-forwarded-for")).hostAddress + serverLog.event("bitmap.http.request id=$clientId method=${request.method} path=${request.path} client=$client") if (request.method !in setOf("GET", "POST")) { serverLog.event("bitmap.http.response id=$clientId status=405 path=${request.path}") respondText(socket, "405 Method Not Allowed", "text/plain; charset=utf-8", "GET required\n") return } + // A POST or the game's socket, sent by a page from another site, would carry the player's cookies. + if ((request.method == "POST" || request.path == "/ws/play") && !request.isSameOrigin(config.publicUrl)) { + serverLog.event( + "bitmap.http.reject id=$clientId client=$client path=${request.path} reason=cross_origin " + + "origin=${serverLogValue(request.header("origin").orEmpty())}", + ) + respondText(socket, "403 Forbidden", "text/plain; charset=utf-8", "cross-origin request refused\n") + return + } when (request.path) { "/" -> routeHome(socket, request, clientId) "/play" -> routePlayPage(socket, request, clientId) @@ -512,7 +537,7 @@ private class BitmapWebServer( "/tools/art-gallery" -> routeArtGallery(socket, request, clientId) "/login" -> routeLoginPage(socket, request, clientId) "/register" -> routeRegisterPage(socket, request, clientId) - "/api/login" -> routeLogin(socket, request, clientId) + "/api/login" -> routeLogin(socket, request, clientId, client) "/api/register" -> routeRegister(socket, request, clientId) "/api/logout" -> routeLogout(socket, request, clientId) "/api/auth/availability" -> routeAuthAvailability(socket, request, clientId) @@ -673,11 +698,35 @@ private class BitmapWebServer( socket: Socket, request: WebHttpRequest, clientId: Long, + client: String, ) { val form = request.formFields() val email = form["email"].orEmpty() + val wait = loginThrottle.retryAfter(client) + if (!wait.isZero) { + val minutes = (wait.seconds + 59) / 60 + serverLog.event( + "bitmap.auth.login_throttled id=$clientId client=$client email=${serverLogValue(email)} " + + "retryAfter=${wait.seconds}s", + ) + serverLog.event("bitmap.http.response id=$clientId status=429 path=${request.path}") + respondText( + socket, + "429 Too Many Requests", + "text/html; charset=utf-8", + webAuthPageHtml( + WebAuthPageMode.Login, + "Too many failed logins. Try again in $minutes minute${if (minutes == 1L) "" else "s"}.", + email, + backgroundImage = "/assets/title/title-rider.png", + ), + headers = listOf(WebHttpHeader("Retry-After", wait.seconds.toString())), + ) + return + } when (val result = userStore.authenticate(email, form["password"].orEmpty())) { is WebAuthResult.Success -> { + loginThrottle.recordSuccess(client) val token = sessions.create(result.account) serverLog.event("bitmap.auth.login id=$clientId user=${result.account.slug} email=${serverLogValue(result.account.email)}") serverLog.event("bitmap.http.response id=$clientId status=303 path=${request.path} location=/play") @@ -691,8 +740,10 @@ private class BitmapWebServer( ) } is WebAuthResult.Failure -> { + loginThrottle.recordFailure(client) serverLog.event( - "bitmap.auth.login_failed id=$clientId email=${serverLogValue(email)} reason=${serverLogValue(result.message)}", + "bitmap.auth.login_failed id=$clientId client=$client email=${serverLogValue(email)} " + + "reason=${serverLogValue(result.message)}", ) serverLog.event("bitmap.http.response id=$clientId status=401 path=${request.path}") respondText( diff --git a/runtimes/runtime-web/README.md b/runtimes/runtime-web/README.md index 13b110c3..9cf0b8c8 100644 --- a/runtimes/runtime-web/README.md +++ b/runtimes/runtime-web/README.md @@ -14,11 +14,6 @@ This module should not own game mechanics, key-command meaning, password storage, or generic WebSocket protocol code. Those belong in `:runtime` or `:web-common`. -For production behind a reverse proxy, build -`deploy/docker/Dockerfile.production`, bind the container to loopback or a -private network, terminate HTTPS at the proxy, and keep -`RYLWEEN_AUTH_SECURE_COOKIES=true`. - ## Running It Locally Build the bundle and the launcher, then run the launcher against the bundle: @@ -44,172 +39,8 @@ already playing is turned away. Quitting ends the session and closes the connection, so the player reloads the page to play again. (The bitmap server returns to its title screen instead.) -## Exposing A Production Docker Deployment - -The safe production shape is: - -1. Rylween runs as the production Docker container on the deployment host. -2. The container publishes plain HTTP only to `127.0.0.1` or a private Docker - network on that host. -3. A reverse proxy on the deployment host terminates public HTTPS and forwards - to the local container port. -4. The internet router forwards only TCP 443, and optionally TCP 80 for ACME - HTTP-01 certificates, to the reverse proxy host. - -Do not expose the Rylween container port directly to the internet. Do not add -RouterOS `input` rules for Rylween unless the reverse proxy is actually running -on the router itself; normal port forwarding to a host behind the router is -`dstnat` plus `forward`, not `input`. - -Example host-side run, using the ANSI production image: - -```sh -docker build -f deploy/docker/Dockerfile.production -t rylween-web-prod . - -mkdir -p /etc/rylween -chmod 700 /etc/rylween -$EDITOR /etc/rylween/rylween.env -chmod 600 /etc/rylween/rylween.env - -docker run -d \ - --name rylween-web \ - --restart unless-stopped \ - --env-file /etc/rylween/rylween.env \ - -p 127.0.0.1:8080:8080 \ - -v rylween-data:/data \ - rylween-web-prod -``` - -Example `/etc/rylween/rylween.env`: - -```sh -RYLWEEN_ADMIN_PASSWORD=replace-with-a-long-unique-secret -RYLWEEN_AUTH_SECURE_COOKIES=true -``` - -On first start the server creates the sysop account (`RYLWEEN_ADMIN_ACCOUNT`, -default `admin`), which gets the game's secret wilderness keys and which -players cannot register. `RYLWEEN_ADMIN_PASSWORD` only applies when that account -is created; without it the server generates a password into -`/data/auth/admin-password.txt`, readable with -`docker exec rylween-web cat /data/auth/admin-password.txt`. -`RYLWEEN_VICTIM_ACCOUNT` names an account the sysop gods hunt down every 101 -moves; unset means nobody. `RYLWEEN_AUTH_ACCOUNT`, `RYLWEEN_AUTH_EMAIL`, and -`RYLWEEN_AUTH_PASSWORD` optionally create or verify one more account at startup; -giving it the sysop's name makes it the sysop account. The production image -already defaults `RYLWEEN_AUTH_SECURE_COOKIES` to `true`. - -Do not pass production passwords on the command line. They can end up in shell -history, process listings, or operational logs. Prefer a locked-down environment -file, Docker secrets, or the deployment platform's secret manager. - -Example Caddy reverse proxy on the deployment host: - -```caddyfile -rylween.example.net { - encode zstd gzip - reverse_proxy 127.0.0.1:8080 - header { - Strict-Transport-Security "max-age=31536000; includeSubDomains" - X-Content-Type-Options "nosniff" - Referrer-Policy "no-referrer" - } -} -``` - -Caddy handles WebSocket upgrades for `reverse_proxy`. If you use nginx, HAProxy, -Traefik, or another proxy, make sure WebSocket upgrade headers are forwarded; -the game socket is `/ws/play`. `GET /healthz` returns `ok` without a login, for -health checks. - -The server log is `/data/logs/web-server.log`, and each session writes -`/data/logs/-.log`. Server log lines and session events -are also echoed to standard output, so `docker logs rylween-web` shows them. - -### RouterOS Port Forwarding Example - -Assumptions: - -- RouterOS has interface lists named `WAN` and `LAN`. -- Public DNS for `rylween.example.net` points at the router's public address. -- The deployment host has a stable LAN address, `192.168.88.20`. -- The reverse proxy listens on `192.168.88.20:443`. -- The Rylween container itself is not reachable on the LAN or WAN; it is bound - to `127.0.0.1:8080` on the deployment host. - -Forward public HTTPS to the reverse proxy: - -```routeros -/ip firewall nat -add chain=dstnat in-interface-list=WAN protocol=tcp dst-port=443 \ - action=dst-nat to-addresses=192.168.88.20 to-ports=443 \ - comment="Rylween HTTPS to reverse proxy" -``` - -If your reverse proxy uses ACME HTTP-01 certificate validation, also forward -TCP 80 to the reverse proxy. If you use DNS-01 validation or install -certificates out of band, leave TCP 80 closed. - -```routeros -/ip firewall nat -add chain=dstnat in-interface-list=WAN protocol=tcp dst-port=80 \ - action=dst-nat to-addresses=192.168.88.20 to-ports=80 \ - comment="Rylween ACME HTTP-01 to reverse proxy" -``` - -Many RouterOS default firewall configurations already allow established -connections and drop new WAN traffic that is not destination-NATed. If your -forward chain ends in a drop rule, add a narrow accept rule before that final -drop: - -```routeros -/ip firewall filter -add chain=forward action=accept in-interface-list=WAN \ - connection-nat-state=dstnat connection-state=new protocol=tcp \ - dst-address=192.168.88.20 dst-port=443 \ - comment="Allow Rylween HTTPS dstnat" -``` - -Add the same kind of narrow forward rule for TCP 80 only if you forwarded TCP 80 -above. Keep existing `established,related` and `invalid` rules in front of the -final drop. A good baseline forward policy accepts established/related traffic, -drops invalid traffic, accepts the specific `dstnat` services you intend to -publish, and drops other new WAN-originated traffic. - -Do not add a broad rule such as "accept all from WAN to server" and do not -forward port `8080` or `8081` from the internet. Those are internal application -ports used behind the reverse proxy. - -### IPv6, CGNAT, And Network Isolation - -IPv4 port forwarding only works when the router has a real public IPv4 address. -If the WAN address is in private space or `100.64.0.0/10`, the ISP is probably -using CGNAT and inbound IPv4 forwarding will not work without a public address, -a tunnel, or an external hosting endpoint. - -IPv6 is different: hosts may be globally reachable without NAT. If the -deployment host receives an IPv6 address, add explicit IPv6 firewall rules that -allow only TCP 443, and optionally TCP 80 for ACME, to the reverse proxy host. -Do not assume IPv4 NAT protects IPv6. - -A separate NIC, VLAN, or dedicated router port can be useful for a stricter -server network, but it is not required for a small deployment if these controls -are in place: - -- the Docker app port is bound to loopback or a private container network, -- only the reverse proxy listens on the host LAN address, -- RouterOS forwards only the public HTTPS service to that host, -- host firewall rules allow administrative access only from trusted LAN or VPN - addresses, -- the OS, Docker image, reverse proxy, and RouterOS are kept updated, -- `/data` is backed up and auth/save data is not stored in the image. +## Running It On A Server -The bitmap production image follows the same exposure pattern. Its internal app -port defaults to `8081`, so keep it behind the reverse proxy just like the ANSI -web image and publish only public HTTPS at the router. `deploy/compose.yaml` -runs that image (`docker compose -f deploy/compose.yaml up --build -d`) and -publishes it on `127.0.0.1:8081` by default. Compose defaults -`RYLWEEN_AUTH_SECURE_COOKIES` to `false`, so set it to `true` in `deploy/.env` -behind an HTTPS proxy. `./deploy.sh` publishes on this machine's LAN address for -local-network play; for a reverse-proxy deployment set -`RYLWEEN_PUBLISH_HOST=127.0.0.1` or run compose directly. +[`deploy/README.md`](../../deploy/README.md#the-ansi-game-in-the-browser) covers +its production image, `deploy/docker/Dockerfile.production`, and putting a +server on the internet behind HTTPS, with port forwarding and network advice. diff --git a/support/web-common/README.md b/support/web-common/README.md index 1535b751..b8c2b03a 100644 --- a/support/web-common/README.md +++ b/support/web-common/README.md @@ -4,7 +4,9 @@ runtimes. Server-specific modules keep their renderer, launcher policy, save loading, and game-loop wiring local, but reuse this module for HTTP parsing, WebSocket handshakes, authentication, session cookies, shared auth pages, and -status responses. +status responses. It also holds the pieces a server on the internet needs: client +addresses behind a reverse proxy, the same-origin check, and the failed-login +limit, which only the bitmap server uses so far. ## Authentication Flow @@ -315,8 +317,29 @@ the browser UI. It currently reports: The popover is UI-specific, but the response shape belongs here so both web runtimes report the same operational information. +## Behind A Proxy + +These are what `deploy/compose.https.yaml` relies on. The bitmap server applies +them; the ANSI web server does not yet. + +- `WebTrustedProxies` turns the connecting address and `X-Forwarded-For` into + the client's address. It believes `X-Forwarded-For` only from the configured + proxies (`RYLWEEN_TRUSTED_PROXIES`, addresses and CIDR ranges), takes the + nearest hop that is not a trusted proxy, and never looks a name up in DNS. + The bitmap server logs it as `client=` on every request and failed login. +- `WebHttpRequest.isSameOrigin` checks a request's `Origin` against the server's + public URL (`RYLWEEN_PUBLIC_URL`) or, for any other name, its `Host`. The + bitmap server refuses every POST and the `/ws/play` handshake that fail it, + with 403. Requests without `Origin` come from outside a browser and pass. +- `WebLoginThrottle` refuses a client's logins, with 429 and `Retry-After`, after + 10 failures within 15 minutes, until 15 minutes after the first. A successful + login clears the count; counts live in memory. + ## Production Hardening +`deploy/README.md` sets up items 1 to 5 below, and the headers of item 16 other +than `Content-Security-Policy`, with Caddy in `deploy/compose.https.yaml`. + The current implementation is suitable for local development and small self-hosted testing. To turn it into a commercial-strength HTTPS web app, do the following before exposing it publicly. @@ -347,13 +370,16 @@ following before exposing it publicly. environment file with locked permissions, Docker/Kubernetes secret, or cloud secret manager. -6. Add CSRF protection for `POST /api/login`, `POST /api/register`, and - `POST /api/logout`. `SameSite=Lax` is useful, but commercial deployments - should use explicit CSRF tokens for state-changing forms. The routes do not - check the HTTP method today, so `GET /api/logout` also logs out. +6. Strengthen CSRF protection. The bitmap server refuses POSTs from another + site's page by their `Origin` (see Behind A Proxy), and `SameSite=Lax` keeps + the session cookie off cross-site POSTs. Explicit CSRF tokens would add a + second layer, and the ANSI web server needs the `Origin` check too. The + routes do not check the HTTP method today, so `GET /api/logout` also logs + out. -7. Add login throttling and abuse controls: per-IP and per-account rate limits, - temporary lockout/backoff, and alerting for repeated failures. OWASP's +7. Extend login throttling. The bitmap server limits failed logins per client + address (see Behind A Proxy). Per-account limits, alerting on repeated + failures, and the same limit in the ANSI web server remain. OWASP's authentication guidance calls out protections against automated attacks: . diff --git a/support/web-common/src/main/kotlin/rylween/webcommon/WebClientAddress.kt b/support/web-common/src/main/kotlin/rylween/webcommon/WebClientAddress.kt new file mode 100644 index 00000000..ba23345d --- /dev/null +++ b/support/web-common/src/main/kotlin/rylween/webcommon/WebClientAddress.kt @@ -0,0 +1,105 @@ +/** + * Client addresses behind a reverse proxy. A proxy that terminates HTTPS, such as Caddy, connects to the server itself + * and says in `X-Forwarded-For` whom it forwards for. Only the proxies the server is told to trust are believed: any + * client can send that header. + */ + +package rylween.webcommon + +import java.net.InetAddress + +/** An address range in CIDR notation, such as `172.16.0.0/12` or `fc00::/7`. A bare address is a range of one. */ +class WebAddressRange private constructor( + private val network: ByteArray, + private val prefixLength: Int, +) { + fun contains(address: InetAddress): Boolean { + val bytes = address.address + if (bytes.size != network.size) return false + val wholeBytes = prefixLength / 8 + val restBits = prefixLength % 8 + val mask = (0xFF shl (8 - restBits)) and 0xFF + return (0 until wholeBytes).all { index -> bytes[index] == network[index] } && + (restBits == 0 || (bytes[wholeBytes].toInt() and mask) == (network[wholeBytes].toInt() and mask)) + } + + override fun toString(): String = "${InetAddress.getByAddress(network).hostAddress}/$prefixLength" + + companion object { + /** Parses `address` or `address/prefix`, and fails for anything that is not a literal address. */ + fun parse(text: String): WebAddressRange { + val addressText = text.substringBefore('/').trim() + val prefixText = text.substringAfter('/', missingDelimiterValue = "").trim() + val address = webAddressLiteral(addressText) ?: throw IllegalArgumentException("not an address range: \"$text\"") + val bits = address.address.size * 8 + val prefix = + if (prefixText.isEmpty()) { + bits + } else { + prefixText.toIntOrNull()?.takeIf { length -> length in 0..bits } + ?: throw IllegalArgumentException("not an address range: \"$text\"") + } + return WebAddressRange(address.address, prefix) + } + } +} + +/** The proxies whose `X-Forwarded-For` the server believes. */ +class WebTrustedProxies( + private val ranges: List, +) { + fun trusts(address: InetAddress): Boolean = ranges.any { range -> range.contains(address) } + + /** + * The client a request came from. That is [peer], the address that connected, unless [peer] is a trusted proxy. + * Then it is the nearest address in [forwardedFor] that is not one, walking back from the end, where each proxy + * appends whom it forwards for. An entry that is no address ends the walk, since no trusted proxy wrote it. + */ + fun clientAddress( + peer: InetAddress, + forwardedFor: String?, + ): InetAddress { + if (forwardedFor == null || !trusts(peer)) return peer + val hops = + forwardedFor + .split(',') + .asReversed() + .asSequence() + .map(::webForwardedAddress) + .takeWhile { hop -> hop != null } + .filterNotNull() + .toList() + return hops.firstOrNull { hop -> !trusts(hop) } ?: hops.lastOrNull() ?: peer + } + + override fun toString(): String = ranges.joinToString(",") + + companion object { + val None = WebTrustedProxies(emptyList()) + + /** Parses a comma- or space-separated list of addresses and CIDR ranges. Blank trusts no one. */ + fun parse(text: String): WebTrustedProxies = + WebTrustedProxies( + text + .split(',', ' ') + .filter(String::isNotBlank) + .map(WebAddressRange::parse), + ) + } +} + +/** A literal IPv4 or IPv6 address, optionally in brackets, never looked up in DNS; null for anything else. */ +private fun webAddressLiteral(text: String): InetAddress? = + runCatching { InetAddress.ofLiteral(text.removePrefix("[").removeSuffix("]")) }.getOrNull() + +/** One `X-Forwarded-For` entry: an address, maybe in brackets and maybe with a port. */ +private fun webForwardedAddress(entry: String): InetAddress? { + val text = entry.trim() + val address = + when { + text.startsWith("[") -> text.substringAfter('[').substringBefore(']') + text.count { char -> char == ':' } == 1 -> text.substringBefore(':') + else -> text + } + return webAddressLiteral(address) +} diff --git a/support/web-common/src/main/kotlin/rylween/webcommon/WebOrigin.kt b/support/web-common/src/main/kotlin/rylween/webcommon/WebOrigin.kt new file mode 100644 index 00000000..bc671ebd --- /dev/null +++ b/support/web-common/src/main/kotlin/rylween/webcommon/WebOrigin.kt @@ -0,0 +1,39 @@ +/** + * Same-origin checks for the requests a browser can be made to send from another site, such as a form POST or the + * game's WebSocket, which the browser opens with the player's cookies wherever the page that opens it came from. + */ + +package rylween.webcommon + +import java.net.URI +import java.util.Locale + +/** + * Whether this request's `Origin` is this server. The browser names the scheme, host and port the page came from. That + * must be [publicUrl], where players reach the server, perhaps through a proxy that rewrites `Host`. Or, for any other + * name, such as a LAN address, it must be the `Host` the request was sent to. `Host` has no scheme, which behind a + * proxy that terminates HTTPS the server cannot see, so for the public URL's own host only its scheme and port count. + * A request without `Origin` comes from outside a browser and passes: browsers send `Origin` on every POST and + * WebSocket, and only a browser holds a player's cookies. + */ +fun WebHttpRequest.isSameOrigin(publicUrl: String): Boolean { + val origin = header("origin") ?: return true + val from = webOrigin(origin) ?: return false + val public = webOrigin(publicUrl) + return from == public || + (from.host != public?.host && from == header("host")?.let { host -> webOrigin("${from.scheme}://$host") }) +} + +private data class WebOrigin( + val scheme: String, + val host: String, + val port: Int, +) + +private fun webOrigin(url: String): WebOrigin? { + val uri = runCatching { URI(url) }.getOrNull() ?: return null + val scheme = uri.scheme?.lowercase(Locale.ROOT) ?: return null + val host = uri.host?.lowercase(Locale.ROOT) ?: return null + val port = uri.port.takeIf { explicit -> explicit >= 0 } ?: if (scheme == "https") 443 else 80 + return WebOrigin(scheme, host, port) +} diff --git a/support/web-common/src/main/kotlin/rylween/webcommon/auth/WebLoginThrottle.kt b/support/web-common/src/main/kotlin/rylween/webcommon/auth/WebLoginThrottle.kt new file mode 100644 index 00000000..00ff5ab5 --- /dev/null +++ b/support/web-common/src/main/kotlin/rylween/webcommon/auth/WebLoginThrottle.kt @@ -0,0 +1,51 @@ +/** Failed-login limits that slow down password guessing. */ + +package rylween.webcommon.auth + +import java.time.Duration +import java.time.Instant +import java.util.concurrent.ConcurrentHashMap + +/** Past this many clients with a record, recording a failure also forgets the records whose window has passed. */ +private const val PRUNE_THRESHOLD = 10_000 + +/** + * Slows down password guessing. After [maxFailures] failed logins from one client within [window] of the first, that + * client's further attempts are refused until the window has passed. A successful login clears the client's record. + * Clients are told apart by address, so behind a proxy this needs the proxy trusted (see WebTrustedProxies). + */ +class WebLoginThrottle( + private val maxFailures: Int = 10, + private val window: Duration = Duration.ofMinutes(15), + private val now: () -> Instant = Instant::now, +) { + private data class Failures( + val count: Int, + val since: Instant, + ) + + // The only state. ConcurrentHashMap.compute keeps each client's update atomic across the request threads. + private val failures = ConcurrentHashMap() + + /** How long [client] must wait before its next attempt; zero when it may try now. */ + fun retryAfter(client: String): Duration = + failures[client] + ?.takeIf { record -> record.count >= maxFailures } + ?.let { record -> Duration.between(now(), record.since.plus(window)) } + ?.takeIf(Duration::isPositive) + ?: Duration.ZERO + + fun recordFailure(client: String) { + val at = now() + failures.compute(client) { _, record -> + if (record == null || record.expiredAt(at)) Failures(1, at) else record.copy(count = record.count + 1) + } + if (failures.size > PRUNE_THRESHOLD) failures.values.removeIf { record -> record.expiredAt(at) } + } + + fun recordSuccess(client: String) { + failures.remove(client) + } + + private fun Failures.expiredAt(at: Instant): Boolean = !at.isBefore(since.plus(window)) +} diff --git a/support/web-common/src/test/kotlin/rylween/webcommon/WebClientAddressTest.kt b/support/web-common/src/test/kotlin/rylween/webcommon/WebClientAddressTest.kt new file mode 100644 index 00000000..945d2fbe --- /dev/null +++ b/support/web-common/src/test/kotlin/rylween/webcommon/WebClientAddressTest.kt @@ -0,0 +1,66 @@ +package rylween.webcommon + +import java.net.InetAddress +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class WebClientAddressTest { + private fun address(text: String): InetAddress = InetAddress.ofLiteral(text) + + private val dockerNetworks = WebTrustedProxies.parse("10.0.0.0/8, 172.16.0.0/12 192.168.0.0/16,fc00::/7") + + @Test + fun rangesMatchTheirPrefix() { + val range = WebAddressRange.parse("172.16.0.0/12") + + assertTrue(range.contains(address("172.16.0.1"))) + assertTrue(range.contains(address("172.31.255.254"))) + assertFalse(range.contains(address("172.32.0.1"))) + assertFalse(range.contains(address("fc00::1"))) + assertTrue(WebAddressRange.parse("fc00::/7").contains(address("fd12:3456::1"))) + assertTrue(WebAddressRange.parse("203.0.113.7").contains(address("203.0.113.7"))) + assertFalse(WebAddressRange.parse("203.0.113.7").contains(address("203.0.113.8"))) + assertTrue(WebAddressRange.parse("0.0.0.0/0").contains(address("198.51.100.1"))) + } + + @Test + fun rangesRejectAnythingButLiteralAddresses() { + assertFailsWith { WebAddressRange.parse("proxy.example.test") } + assertFailsWith { WebAddressRange.parse("10.0.0.0/33") } + assertFailsWith { WebAddressRange.parse("10.0.0.0/x") } + assertEquals("10.0.0.0/8", WebAddressRange.parse(" 10.0.0.0/8 ").toString()) + } + + @Test + fun anUntrustedPeerIsTheClientWhateverItForwards() { + assertEquals(address("203.0.113.7"), dockerNetworks.clientAddress(address("203.0.113.7"), "198.51.100.1")) + assertEquals(address("172.18.0.3"), WebTrustedProxies.None.clientAddress(address("172.18.0.3"), "198.51.100.1")) + } + + @Test + fun aTrustedProxyNamesTheNearestUntrustedHop() { + val caddy = address("172.18.0.3") + + assertEquals(address("198.51.100.1"), dockerNetworks.clientAddress(caddy, "198.51.100.1")) + // A client can put anything first; the proxy appends the address it really saw. + assertEquals(address("198.51.100.1"), dockerNetworks.clientAddress(caddy, "203.0.113.99, 198.51.100.1")) + assertEquals(address("198.51.100.1"), dockerNetworks.clientAddress(caddy, "198.51.100.1, 10.1.2.3")) + assertEquals(address("2001:db8::5"), dockerNetworks.clientAddress(caddy, "[2001:db8::5]:443")) + assertEquals(address("198.51.100.1"), dockerNetworks.clientAddress(caddy, "198.51.100.1:5050")) + assertEquals(caddy, dockerNetworks.clientAddress(caddy, null)) + } + + @Test + fun aHopThatIsNoAddressEndsTheWalk() { + val caddy = address("172.18.0.3") + + // Never looked up in DNS: a name ends the walk at the proxy that forwarded it. + assertEquals(caddy, dockerNetworks.clientAddress(caddy, "localhost")) + assertEquals(address("10.1.2.3"), dockerNetworks.clientAddress(caddy, "198.51.100.1, unknown, 10.1.2.3")) + // When every hop is trusted, the farthest one is the client. + assertEquals(address("10.9.9.9"), dockerNetworks.clientAddress(caddy, "10.9.9.9, 10.1.2.3")) + } +} diff --git a/support/web-common/src/test/kotlin/rylween/webcommon/WebOriginTest.kt b/support/web-common/src/test/kotlin/rylween/webcommon/WebOriginTest.kt new file mode 100644 index 00000000..8e166105 --- /dev/null +++ b/support/web-common/src/test/kotlin/rylween/webcommon/WebOriginTest.kt @@ -0,0 +1,40 @@ +package rylween.webcommon + +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class WebOriginTest { + private fun request(vararg headers: Pair): WebHttpRequest = + WebHttpRequest("POST", "/api/login", "/api/login", emptyMap(), headers.toMap(), ByteArray(0)) + + private val local = "http://localhost:8081/" + private val public = "https://rylween.example.net/" + + @Test + fun aPageFromTheServerItselfPasses() { + assertTrue(request("origin" to "http://localhost:8081", "host" to "localhost:8081").isSameOrigin(local)) + assertTrue(request("origin" to "http://192.168.1.20:8081", "host" to "192.168.1.20:8081").isSameOrigin(local)) + // Behind HTTPS on the default port, neither side names the port. + assertTrue(request("origin" to "https://rylween.example.net", "host" to "rylween.example.net").isSameOrigin(public)) + assertTrue(request("origin" to "HTTPS://Rylween.Example.Net", "host" to "rylween.example.net:443").isSameOrigin(public)) + } + + @Test + fun thePublicUrlPassesWhenAProxyRewritesHost() { + assertTrue(request("origin" to "https://rylween.example.net", "host" to "127.0.0.1:8081").isSameOrigin(public)) + } + + @Test + fun anotherSiteIsRefused() { + assertFalse(request("origin" to "https://evil.example.test", "host" to "rylween.example.net").isSameOrigin(public)) + assertFalse(request("origin" to "http://rylween.example.net", "host" to "rylween.example.net").isSameOrigin(public)) + assertFalse(request("origin" to "http://localhost:9999", "host" to "localhost:8081").isSameOrigin(local)) + assertFalse(request("origin" to "null", "host" to "localhost:8081").isSameOrigin(local)) + } + + @Test + fun aRequestFromOutsideABrowserPasses() { + assertTrue(request("host" to "localhost:8081").isSameOrigin(local)) + } +} diff --git a/support/web-common/src/test/kotlin/rylween/webcommon/auth/WebLoginThrottleTest.kt b/support/web-common/src/test/kotlin/rylween/webcommon/auth/WebLoginThrottleTest.kt new file mode 100644 index 00000000..da215897 --- /dev/null +++ b/support/web-common/src/test/kotlin/rylween/webcommon/auth/WebLoginThrottleTest.kt @@ -0,0 +1,54 @@ +package rylween.webcommon.auth + +import java.time.Duration +import java.time.Instant +import kotlin.test.Test +import kotlin.test.assertEquals + +class WebLoginThrottleTest { + private var clock = Instant.parse("2026-11-07T12:00:00Z") + private val throttle = WebLoginThrottle(maxFailures = 3, window = Duration.ofMinutes(15), now = { clock }) + + private fun advance(minutes: Long) { + clock = clock.plus(Duration.ofMinutes(minutes)) + } + + @Test + fun aClientMayFailUpToTheLimitAndThenWaitsOutTheWindow() { + repeat(2) { throttle.recordFailure("198.51.100.1") } + assertEquals(Duration.ZERO, throttle.retryAfter("198.51.100.1")) + + advance(5) + throttle.recordFailure("198.51.100.1") + assertEquals(Duration.ofMinutes(10), throttle.retryAfter("198.51.100.1")) + + advance(10) + assertEquals(Duration.ZERO, throttle.retryAfter("198.51.100.1")) + } + + @Test + fun aFailureAfterTheWindowStartsAFreshCount() { + repeat(3) { throttle.recordFailure("198.51.100.1") } + advance(15) + throttle.recordFailure("198.51.100.1") + + assertEquals(Duration.ZERO, throttle.retryAfter("198.51.100.1")) + } + + @Test + fun aSuccessClearsTheRecord() { + repeat(2) { throttle.recordFailure("198.51.100.1") } + throttle.recordSuccess("198.51.100.1") + repeat(2) { throttle.recordFailure("198.51.100.1") } + + assertEquals(Duration.ZERO, throttle.retryAfter("198.51.100.1")) + } + + @Test + fun clientsAreCountedApart() { + repeat(3) { throttle.recordFailure("198.51.100.1") } + + assertEquals(Duration.ofMinutes(15), throttle.retryAfter("198.51.100.1")) + assertEquals(Duration.ZERO, throttle.retryAfter("203.0.113.7")) + } +}