diff --git a/README.md b/README.md index b78f168..abc167a 100644 --- a/README.md +++ b/README.md @@ -31,19 +31,50 @@ room and send the invite link (or the 4-letter code) to a friend. Solo only: you can also just open `public/index.html` in a browser (the built-in synth music plays; your own tracks need the server, because browsers block loading the track list from a `file://` page). -Environment variables: `PORT` (8080), `HOST` (`::`, dual-stack IPv4 + IPv6), `TRUST_PROXY`, `ALLOWED_ORIGINS`, -`MAX_CONN_PER_IP`, `GRACE_MS`. Full reference and troubleshooting: [docs/DEPLOY.md](docs/DEPLOY.md). +Environment variables: `PORT` (8080), `HOST` (`::`, dual-stack IPv4 + IPv6), `TRUST_PROXY`, `TRUSTED_PROXIES`, +`ALLOWED_ORIGINS`, `MAX_CONN_PER_IP`, `GRACE_MS`. Full reference and troubleshooting: [docs/DEPLOY.md](docs/DEPLOY.md). ## Setup guide: Debian 13 LXC behind nginx Proxy Manager The game is one small Node process (static files + a WebSocket at `/ws`), so the proxy only has to forward HTTP and WebSockets. Nothing is stored on disk; a restart ends running games. +What was tested and what was not: the proxy side was run against a real nginx 1.26.3 loaded with the configuration that +nginx Proxy Manager (NPM) v2.16.0 generates, not against the NPM application itself, Let's Encrypt, a Proxmox LXC or a +phone. The details and the observations behind every statement below are in [docs/DEPLOY.md](docs/DEPLOY.md). + +**You need first** + +* A Debian 13 LXC (any Linux with Node 18+ works) with an IP address that NPM can reach, for example `192.168.1.50` + (`ip -br a` inside the container shows it). +* NPM already running, and a DNS name for the game (here `game.example.com`) that points at it. NPM's Let's Encrypt + request needs the name to resolve to your public address and ports 80 and 443 forwarded to NPM; that part is NPM's + own setup, see its documentation. + ### 1. Install it in the LXC (as root) ```bash -apt update && apt install -y nodejs npm git # Debian 13 ships Node 20, which is plenty (18+ works) +apt update && apt install -y nodejs npm git rsync # Debian 13 ships Node 20, which is plenty (18+ works) +``` + +Get the code into `/opt/netwall`, either **(a)** copied from your own computer (no keys needed on the LXC; run this in +the repository folder; `rsync` is needed on both sides): + +```bash +rsync -a --exclude node_modules --exclude test --exclude .git ./ root@192.168.1.50:/opt/netwall/ +``` + +or **(b)** cloned inside the LXC. That only works if the LXC may read the repository: for a private one create a key in +the LXC (`ssh-keygen -t ed25519`) and add the public key (`~/.ssh/id_ed25519.pub`) to the repository as a read-only +deploy key on your git server first (not tested here): + +```bash git clone ssh://forgejo@int.git.vanvikinternet.no/jvanvik/towerdef.git /opt/netwall +``` + +Then, in the LXC: + +```bash cd /opt/netwall && npm install --omit=dev # only "ws" useradd --system --home-dir /opt/netwall --shell /usr/sbin/nologin netwall @@ -56,28 +87,46 @@ journalctl -u netwall -f # live log ``` The service listens on `[::]:8080` (dual stack) and runs as the unprivileged `netwall` user. Change `PORT`, `HOST`, -`TRUST_PROXY` or `ALLOWED_ORIGINS` in the unit's `Environment=` lines (or `systemctl edit netwall`) and +`TRUST_PROXY`, `TRUSTED_PROXIES` or `ALLOWED_ORIGINS` in the unit's `Environment=` lines (or `systemctl edit netwall`) and `systemctl restart netwall`. If the unit fails with a sandboxing error inside an unprivileged Proxmox container, -comment out the line it names (see the notes in `deploy/netwall.service`). +comment out the line it names (see the notes in `deploy/netwall.service`). Before going on, check from the NPM host that +it can reach the game: `curl http://192.168.1.50:8080/healthz` must print `ok`. ### 2. Add a Proxy Host in nginx Proxy Manager -**Hosts > Proxy Hosts > Add Proxy Host** +**Hosts > Proxy Hosts > Add Proxy Host** (labels as in NPM v2.16.0) | Tab / field | Value | |---|---| | Details: Domain Names | `game.example.com` (your name for it) | | Details: Scheme | `http` | -| Details: Forward Hostname / IP | the LXC's IP address | +| Details: Forward Hostname / IP | the LXC's IP address (`192.168.1.50`), not `127.0.0.1` | | Details: Forward Port | `8080` | | Details: Cache Assets | **off** | -| Details: **Websockets Support** | **on** (without it the page loads but co-op cannot connect) | +| Details: **Websockets Support** | **on** (without it the page loads but co-op cannot connect: HTTP 426 on `/ws`) | +| Custom Locations | leave empty | | SSL: Certificate | Request a new SSL Certificate (Let's Encrypt), **Force SSL** on, **HTTP/2** on | -| Advanced (optional) | `proxy_read_timeout 3600s;` and `proxy_send_timeout 3600s;` for very long idle games | +| Advanced (the gear icon) | nothing needed (NPM's default 90 s timeouts are fine: a joined game streams data all the time) | -NPM passes the original `Host` header through, which is what the server's WebSocket origin check expects, so no -extra configuration is needed. If the server log ever shows `refused websocket ... does not match Host` (HTTP 403 on -the upgrade), set `ALLOWED_ORIGINS=https://game.example.com` in the unit and restart. +On the standard ports (80/443) that is all: NPM sends the public name as `Host`, which is what the server's WebSocket +origin check expects. **If you publish NPM on another port** (for example `https://game.example.com:8443`): NPM drops the +port from `Host`; the server accepts that from a proxy on a private address. If co-op still answers 403 (the log says +`refused websocket ... Origin "https://game.example.com:8443" does not match Host`), the proxy reaches the game from a +non-private address (global IPv6, Tailscale): set `TRUSTED_PROXIES=`, or +`ALLOWED_ORIGINS=https://game.example.com:8443` (**with the port**) in the unit and restart. The Advanced tab cannot +add `X-Forwarded-Host` (NPM ignores it there), so do not follow advice that says it can. + +**If something does not work.** The lobby only ever says "Could not reach the game server."; the real reason is the +HTTP status of the `/ws` request in the browser's developer tools (Network or Console) and the server log +(`journalctl -u netwall -f`): + +| Status of `/ws` | Meaning | +|---|---| +| 426 | Websockets Support is off in the Proxy Host | +| 403 | Origin check, see the paragraph above and `docs/DEPLOY.md` section 9 | +| 429 | too many sockets from one address; usually the proxy is not recognised as a proxy (`TRUSTED_PROXIES`) | +| 400 `Request Header Or Cookie Too Large` | big cookies from another app on the same domain; Advanced box: `large_client_header_buffers 4 16k;` | +| 502 | NPM cannot reach `192.168.1.50:8080`: service down, wrong IP or port, or a firewall | ### 3. IPv6 (optional) @@ -98,35 +147,38 @@ Lock the LXC down so that only the proxy can reach port 8080 (firewall example i ### 5. Update -```bash -cd /opt/netwall && git pull && npm install --omit=dev && systemctl restart netwall -``` +If you cloned it: `cd /opt/netwall && git pull && npm install --omit=dev && systemctl restart netwall`. If you copied it +with rsync: run the same `rsync` again, then `cd /opt/netwall && npm install --omit=dev && systemctl restart netwall`. Running games end with the restart (players see the room is gone and can create a new one). Under a path prefix such as `https://example.com/netwall/`, the proxy must strip the prefix; see section 7 of -[docs/DEPLOY.md](docs/DEPLOY.md). A dedicated sub-domain is simpler. +[docs/DEPLOY.md](docs/DEPLOY.md) (in NPM: a Custom Location `/netwall/` with Forward Hostname `192.168.1.50/`, both with +the trailing slash). A dedicated sub-domain is simpler. ## How to play | | | |---|---| -| **Goal** | Survive 30 waves (then keep going in endless mode). Every packet that reaches the server costs integrity. | +| **Goal** | Survive 30 waves (then keep going in endless mode) on one of seven maps. Every packet that reaches the server costs integrity. | | **Firewall** (5) | A wall. Packets path-find around it; the route preview shows how much longer it makes their trip. | | **Packet Filter** | Fast and cheap. Weak against armour. | | **IDS Sniper** | Long range, hits hard, slow. The answer to armour and bosses. | | **Flood Mortar** | Splash damage on ground swarms. Cannot hit flyers. | | **Rate Limiter** | Slows everything in range. Rootkits resist it. | | **Router Arc** | Chain lightning between nearby packets. | +| **Orbital Uplink** | The endgame weapon: a piercing beam that ignores armour, hits ground and air, blasts and slows around the target and reaches across most of the map. Very expensive to buy and to upgrade (4 levels). | | **Spoofed packets** | Fly straight over your maze: keep some anti-air. | -| **Credits** | From kills and cleared waves. Upgrade turrets to level 3; selling returns 70% (walls 100%). | +| **Credits** | From kills and cleared waves. Upgrade turrets (3 levels, 4 for the Uplink); selling returns 70% (walls 100%). | -Controls, desktop: click to build, drag to paint walls, right-click cancels, `1`-`6` pick a tower, `Space` next wave, +Controls, desktop: click to build, drag to paint walls, right-click cancels, `1`-`7` pick a tower, `Space` next wave, `U` upgrade, `X` sell, `T` change targeting, `P` pause, `F` speed, `A` auto-waves, `M` mute, wheel zoom, Alt+click pings. -Controls, touch: tap a tower type, tap the map to preview (the new route is drawn), tap the check mark (or the same cell -again) to build. Walls paint as you drag. Two fingers pan and zoom; long-press pings your partner. In portrait the board -turns 90 degrees so the cells stay big. +Controls, touch: tap a tower type, tap the map to preview (the new route is drawn), nudge the preview with the arrow +buttons if you missed the cell, then tap the check mark to build. A tap only ever acts when the finger lifts, so a pinch +never builds by accident. Walls paint as you drag. Two fingers pan and zoom; long-press pings your partner with any tool +armed. Tap a tower to get an action bar over the board (Upgrade, Sell, Target). In portrait the board turns 90 degrees +when that makes the cells bigger. ## Music @@ -170,7 +222,7 @@ reconnects automatically and resumes the same seat for a minute. npm test # rules + server: placement validation, route sealing, corner cutting, targeting, waves, economy, # protocol, rooms, reconnects, security checks, static files, dual stack npm run e2e # real browsers: desktop, phone touch (tap-to-build, drag-paint, pinch, long-press), end screens, - # two-browser co-op incl. reconnect, and a 14-size layout matrix + # two-browser co-op incl. reconnect, and a 22-layout matrix (phones, tablets, desktop, thumb reach of every control) ``` `npm run e2e` drives Chromium through Playwright (a devDependency). Install the browser once with diff --git a/deploy/netwall.service b/deploy/netwall.service index 395d4fa..8c9e645 100644 --- a/deploy/netwall.service +++ b/deploy/netwall.service @@ -27,8 +27,12 @@ Environment=PORT=8080 Environment=HOST=:: # auto: believe X-Forwarded-For / X-Forwarded-Host only from loopback / private-range peers (your proxy). Environment=TRUST_PROXY=auto -# Only needed when the proxy rewrites the Host header (symptom: 403 on the WebSocket upgrade). -# Comma separated, e.g. https://game.example.com +# Only needed when your proxy reaches this server from an address that is NOT private: a global IPv6 address, +# Tailscale / CGNAT (100.64.0.0/10), ... (symptom: the log says "from " for every player, or +# "this connection is not from a trusted proxy"). Comma separated IPs / CIDRs, added to the private ranges. +#Environment=TRUSTED_PROXIES=100.64.0.0/10,2001:db8::6 +# Only needed when the proxy rewrites the Host header or you serve several public names (symptom: 403 on the +# WebSocket upgrade). Comma separated; include the port when it is not 80/443, e.g. https://game.example.com:8443 #Environment=ALLOWED_ORIGINS=https://game.example.com #Environment=MAX_CONN_PER_IP=40 #Environment=GRACE_MS=60000 diff --git a/docs/DEPLOY.md b/docs/DEPLOY.md index 28a92c3..5767d8b 100644 --- a/docs/DEPLOY.md +++ b/docs/DEPLOY.md @@ -8,13 +8,25 @@ the co-op rooms. There is no database and no build step; games live in memory (a ◀──wss── (HOST=::, IPv4 + IPv6) ``` -What was actually run while writing this: the server and its test suite (Node 20.20.2 and 24.21), the real -`node server/index.js` over IPv4 and IPv6 on loopback (`curl`, a two-player WebSocket session, `SIGTERM` exit 0), the -IPv6-disabled case in a throwaway network namespace, and `systemd-analyze verify` on the unit (syntax only). The -proxy behaviour was only *simulated* by sending the headers a proxy would send (`Host`, `X-Forwarded-For`, -`X-Forwarded-Host`, `Origin`) straight to the server. **Never run here:** nginx Proxy Manager or any nginx, a started -systemd unit, a Proxmox LXC, a real browser or phone. Everything about NPM below is what its documented UI and -nginx's behaviour lead one to expect; labels differ between NPM versions, so check each step against your version. +What was actually run while writing and re-checking this: + +* The server and its test suite (Node 20.20.2 and 24.21), the real `node server/index.js` over IPv4 and IPv6 on loopback + (`curl`, two-player WebSocket sessions, `SIGTERM` exit 0), the IPv6-disabled case in a throwaway network namespace, + and `systemd-analyze verify` on the unit (syntax only). +* **A real nginx 1.26.3** (the Debian 13 package, unpacked without root and run in a private network namespace) loaded + with the server and location blocks that **nginx Proxy Manager v2.16.0** renders: its own `nginx.conf` (timeouts, + `real_ip`, headers), `proxy.conf` and the proxy-host and custom-location templates, taken from the NPM v2.16.0 source + and filled in by hand. Behind it ran the real game server, headless Chromium (page, service worker, co-op lobby, the + e2e scenarios over https), `curl` and raw WebSocket clients, with extra loopback addresses acting as distinct client + and proxy addresses (`203.0.113.x`, `2001:db8::x`, `192.168.77.9`). Everything marked **observed** below comes from + that setup. +* NPM's UI labels (Details / Custom Locations / SSL tabs, "Websockets Support", "Cache Assets", "Forward Hostname / IP", + the gear icon for the Advanced box) and its path-prefix handling were **read from the v2.16.0 source** + (`frontend/src/...`, `backend/internal/nginx.js`), not clicked through. Those are marked **from source**. + +**Never run:** the NPM application itself (its UI, its Docker image, its database), NPM versions other than 2.16.0, +Let's Encrypt, NPM in Docker with published ports (see "Client addresses" in section 4), a real phone, a Proxmox LXC, a +started systemd unit, a git deploy key. Labels differ between NPM versions, so check each step against yours. ## 1. Requirements @@ -37,7 +49,9 @@ useradd --system --home-dir /opt/netwall --shell /usr/sbin/nologin netwall # copy the project to /opt/netwall (from your workstation, for example): # rsync -a --exclude node_modules --exclude test --exclude .git ./ root@:/opt/netwall/ -# it needs server/, public/, package.json, package-lock.json (docs/ and deploy/ are optional) +# it needs server/, public/, package.json, package-lock.json and deploy/ (for the unit file in section 3; docs/ is optional) +# or clone it there: `git clone /opt/netwall`. That works from inside the LXC only if the LXC can read the +# repository: a private one needs an SSH key on the LXC that the git server knows (a read-only "deploy key"); see the README. cd /opt/netwall npm install --omit=dev # only "ws"; `npm ci --omit=dev` also works and follows the lockfile exactly chown -R root:root /opt/netwall # the service user only needs read access @@ -78,8 +92,9 @@ Environment variables, read when the server is started directly (`node server/in |---|---|---| | `PORT` | `8080` | TCP port. `0` picks a free one (the banner prints the real port). | | `HOST` | `::` | Address to bind. `::` is **one dual-stack socket serving IPv4 and IPv6** (`ipv6Only:false`). `0.0.0.0` = IPv4 only. `127.0.0.1` = this container only. Any explicit address is used as given. | -| `TRUST_PROXY` | `auto` | `auto`: believe `X-Forwarded-For` / `X-Real-IP` / `X-Forwarded-Host` only when the TCP peer is loopback, RFC1918 (`10/8`, `172.16/12`, `192.168/16`), `fc00::/7` or link-local. `1` (also `true`, `yes`, `on`): always believe them. `0` (also `false`, `no`, `off`): never. | -| `ALLOWED_ORIGINS` | empty | Comma separated list of extra origins allowed to open the WebSocket, for example `https://game.example.com,https://play.example.org` (list every public name if the game has more than one). See "Origin check". | +| `TRUST_PROXY` | `auto` | `auto`: believe `X-Forwarded-For` / `X-Real-IP` / `X-Forwarded-Host` (and the stripped-port rule of the "Origin check") only when the TCP peer is loopback, RFC1918 (`10/8`, `172.16/12`, `192.168/16`), `fc00::/7` or link-local, **or is listed in `TRUSTED_PROXIES`**. `1` (also `true`, `yes`, `on`): always believe them, from any peer (then firewall the port). `0` (also `false`, `no`, `off`): never. | +| `TRUSTED_PROXIES` | empty | Comma separated IPs and CIDRs (IPv4 or IPv6) that `TRUST_PROXY=auto` believes **in addition to** the private ranges above, for example `100.64.0.0/10,2001:db8::6`. Needed when your proxy reaches the game from an address the built-in list does not call private: a global IPv6 address, Tailscale / CGNAT (`100.64.0.0/10`) or any other routable one. Ignored when `TRUST_PROXY` is `1` or `0`. A malformed entry stops the start-up with a message. See "Client addresses". | +| `ALLOWED_ORIGINS` | empty | Comma separated list of extra origins allowed to open the WebSocket, for example `https://game.example.com,https://play.example.org` (list every public name if the game has more than one). **Include the port when it is not 80/443**: `https://game.example.com:8443`. See "Origin check". | | `MAX_CONN_PER_IP` | `40` | Open WebSockets per client IP; more get HTTP `429` on the upgrade. `0` disables the cap. | | `GRACE_MS` | `60000` | How long a disconnected player keeps their slot (so a phone can come back after a screen lock or a network switch). | @@ -95,20 +110,37 @@ What the server does, relevant to a proxy setup: it comes from `X-Forwarded-For` (else `X-Real-IP`); otherwise it is the TCP peer. From `X-Forwarded-For` the server takes the **rightmost entry that is not a private address**: proxies such as NPM *append* the address they saw to whatever header the client sent, so the entries further left are the client's own claim and are never believed (a - chain that is private all the way gives its rightmost entry; a client with a private LAN address cannot be told - apart from your own proxy hops, so it can still choose its own address). IPv4-mapped IPv6 peers (`::ffff:a.b.c.d`) are shown - as plain IPv4. `X-Forwarded-Proto` is never used. + chain that is private all the way gives its rightmost entry). IPv4-mapped IPv6 peers (`::ffff:a.b.c.d`) are shown + as plain IPv4. `X-Forwarded-Proto` is never used. See "Client addresses" below for what this does and does not protect + when the proxy is nginx Proxy Manager. * **Player ids.** A player's id (`pid`, kept in the browser's session storage) is what lets a browser take its slot back after a disconnect, so the server only ever sends it to its owner; the other player is shown under an opaque, stable alias. -* **Keep-alive.** Every 25 s the server sends a WebSocket protocol ping to each socket and terminates a socket that did - not answer the previous one (browsers answer automatically). The ping traffic also keeps nginx's `proxy_read_timeout` - (default 60 s) from firing on an idle but healthy game. A terminated player stays in the room for `GRACE_MS`. +* **Keep-alive and dead peers.** Every 25 s the server sends a WebSocket protocol ping to each socket and terminates a + socket that did not answer the previous one (browsers answer automatically), so a phone that silently lost the + network is dropped after 25 to 50 s (observed through nginx: first ping at 24.8 s, socket closed at 49.8 s). A + terminated player stays in the room for `GRACE_MS`. The pings are for finding dead peers; they are **not** what keeps a + proxy's idle timer quiet: a joined game receives about 20 snapshots a second, also while paused, so nginx never sees + the connection idle. Observed: a paused two-player room behind a 20 s `proxy_read_timeout` stayed connected for + 60 s (three timeouts' worth) with no reconnect, at 20.5 frames/s per browser. nginx Proxy Manager's own default is 90 s + (`proxy_connect_timeout`, `proxy_send_timeout`, `proxy_read_timeout` and `keepalive_timeout` in its v2.16.0 + `nginx.conf`), so no timeout setting is needed for the game. A socket that never joins is closed by the server after + 10 s, whatever the proxy does. * **Origin check** (WebSocket upgrade only, path `/ws`). A request without `Origin` is allowed (non-browser clients). Otherwise the origin host must equal the `Host` header, **or** the first entry of `X-Forwarded-Host` (only from a - trusted proxy), **or** be listed in `ALLOWED_ORIGINS`. Comparison is on lower-case `host[:port]` with the scheme - ignored and ports 80/443 treated as "no port" (so listing `https://game.example.com` also admits - `http://game.example.com`). Everything else gets `403`; the reason is logged. + trusted proxy), **or** (trusted proxy only) the `Host` header has **no port** and the origin has the same host name on + any port, **or** be listed in `ALLOWED_ORIGINS`. Comparison is on lower-case `host[:port]` with the scheme ignored + and ports 80/443 treated as "no port" (so listing `https://game.example.com` also admits `http://game.example.com`, + but not `https://game.example.com:8443`). Everything else gets `403`; the reason is logged. + The "no port" rule exists because nginx's `proxy_set_header Host $host` (which nginx Proxy Manager uses) **drops the + port**: published on `https://game.example.com:8443`, the browser's Origin is `https://game.example.com:8443` but the + server sees `Host: game.example.com`. Observed before the fix: 403 for both http and https on a non-default port + (`refused websocket ... Origin "https://highport.test:8332" does not match Host "highport.test"`), and the same + proxy host worked on 80/443; after it, both join. A browser talking to the server directly on its default + port 8080 (or any port other than 80/443) always sends that port in `Host`, so direct connections are still matched + exactly (observed: Origin `:9999` against Host `127.0.0.1:8331` is refused), and a different host name is still + refused (observed through the proxy). The one exception is a server you run on `PORT=80` or `443` itself: a direct + connection from a private address then also has a port-less `Host` and gets the same-host-name rule (other host names are still refused). * **Path prefix.** The server only knows `/ws` and `/`; the browser builds the socket URL relative to the page, so a proxy that strips a prefix works (section 7). * `GET /healthz` (and `HEAD`) returns `200 ok`. Static files are only served from `public/`, with @@ -119,9 +151,41 @@ What the server does, relevant to a proxy setup: * **Shutdown.** `SIGTERM`/`SIGINT`: all sockets are closed with code 1001, the process exits 0 (within about a second, forced after 5 s). Running games are lost; clients that reconnect are told the room no longer exists. +### Client addresses (per-IP cap, log) behind nginx Proxy Manager + +`MAX_CONN_PER_IP` (default 40 open WebSockets per address) counts the client address the server works out: from +`X-Forwarded-For` / `X-Real-IP` when the TCP peer is a trusted proxy, otherwise the peer itself. All of the following +was **observed** against nginx 1.26.3 with NPM v2.16.0's configuration, with the cap set to 3 to make it visible: + +* **A proxy on an address the built-in list does not call private** (a global IPv6 address, Tailscale / CGNAT + `100.64.0.0/10`; the built-in check says "not private" for `2001:db8::6` and `100.64.1.1`): with + `TRUST_PROXY=auto` the server believes no forwarded header. Three client addresses behind a proxy at `2001:db8::6` + got 3 sockets in total and `429` for the rest, and the log said `from 2001:db8::6` for everybody; with + `TRUSTED_PROXIES=2001:db8::6` each client address got its own budget (2 joined each, 6 in total) and the log named + `203.0.113.5`, `.6`, `.7`. `TRUST_PROXY=1` does the same without a list but trusts every peer, so firewall port 8080 + to the proxy if you use it. Symptom of the problem: every log line says `from `, and a few players + exhaust the cap for everyone. The same untrusted-proxy case also ignores `X-Forwarded-Host` and the stripped-port + rule of the Origin check; the 403 line in the log then says `this connection is not from a trusted proxy`. +* **Public clients cannot fake an address.** A public client sending its own `X-Forwarded-For` and `X-Real-IP` + (`198.51.100.1`, `.2`) was still counted as its real address (`203.0.113.5`): 3 sockets joined, 2 refused. +* **Clients on a private (LAN or VPN) address can choose any address.** NPM's `nginx.conf` has + `set_real_ip_from 10.0.0.0/8; 172.16.0.0/12; 192.168.0.0/16; real_ip_header X-Real-IP;`, so when the connection to NPM + comes from such an address, nginx replaces its idea of the client address with the client's own `X-Real-IP` header + *before* it builds the forwarded headers. Eight sockets from one LAN address (`192.168.77.9`), each sending a + different `X-Real-IP`, all joined and were logged as `198.51.100.1` to `.8` although the cap was 3; five sockets from the + same LAN address without the header were capped at 3. The cap is therefore a guard against accidents and against + public abuse, **not** against someone on your own LAN: rely on the firewall and on who is on the network. Nothing else + in the game depends on the client address (it only affects the cap and the log). +* **LAN players that nginx sees as one address share one budget.** Players whose connections reach nginx from the same + address (a household behind one public IP, or a router in front of the proxy) count together, which is fine at 40 + sockets (the game uses one socket per player). **Not run:** NPM in Docker with published ports and the default bridge + network, where nginx may see every LAN client as the Docker gateway address. If all your LAN players get `429` + there, raise `MAX_CONN_PER_IP`, or set it to `0` for a private game. + ## 5. nginx Proxy Manager (NPM) -In NPM, **Hosts > Proxy Hosts > Add Proxy Host**. +In NPM, **Hosts > Proxy Hosts > Add Proxy Host** (tab names and labels as in the v2.16.0 source: *Details*, *Custom +Locations*, *SSL*, and the gear icon at the right end of the tab row for the Advanced box). **Details tab** @@ -129,39 +193,77 @@ In NPM, **Hosts > Proxy Hosts > Add Proxy Host**. |---|---| | Domain Names | `game.example.com` | | Scheme | `http` | -| Forward Hostname / IP | the LXC's IP address (for example `192.168.1.50`) or a name NPM can resolve | +| Forward Hostname / IP | the LXC's IP address (for example `192.168.1.50`) or a name NPM can resolve. Not `127.0.0.1` / `localhost` when NPM runs in its own container or on another machine: that would be NPM itself | | Forward Port | `8080` | | Cache Assets | **off** (the game files must revalidate; the server already sends `no-cache`) | | Block Common Exploits | optional, can stay on | -| **Websockets Support** | **on** (required: it adds the `Upgrade` / `Connection` headers and HTTP/1.1 to the upstream) | +| **Websockets Support** | **on** (required: it adds the `Upgrade` / `Connection` headers and HTTP/1.1 to the upstream). Observed with it off: the page loads, the browser's WebSocket gets HTTP `426`, and the lobby only says "Could not reach the game server." | + +**Custom Locations tab**: leave empty (only needed for a path prefix, section 7). **SSL tab**: SSL Certificate = *Request a new SSL Certificate* (Let's Encrypt), then switch on **Force SSL** and **HTTP/2 Support** (HSTS is optional), agree to the terms, Save. Browsers fall back to HTTP/1.1 for the WebSocket; -that is normal. +that is normal. (The Let's Encrypt request itself was not run; it needs the name to resolve to your proxy and ports +80/443 reachable from the internet, see NPM's own documentation.) -**Advanced tab** (Custom Nginx Configuration): paste +**Advanced tab** (gear icon, *Custom Nginx Configuration*): nothing is required. In particular no +`proxy_read_timeout` / `proxy_send_timeout` is needed: NPM's default is 90 s, and a joined game never goes quiet +(see "Keep-alive and dead peers" in section 4). Save, then open `https://game.example.com/`. -```nginx -proxy_read_timeout 3600s; -proxy_send_timeout 3600s; -``` +### The Host header, ports other than 443, and what the Advanced tab can and cannot do -Not strictly needed (the server pings every 25 s), but it makes a long-idle game survive proxies and middleboxes -with short idle timers. Save, then open `https://game.example.com/`. +What NPM v2.16.0's `proxy.conf` sends upstream is `Host $host`, `X-Forwarded-Scheme`, `X-Forwarded-Proto`, +`X-Forwarded-For $proxy_add_x_forwarded_for` and `X-Real-IP`, plus `Upgrade` / `Connection` when Websockets Support is +on. Observed with an echo server behind the rendered config: `host` is the public name **without a port**, and there is +**no `X-Forwarded-Host` and no `X-Forwarded-Port`**. The browser's `Origin` and that `Host` match on 80/443, so +nothing needs configuring there. -NPM is expected to pass the original `Host` header through unchanged (not verified here); then the browser's `Origin` -and the `Host` the server sees match and no configuration is needed. If the server log shows -`refused websocket ... does not match Host` (HTTP 403 on the upgrade), or if you set `Host` yourself in a custom -config, either make the proxy send `X-Forwarded-Host` with the public name, or set -`ALLOWED_ORIGINS=https://game.example.com`. +* **Public port other than 80/443** (for example NPM published on `8443`, or Docker `-p 8443:443`): `$host` drops the + port, so Origin `https://game.example.com:8443` meets `Host: game.example.com`. Older versions of the server answered + `403` (observed: both `http://highport.test:8330` and `https://highport.test:8332` failed with `HTTP 403`; the same + host on 80/443 worked). The current server accepts the same host name on any port **when the connection comes from a + trusted proxy** (private address, or one listed in `TRUSTED_PROXIES`); observed: both now join, and a different host + name or a direct connection with a mismatching port is still refused. If your proxy is **not** trusted (a global IPv6 or + Tailscale address and no `TRUSTED_PROXIES`, or `TRUST_PROXY=0`), the log says `this connection is not from a trusted + proxy`: list the proxy in `TRUSTED_PROXIES`, or set `ALLOWED_ORIGINS=https://game.example.com:8443` **with the port** + (observed: an entry without the port does not match an origin with one). +* **You cannot add `X-Forwarded-Host` (or change `Host`) from the Advanced tab for the default location.** Observed: + `proxy_set_header X-Forwarded-Host $host;` and `proxy_set_header Host an.internal.name;` typed into the Advanced box + were silently ignored (the upstream still saw `Host: ` and no `X-Forwarded-Host`), because NPM renders the + Advanced text at the `server {}` level and its own `location /` sets its own `proxy_set_header` lines, so nginx + inherits none of the server-level ones. The same two lines inside a *custom location's* gear box do take effect + (observed). From source: an Advanced box that contains its own `location / {` replaces NPM's default location + completely, and then you must repeat every proxy header and the `Upgrade` / `Connection` pair yourself. + So for an NPM user the one fix that always works is `ALLOWED_ORIGINS=https://game.example.com` (with the port if it + is not 443). `X-Forwarded-Host` is for hand-written nginx: observed with a hand-written `location /` that sets + `Host an.internal.name` and `X-Forwarded-Host $host`, `TRUST_PROXY=auto` joined, `TRUST_PROXY=0` got `403`, and + `TRUST_PROXY=0` with `ALLOWED_ORIGINS=http://rw2.test` joined again. -Optional, in the same Advanced box, to compress text for phones on mobile data (the Node server does not): +Optional, in the Advanced box, to compress text for phones on mobile data (the Node server does not; NPM's own +`gzip on` only covers `text/html` by default, observed): ```nginx gzip on; -gzip_types text/css text/javascript application/javascript application/json image/svg+xml; +gzip_types text/css text/javascript application/javascript application/json application/manifest+json image/svg+xml; ``` +Observed with this list: `/`, `js/*.js`, `css/style.css`, `sw.js`, `icons/icon.svg`, `assets/music/tracks.json` and +`manifest.webmanifest` come back `Content-Encoding: gzip`; the PNG icons and mp3 files are left alone. + +Optional, if **co-op never connects but the page loads** and the browser's developer tools show the `/ws` request +answered `400 Request Header Or Cookie Too Large`: another application on the same parent domain has set big cookies, +and the browser sends them to the game too. nginx's default `large_client_header_buffers 4 8k` refuses a single header +line above 8 KB (NPM leaves that default). Observed with an 8300-byte cookie: `400` on HTTP/1.1 requests and on the +WebSocket upgrade, while the page itself still loaded over HTTP/2 (`200`); up to about 7.8 KB everything worked. Put + +```nginx +large_client_header_buffers 4 16k; +``` + +in the Advanced box (observed: cookies up to 16000 bytes then pass, upgrade included). Do not expect more: the Node +server itself refuses request headers above about 16 KB with `431` (observed at 16.3 KB), so beyond that clear the +cookies or serve the game from a name outside the cookie's domain. The game sets no cookies of its own. + ## 6. Dual stack (IPv4 + IPv6) * **The app side is automatic.** `HOST=::` (the default) is a single dual-stack socket: IPv4 clients arrive as @@ -195,9 +297,10 @@ gzip_types text/css text/javascript application/javascript application/json imag ``` `systemctl enable --now nftables`. The Proxmox firewall (Datacenter / Node / CT > Firewall) can do the same. - `TRUST_PROXY=auto` is meant for exactly this setup: only private-range peers (the proxy) are believed. If the port - is reachable by other LAN machines they could forge `X-Forwarded-For`; the effect is limited to the per-IP cap - and the log. + `TRUST_PROXY=auto` is meant for exactly this setup: only private-range peers (the proxy) are believed, plus the + addresses in `TRUSTED_PROXIES` if your proxy reaches the LXC over a global IPv6, Tailscale / `100.64.0.0/10` or other + routable address. If the port is reachable by other LAN machines they could forge `X-Forwarded-For`; the effect is + limited to the per-IP cap and the log (and see "Client addresses" for what NPM lets LAN clients do on its own). * **IPv6 disabled in the container.** If IPv6 is switched off by sysctl (`net.ipv6.conf.all.disable_ipv6=1`) the `::` socket still binds and still serves IPv4 (tested in a throwaway Linux network namespace with `disable_ipv6=1`, not in an LXC). Only a kernel without IPv6 at all fails to bind `::` @@ -210,11 +313,39 @@ gzip_types text/css text/javascript application/javascript application/json imag The client never uses absolute URLs: it opens `new URL('ws', location.href)`, so at `https://example.com/netwall/` it connects to `wss://example.com/netwall/ws`. The proxy must **strip the prefix** so the server sees `/` and `/ws`, and the page must be opened **with the trailing slash** (`/netwall/`, not `/netwall`, or the relative URLs resolve to -the wrong place). The behaviour you need is this nginx block (a trailing slash on `proxy_pass` replaces the matched -prefix): +the wrong place; nginx itself redirects `/netwall` to `/netwall/` for the locations below, observed). The simpler route +is a dedicated sub-domain (`game.example.com`), which needs none of this. Origin check: the browser's `Origin` is +`https://example.com` and `Host` is `example.com`, so it passes unchanged. + +**Way 1, in the NPM UI: the Custom Locations tab of the proxy host.** Add a location with + +| Field | Value | Why | +|---|---|---| +| Location | `/netwall/` | **with the trailing slash** | +| Scheme / Forward Port | `http` / `8080` | | +| Forward Hostname / IP | `192.168.1.50/` | **with a trailing slash after the address**: NPM turns everything after the first `/` into the path it puts on `proxy_pass`, so this renders `proxy_pass http://192.168.1.50:8080/;`, and that trailing `/` is what strips the `/netwall/` prefix | + +and keep **Websockets Support** on in the Details tab (NPM copies it into each location). The Details tab still needs a +forward target for the host's own `/`; point it at whatever else the name serves. +What was run and what was not: NPM's `_location.conf` template, filled in the way its backend does it for exactly these +values, was run in nginx (observed: `/netwall/healthz` `200`, `/netwall` answered `301` to `/netwall/`, a WebSocket +join through `wss://.../netwall/ws`, and the repo's e2e smoke scenario and two-browser co-op scenario, invite link and +reconnect included, over https at `https://.../netwall/`). That a slash typed into the +Forward Hostname field is split into the forward path is **from source** (`backend/internal/nginx.js` +`renderLocations` in v2.16.0, and the field's own placeholder there, `eg: 10.0.0.1/path/`); the UI itself was not clicked. +Two near misses, both observed, that make this fail: + +* Location `/netwall` **without** the trailing slash and a forward target ending in `/`: the page and its files load, + but `/netwall/healthz` and `/netwall/ws` are `404` (the upstream sees `//ws`), so co-op reports "Could not reach the + game server" (`WebSocket ... Unexpected response code: 404`). +* Forward Hostname `192.168.1.50` **without** the slash: nothing is stripped, so every `/netwall/...` request is `404`. + +**Way 2: the host's Advanced tab** (gear icon). Paste this block; it adds its own location next to NPM's default one, +so the host's Details tab still needs *some* forward target. Observed working verbatim (the proxy address replaced by a +local one): `/netwall/healthz` `200`, `/netwall` `301` to `/netwall/`, `manifest.webmanifest` `200`, a music file with a +`Range` header `206`, a WebSocket join through `wss://.../netwall/ws`, and the e2e smoke and co-op scenarios over https. ```nginx -location = /netwall { return 301 /netwall/; } location /netwall/ { proxy_pass http://192.168.1.50:8080/; proxy_http_version 1.1; @@ -223,15 +354,12 @@ location /netwall/ { proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Real-IP $remote_addr; - proxy_read_timeout 3600s; - proxy_send_timeout 3600s; } ``` -In NPM the dialog differs between versions (Proxy Host > **Custom locations** tab, or the Advanced tab of a host). -Whichever you use, the result must be the block above; check with `curl -i https://example.com/netwall/healthz` -(expect `200 ok`). The simpler route is a dedicated sub-domain (`game.example.com`), which needs none of this. -Origin check: the browser's `Origin` is `https://example.com` and `Host` is `example.com`, so it passes unchanged. +(An earlier version of this guide also had `location = /netwall { return 301 /netwall/; }` in front: redundant, because +nginx already answers `/netwall` with `301` to `/netwall/` for a prefix location ending in a slash; observed.) Check with +`curl -i https://example.com/netwall/healthz` (expect `200 ok`). ## 8. Verify @@ -241,19 +369,23 @@ curl -i https://game.example.com/healthz # 200 ok curl -I https://game.example.com/ # 200, Content-Security-Policy etc. curl -6 -I https://game.example.com/ # over IPv6 (once the AAAA record exists) -# WebSocket through the proxy (run in /opt/netwall, uses the installed "ws"). -# (Run here only against the local server, with the URL and origin pointed at it.) +# WebSocket through the proxy (run in /opt/netwall, uses the installed "ws"). It creates a room that disappears +# again after the 60 s grace period. For a public name on a non-default port use that port in both places. node -e " const WebSocket=require('ws'); const ws=new WebSocket('wss://game.example.com/ws',{origin:'https://game.example.com'}); ws.on('open',()=>ws.send(JSON.stringify({t:'join',pid:'deploy-check-0001',name:'check'}))); -ws.on('message',d=>{const m=JSON.parse(d);console.log(m.t,m.room||'');if(m.t==='joined'){ws.close();}}); +ws.on('message',d=>{const m=JSON.parse(d);if(m.t==='joined'){console.log('joined',m.room);process.exit(0)}}); ws.on('unexpected-response',(q,r)=>{console.log('HTTP',r.statusCode);process.exit(1)}); ws.on('error',e=>{console.log(e.message);process.exit(1)}); +setTimeout(()=>{console.log('no reply');process.exit(1)},5000); " -# prints: joined XXXX +# prints: joined XXXX (or HTTP 403 / 426 / 429 / 502, see section 9) ``` +The snippet was run (with the host replaced by a test name and certificate checking off for the self-signed +certificate) through nginx with NPM's configuration and printed `joined XXXX`. + Then open the URL on two phones, create a room on one and enter the 4-letter code on the other. ## 9. Troubleshooting @@ -261,11 +393,14 @@ Then open the URL on two phones, create a room on one and enter the 4-letter cod | Symptom | Cause and fix | |---|---| | Page loads, but the game says it cannot reach the server / WebSocket never opens | **Websockets Support** is off in the Proxy Host, or something in front strips the `Upgrade` header. Turn it on. | -| WebSocket upgrade answered with **403** | Origin check: the browser's `Origin` host differs from the `Host` the server sees. The log says `refused websocket ... Origin "..." does not match Host "..."`. Fix the proxy so `Host` is the public name, or set `ALLOWED_ORIGINS=https://game.example.com` (comma separated for several) and restart. | -| Upgrade answered with **429** | More than `MAX_CONN_PER_IP` sockets from one IP. If every visitor appears to come from the proxy, `TRUST_PROXY` is `0`, or the proxy connects from a non-private address; set `TRUST_PROXY=1`. | -| WebSocket dies after exactly 60 s | Should not happen with the defaults: the server's 25 s pings keep nginx's 60 s `proxy_read_timeout` fed. If it does, something else sits in the path with its own idle timer (a CDN, a second proxy, a firewall) that is not passing the pings, or the proxy's read timeout is shorter than 25 s. Add the `proxy_read_timeout`/`proxy_send_timeout` snippet (section 5) and check every hop. | +| The lobby only says "Could not reach the game server." | That one message covers every failed WebSocket upgrade. The browser's developer-tools console shows the real reason as `Unexpected response code: NNN`; the rows below are by that code. The server log (`journalctl -u netwall -f`) names the reason for 403 and 429. | +| WebSocket upgrade answered with **426** | **Websockets Support** is off in the Proxy Host (observed). Turn it on. | +| WebSocket upgrade answered with **403** | Origin check: the browser's `Origin` host differs from the `Host` the server sees. The log says `refused websocket from ...: Origin "..." does not match Host "..."`. On a **non-default public port** this is handled automatically for a trusted proxy (section 4, "Origin check"); if the log says `this connection is not from a trusted proxy`, list the proxy in `TRUSTED_PROXIES` (or set `TRUST_PROXY=1`). Otherwise (a proxy that rewrites `Host`, several public names) set `ALLOWED_ORIGINS=https://game.example.com` (comma separated for several, **with `:port` when it is not 80/443**) and restart. | +| Upgrade answered with **429** | More than `MAX_CONN_PER_IP` sockets from one address. If the log shows every visitor as the proxy (`from `), the proxy is not trusted: it connects from an address the `auto` list does not call private (global IPv6, `100.64.0.0/10`, ...). Set `TRUSTED_PROXIES=` (section 4, "Client addresses"). If all LAN players share one address in front of nginx, raise `MAX_CONN_PER_IP`. | +| Page loads, upgrade answered with **400** `Request Header Or Cookie Too Large` | Big cookies from another application on the same parent domain. Add `large_client_header_buffers 4 16k;` in the Advanced box (section 5), or clear the cookies. | +| WebSocket dies after exactly 60 s (or another round number) | Should not happen with the defaults: a joined game receives about 20 snapshots a second, so a proxy idle timer never fires (observed with a 20 s `proxy_read_timeout`). If it does, something else sits in the path that drops connections after a fixed time (a CDN, a second proxy, a firewall, a `proxy_read_timeout` / `proxy_send_timeout` set in the Advanced box that is far lower). Check every hop. | | Players are dropped every few seconds and reconnect | The current client treats a socket as dead after 5 s without data (snapshots arrive 20 times a second). Something is buffering or throttling the stream; look at the proxy's buffering settings and at CPU use of the LXC. | -| **502 Bad Gateway** | NPM cannot reach the upstream. `systemctl status netwall`; from the NPM host run `curl -i http://:8080/healthz`; check forward IP/port, the firewall (section 6) and that `HOST` is not `127.0.0.1`. | +| **502 Bad Gateway** | NPM cannot reach the upstream. (A browser that has loaded the game before still gets the cached app and can play solo while this lasts: observed in Chromium through nginx for 502; 503 and 504 take the same path in the service worker and are covered by a unit test.) `systemctl status netwall`; from the NPM host run `curl -i http://:8080/healthz`; check forward IP/port, the firewall (section 6) and that `HOST` is not `127.0.0.1`. | | `listen EADDRINUSE` in the log, service restarts in a loop | Another process uses the port (`ss -ltnp | grep 8080`), or two copies are running. Change `PORT` and the NPM forward port together. | | `IPv6 is not available (...); falling back to 0.0.0.0` | The kernel has no IPv6 at all. IPv4 keeps working; nothing to do, or set `HOST=0.0.0.0` to silence it. With IPv6 merely disabled by sysctl the `::` bind still works. | | IPv6 visitors cannot connect, IPv4 can | The `AAAA` record points somewhere that does not answer on 443, or NPM/the firewall is not listening on IPv6. Test `curl -6 -I https://game.example.com/`. The app itself is dual-stack. | diff --git a/docs/NEXT.md b/docs/NEXT.md index 415a6d3..445a6f2 100644 --- a/docs/NEXT.md +++ b/docs/NEXT.md @@ -14,7 +14,7 @@ Development was paused on purpose before the fix stage. This file is the entry p | `tools/bot.js` | Headless balance bot (dev tool). Complete; its results are summarised in `docs/BALANCE.md`. | | Deploy | `docs/DEPLOY.md`, `deploy/netwall.service`, README setup guide. Never run against a real nginx Proxy Manager or on a phone yet (an NPM-style review found doc inaccuracies, listed in the findings). | -`npm test` = 80 passing (20 sim + 59 server + 1 balance-table shape test). Verified from a fresh `git clone`. +`npm test` = 91 passing. `npm run e2e` = 9 scenarios (22-layout matrix, touch precision, selection/sell, info-panel stability, UI states, co-op). Verified from a fresh `git clone` earlier (2026-10-09). ## Fixed since this was written @@ -29,9 +29,9 @@ and a check that the layout holds on **tablets and foldables**. | Wave | Content | State | |---|---|---| -| 1 | Phone panels/layout + touch precision (one owner of main.js/style.css), proxy/server doc fixes, QA | running / see git log | +| 1 | Phone panels/layout + touch precision (one owner of main.js/style.css), proxy/server doc fixes, QA | **done 2026-10-10** (QA passed) | | 2 | Co-op robustness (stalled-render tower loss, half-open sockets, idempotent upgrade/wave), audio + keyboard + a11y | drafted | -| 3 | Content: Orbital Uplink client side (glyph, beam, hotkey), new towers/enemies (healer, shielded, Sandbox, Load Balancer), 4 new maps (in sim already) | sim half done | +| 3 | Content: new towers/enemies (healer, shielded, Sandbox, Load Balancer). Done already: Orbital Uplink (sim, glyph, beam, sound, help), 4 new maps (Canyon, Archipelago, Fortress, Pinwheel) | in progress | | 4 | Attack-vs-defend versus mode, bots for both sides | design in `docs/VERSUS.md` | | 5 | Difficulty picker + ONE time-boxed balance pass (IDS dominance, weak Mortar/Arc, credit pile-up; maze stays strong) | after 3 and 4 | | 6 | Server leaderboard (needs `StateDirectory=netwall` + `DATA_DIR`; solo scores are client-reported) and an opt-in public room list | after 5 | diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index 961be2d..1313f20 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -15,11 +15,13 @@ Transport: one WebSocket per player at `ws(s):///ws`, JSON text frames, on ``` createServer({ port = 8080, host = '::', publicDir = /public, graceMs = 60000, snapshotHz = 20, maxRooms = 50, - trustProxy = 'auto', allowedOrigins = [], maxConnPerIp = 40, pingMs = 25000, log = console.log }) + trustProxy = 'auto', trustedProxies = null, allowedOrigins = [], maxConnPerIp = 40, pingMs = 25000, + log = console.log }) -> Promise<{ port, addresses: string[], close(): Promise, rooms: Map }> ``` -Env when run directly: `PORT` (8080), `HOST` (`::`), `TRUST_PROXY` (`auto`|`1`|`0`), `ALLOWED_ORIGINS` -(comma separated, e.g. `https://game.example.com`), `MAX_CONN_PER_IP`, `GRACE_MS`. +Env when run directly: `PORT` (8080), `HOST` (`::`), `TRUST_PROXY` (`auto`|`1`|`0`), `TRUSTED_PROXIES` (comma separated +IPs / CIDRs added to the private ranges that `auto` trusts; a bad entry stops the start-up), `ALLOWED_ORIGINS` +(comma separated, e.g. `https://game.example.com`; include `:port` when it is not 80/443), `MAX_CONN_PER_IP`, `GRACE_MS`. Prints `http://localhost:PORT/` and every non-internal LAN URL from `os.networkInterfaces()` (IPv4 as `http://a.b.c.d:PORT/`, IPv6 as `http://[addr]:PORT/`, skip link-local `fe80::`). Handles SIGINT/SIGTERM by closing sockets and exiting 0. @@ -33,17 +35,20 @@ IPv6** (IPv4 arrives as `::ffff:a.b.c.d`; normalise it for logs). If binding `:: ### Behind a reverse proxy (nginx Proxy Manager, nginx, Caddy, Traefik) The server is meant to sit behind TLS-terminating proxies with "Websockets Support" enabled and must work both at a domain root and under a path prefix the proxy strips. -* **Keep-alive.** Proxies drop idle connections (nginx `proxy_read_timeout` defaults to 60 s). Every `pingMs` - the server sends a WebSocket *protocol* ping to each socket and terminates sockets that did not pong since the - previous round (so a dead mobile client is noticed within ~2 rounds and goes into the grace period). +* **Keep-alive.** Every `pingMs` the server sends a WebSocket *protocol* ping to each socket and terminates sockets + that did not pong since the previous round (so a dead mobile client is noticed within ~2 rounds and goes into the + grace period). The pings are for dead-peer detection: a joined socket gets ~20 snapshots/s anyway, which is what + keeps a proxy's idle timer (nginx `proxy_read_timeout`; 60 s by default, 90 s in nginx Proxy Manager) quiet. * **Real client IP** is used only for logging and the per-IP socket cap `maxConnPerIp`. `trustProxy:'auto'` - means: if the TCP peer is loopback / RFC1918 / `fc00::/7` / link-local, take the client IP from + means: if the TCP peer is loopback / RFC1918 / `fc00::/7` / link-local (or listed in `trustedProxies`), take the client IP from `X-Forwarded-For` (else `X-Real-IP`): the *rightmost* entry that is not a private address (proxies append, so entries further left are the client's own forgeable claim); otherwise use the TCP peer and ignore those headers. `true`/`false` force it. `maxConnPerIp: 0` disables the cap. Reject extra sockets with HTTP `429` on upgrade. * **Origin check** (see below) accepts: Origin host == `Host` header; or == `X-Forwarded-Host` when the proxy is - trusted; or the Origin is listed in `allowedOrigins`. Compare scheme-less `host[:port]`, treat default ports - (80/443) as equal to "no port", case-insensitive. + trusted; or, when the proxy is trusted and `Host` has **no port**, the same host name on any port (nginx's + `Host $host`, which nginx Proxy Manager uses, drops the port of `https://game.example.com:8443`); or the Origin is + listed in `allowedOrigins`. Compare scheme-less `host[:port]`, treat default ports (80/443) as equal to "no port", + case-insensitive. * **No absolute URLs, no hard-coded port** anywhere in served content; the client builds the socket URL relative to the page (`new URL('ws', location.href)` with `http->ws`, `https->wss`), so `https://x.example/netwall/` proxied to `/` works. The server therefore accepts the upgrade on path `/ws` only (the proxy strips any prefix). @@ -61,8 +66,9 @@ at a domain root and under a path prefix the proxy strips. `Content-Security-Policy: default-src 'self'; connect-src 'self' ws: wss:; img-src 'self' data:; style-src 'self' 'unsafe-inline'; media-src 'self' data:; base-uri 'none'; frame-ancestors 'none'`. ### WebSocket upgrade -* Only on path `/ws`. If the request has an `Origin` header, its host must equal the `Host` header, - else `403` (stops random web pages from driving a LAN server). No `Origin` (non-browser clients/tests) is fine. +* Only on path `/ws`. If the request has an `Origin` header, its host must equal the `Host` header (or one of the + trusted-proxy / `allowedOrigins` cases above), else `403` (stops random web pages from driving a LAN server). No + `Origin` (non-browser clients/tests) is fine. * A socket that has not sent a valid `join` within **10 s** is closed (4408). * Per-socket rate limit: token bucket 60 msg/s, burst 120; beyond that close with 4429. * More than 20 malformed/unknown messages on a socket -> close 4400. diff --git a/e2e/scenarios/05-layout-matrix.js b/e2e/scenarios/05-layout-matrix.js index e9c905e..4092251 100644 --- a/e2e/scenarios/05-layout-matrix.js +++ b/e2e/scenarios/05-layout-matrix.js @@ -1,32 +1,288 @@ -const sleep = (ms) => new Promise(r => setTimeout(r, ms)); -const sizes = [[320,568],[360,640],[375,667],[390,844],[414,896],[768,1024],[1024,768],[568,320],[667,375],[740,360],[844,390],[932,430],[1280,720],[1920,1080]]; +// Layout matrix: every control a player needs must be fully on screen, uncovered and big enough at every viewport size, +// for 6 towers (today) and for a stress palette of 10 towers and 8 maps (the planned content). +// +// For each size we drive the real UI (taps on phones, clicks on desktop) and ask the browser where things really are +// (getBoundingClientRect + document.elementFromPoint at the corners and centre), so overlapping panels, content cut by +// the screen edge and tiny targets all show up as failures. Failures are collected per size and thrown at the end. +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + +// [width, height, kind, towers] kind: 'touch' = phone/tablet (coarse pointer), 'mouse' = desktop (fine pointer); +// towers: 10 = stress palette (10+ towers, 8 maps), 6 = the content as it ships (whatever the sim defines) +const SIZES = []; +for (const [w, h] of [[320, 568], [360, 640], [375, 667], [390, 844], [414, 896], [768, 1024], [1024, 768], [568, 320], [667, 375], [740, 360], [844, 390], [932, 430], [1280, 720], [1920, 1080]]) { + SIZES.push([w, h, Math.min(w, h) < 800 ? 'touch' : 'mouse', 10]); +} +SIZES.push([1280, 720, 'mouse', 10], [1024, 768, 'mouse', 10], [800, 600, 'mouse', 10], [640, 400, 'mouse', 10]); // desktop windows (incl. 200% zoom of 1280x800) +SIZES.push([320, 568, 'touch', 6], [667, 375, 'touch', 6], [390, 844, 'touch', 6], [1280, 720, 'mouse', 6]); // the palette as it ships today + +// pretend the game ships 10 towers and 8 maps (the sim is untouched: clones of existing definitions) +function stressContent() { + let td; + Object.defineProperty(window, 'TD', { + configurable: true, + get() { return td; }, + set(v) { + td = v; + if (!v || !v.TOWERS || v.TOWERS.x7) return; + [['x7', '7', 'Test Seven'], ['x8', '8', 'Test Eight'], ['x9', '9', 'Test Nine'], ['x0', '0', 'Test Ten']].forEach(([id, key, name]) => { + v.TOWERS[id] = Object.assign({}, v.TOWERS.filter, { name, key }); + v.TOWER_ORDER.push(id); + }); + for (let i = 4; i <= 8; i++) { + const id = 'm' + i; + v.MAPS[id] = Object.assign({}, v.MAPS.open, { id, name: 'Test Map ' + i, difficulty: 1 + (i % 3) }); + v.MAP_ORDER.push(id); + } + }, + }); +} + +// ---------------------------------------------------------------- in-page probes +// Where is this element, is it entirely on screen, and does it receive pointer events at its centre and corners? +function probeFn(sel) { + const el = typeof sel === 'string' ? document.querySelector(sel) : sel; + if (!el) return { err: 'missing' }; + const cs = getComputedStyle(el), b = el.getBoundingClientRect(); + if (cs.display === 'none' || cs.visibility === 'hidden' || b.width < 1 || b.height < 1) return { err: 'hidden' }; + const e = 0.6; + const on = b.left >= -e && b.top >= -e && b.right <= innerWidth + e && b.bottom <= innerHeight + e; + let blocked = 0; + const ins = Math.min(5, b.width / 4, b.height / 4); + for (const [x, y] of [[b.left + b.width / 2, b.top + b.height / 2], [b.left + ins, b.top + ins], [b.right - ins, b.top + ins], [b.left + ins, b.bottom - ins], [b.right - ins, b.bottom - ins]]) { + const hit = document.elementFromPoint(x, y); + if (!hit || !(hit === el || el.contains(hit))) blocked++; + } + return { on, blocked, w: +b.width.toFixed(1), h: +b.height.toFixed(1), l: +b.left.toFixed(1), t: +b.top.toFixed(1), r: +b.right.toFixed(1), b: +b.bottom.toFixed(1) }; +} +const centre = (p) => ({ x: (p.l + p.r) / 2, y: (p.t + p.b) / 2 }); + module.exports = async function ({ browser, url: URL, out: OUT }) { let bad = 0; - for (const [w, h] of sizes) { - const touch = Math.min(w, h) < 800; - const ctx = await browser.newContext({ viewport: { width: w, height: h }, deviceScaleFactor: 1, isMobile: touch, hasTouch: touch }); - const page = await ctx.newPage(); - await page.goto(URL); await sleep(250); - await page.click('#btnSolo'); await sleep(150); await page.click('#btnHelpClose'); await sleep(150); - await page.evaluate(() => { document.getElementById('netChip').hidden = false; document.getElementById('netRoom').textContent = 'ABCD'; document.getElementById('netPing').textContent = '123 ms'; }); - await page.tap ? 0 : 0; - await page.click('.tbtn[data-type="ids"]'); await sleep(100); - const m = await page.evaluate(() => { - const r = (id) => document.getElementById(id).getBoundingClientRect(); - const tb = document.getElementById('topbar'), st = r('stage'), side = r('side'), pal = r('palette'); - const overflowX = document.documentElement.scrollWidth > innerWidth + 1; - const tbOver = tb.scrollWidth > tb.clientWidth + 1; - const kids = [...tb.children].filter(c => !c.hidden && getComputedStyle(c).display !== 'none').map(c => c.getBoundingClientRect()); - const clipped = kids.some(k => k.right > innerWidth + 1); - const cell = NW.app.renderer.cellSizePx(); - return { stage: [Math.round(st.width), Math.round(st.height)], topbarH: Math.round(tb.getBoundingClientRect().height), cell: +cell.toFixed(1), rot: NW.app.renderer.rot > 0, overflowX, tbOver, clipped, sideH: Math.round(side.height), palVisible: pal.bottom <= innerHeight && pal.height > 40 }; - }); - const flag = (m.overflowX || m.tbOver || m.clipped || !m.palVisible || m.cell < 12) ? ' <== CHECK' : ''; - if (flag) bad++; - console.log(`${w}x${h}`.padEnd(10), JSON.stringify(m), flag); - if (flag) await page.screenshot({ path: `${OUT}matrix-${w}x${h}.png` }); - await ctx.close(); + const allFails = []; + + for (const [w, h, kind, nTowers] of SIZES) { + const touch = kind === 'touch'; + const tag = `${w}x${h} ${kind} t${nTowers}`; + const fails = []; + const check = (ok, what) => { if (!ok) fails.push(what); }; + const mk = async (extra) => { + const ctx = await browser.newContext({ viewport: { width: w, height: h }, deviceScaleFactor: 1, isMobile: touch, hasTouch: touch, ...(extra || {}) }); + if (nTowers > 6) await ctx.addInitScript(stressContent); + const page = await ctx.newPage(); + const errors = []; + page.on('pageerror', (e) => errors.push('pageerror: ' + e.message)); + return { ctx, page, errors }; + }; + const probe = (page, sel) => page.evaluate(probeFn, sel).then((p) => p, () => ({ err: 'probe failed' })); + const tapAt = (page, x, y) => (touch ? page.touchscreen.tap(x, y) : page.mouse.click(x, y)); + // the element is on screen, fully uncovered, and (on phones) big enough to hit + const must = async (page, sel, what, o) => { + const p = await probe(page, sel); + if (p.err) { fails.push(`${what} [${sel}] ${p.err}`); return p; } + if (!p.on) fails.push(`${what} [${sel}] not fully on screen (${p.l},${p.t} - ${p.r},${p.b} in ${w}x${h})`); + if (p.blocked) fails.push(`${what} [${sel}] covered by another element (${p.blocked}/5 probe points)`); + if (touch && !(o && o.small) && Math.min(p.w, p.h) < 43.5) fails.push(`${what} [${sel}] touch target ${p.w}x${p.h} < 44`); + return p; + }; + const tapBtn = async (page, sel, what) => { + const p = await must(page, sel, what); + if (p.err) return p; + const c = centre(p); await tapAt(page, c.x, c.y); await sleep(touch ? 170 : 120); + return p; + }; + const noOverflow = async (page, what) => { + const o = await page.evaluate(() => ({ sw: document.documentElement.scrollWidth, bw: document.body.scrollWidth, iw: innerWidth, sh: document.documentElement.scrollHeight, ih: innerHeight })); + check(o.sw <= o.iw + 1 && o.bw <= o.iw + 1, `${what}: horizontal page overflow (${o.sw}/${o.bw} > ${o.iw})`); + check(o.sh <= o.ih + 1, `${what}: vertical page overflow (${o.sh} > ${o.ih})`); + }; + const allButtonsBigEnough = async (page, what) => { + if (!touch) return; + const small = await page.evaluate(() => [...document.querySelectorAll('button')].filter((b) => { + const cs = getComputedStyle(b), r = b.getBoundingClientRect(); + if (cs.display === 'none' || cs.visibility === 'hidden' || r.width < 1) return false; + if (r.bottom <= 0 || r.right <= 0 || r.top >= innerHeight || r.left >= innerWidth) return false; + let p = b.parentElement; while (p) { if (p.hidden) return false; p = p.parentElement; } + return Math.min(r.width, r.height) < 43.5; + }).map((b) => (b.id || b.className || b.textContent.trim().slice(0, 12)) + ' ' + Math.round(b.getBoundingClientRect().width) + 'x' + Math.round(b.getBoundingClientRect().height))); + if (small.length) fails.push(`${what}: touch targets < 44px: ${small.join(', ')}`); + }; + + // ------------------------------------------------ solo: menu -> help -> palette -> build -> select tower + { + const { ctx, page, errors } = await mk(); + await page.goto(URL); await sleep(300); + + // main menu: primary buttons always reachable (with 8 maps in the picker) + await must(page, '#btnSolo', 'menu Play solo'); await must(page, '#btnCoop', 'menu Co-op'); + await noOverflow(page, 'menu'); await allButtonsBigEnough(page, 'menu'); + await page.screenshot({ path: `${OUT}matrix-${w}x${h}-${kind}-${nTowers}-menu.png` }); + const p0 = await probe(page, '#btnSolo'); + await tapAt(page, centre(p0).x, centre(p0).y); await sleep(250); + + // first-run help opens by itself: it must have a visible "Got it" + const helpOpen = await page.evaluate(() => !document.getElementById('help').hidden); + check(helpOpen, 'first run: help overlay did not open'); + await must(page, '#btnHelpClose', 'help Got it'); + await noOverflow(page, 'help'); await allButtonsBigEnough(page, 'help'); + await page.screenshot({ path: `${OUT}matrix-${w}x${h}-${kind}-${nTowers}-help.png` }); + const p1 = await probe(page, '#btnHelpClose'); + if (!p1.err) await tapAt(page, centre(p1).x, centre(p1).y); + await sleep(250); + check(await page.evaluate(() => document.getElementById('help').hidden && NW.app.inGame), 'Got it did not close the help overlay'); + + // HUD: nothing clipped, no overflow, targets big enough + await noOverflow(page, 'game'); + const hud = await page.evaluate(() => { + const tb = document.getElementById('topbar'); + const kids = [...tb.children].filter((c) => !c.hidden && getComputedStyle(c).display !== 'none' && getComputedStyle(c).visibility !== 'hidden').map((c) => c.getBoundingClientRect()); + return { tbOver: tb.scrollWidth > tb.clientWidth + 1, clipped: kids.some((k) => k.right > innerWidth + 1 || k.left < -1), tbH: Math.round(tb.getBoundingClientRect().height), cell: NW.app.renderer.cellSizePx(), rot: NW.app.renderer.rot > 0 }; + }); + check(!hud.tbOver && !hud.clipped, 'top bar content overflows or is cut off'); + // stacked (portrait) layout: the stage hugs the board (no dead band above/below it, touch-4 / visual-10) and the cells are not smaller than before + const lay = await page.evaluate(() => { const st = document.getElementById('stage').getBoundingClientRect(), r = NW.app.renderer, b = r.board, rot = r.rot > 0; return { stacked: matchMedia('(orientation: portrait), (max-width: 760px) and (min-height: 521px)').matches, deadY: st.height - (rot ? b.cols : b.rows) * r.cellSizePx(), cell: r.cellSizePx() }; }); + if (lay.stacked) check(lay.deadY <= 26, `stage has ${Math.round(lay.deadY)}px of dead band above/below the board`); + const minCell = { '320x568': 11.5, '360x640': 14.3, '375x667': 15, '390x844': 19.5, '414x896': 21, '768x1024': 27 }[`${w}x${h}`]; + if (minCell && touch) check(lay.cell >= minCell, `board cells are ${lay.cell.toFixed(1)}px, expected at least ${minCell}px`); + if (touch) console.log(` ${w}x${h} cell ${lay.cell.toFixed(1)}px, stage dead band ${Math.round(lay.deadY)}px`); + await allButtonsBigEnough(page, 'game HUD'); + for (const id of ['btnMenu', 'btnWave', 'btnAuto', 'btnSpeed', 'btnPause', 'btnSound']) await must(page, '#' + id, 'top bar ' + id); + await page.screenshot({ path: `${OUT}matrix-${w}x${h}-${kind}-${nTowers}-game.png` }); + + // every tower in the palette can be picked with a real tap, and the selected state is visible + const order = await page.evaluate(() => TD.TOWER_ORDER.slice()); + check(order.length >= (nTowers > 6 ? 10 : 1), `palette has only ${order.length} towers`); + let reachable = 0; + for (const type of order) { + let p = await probe(page, `.tbtn[data-type="${type}"]`); + if (p.err) { fails.push(`palette tile ${type}: ${p.err}`); continue; } + if (!p.on || p.blocked) { // off screen: scrolling the palette is allowed (and must be possible) + await page.evaluate((t) => { // what a swipe on the palette does: scroll it so the tile sits in the middle + const pal = document.getElementById('palette'), el = pal.querySelector(`.tbtn[data-type="${t}"]`), pr = pal.getBoundingClientRect(), er = el.getBoundingClientRect(); + pal.scrollLeft += er.left + er.width / 2 - (pr.left + pr.width / 2); pal.scrollTop += er.top + er.height / 2 - (pr.top + pr.height / 2); + }, type); + await sleep(60); + p = await probe(page, `.tbtn[data-type="${type}"]`); + } + if (!p.on || p.blocked) { fails.push(`palette tile ${type} cannot be brought fully on screen (on=${p.on} blocked=${p.blocked})`); continue; } + await tapAt(page, centre(p).x, centre(p).y); await sleep(260); // (the selected border fades in over 120 ms) + const st = await page.evaluate((t) => ({ selType: NW.app.selType, sel: !!document.querySelector(`.tbtn[data-type="${t}"].sel`) }), type); + if (st.selType !== type) { fails.push(`palette tile ${type}: tap did not select it (selType=${st.selType})`); continue; } + const sp = await probe(page, `.tbtn[data-type="${type}"]`); + const vis = await page.evaluate((t) => { const e = document.querySelector(`.tbtn[data-type="${t}"]`); return { pressed: e.getAttribute('aria-pressed'), border: getComputedStyle(e).borderTopColor, cls: e.classList.contains('sel') }; }, type); + if (!sp.on || sp.blocked || !st.sel || vis.pressed !== 'true' || vis.border !== 'rgb(77, 227, 255)') fails.push(`palette tile ${type}: selected state not visible (${JSON.stringify({ on: sp.on, blocked: sp.blocked, ...vis })})`); + else reachable++; + } + check(reachable === order.length, `only ${reachable}/${order.length} palette towers selectable and visibly selected`); + // a palette that scrolls must say so (fade / chevron hint) + const pal = await page.evaluate(() => { const p = document.getElementById('palette'); return { sx: p.scrollWidth > p.clientWidth + 1, sy: p.scrollHeight > p.clientHeight + 1, more: p.dataset.more || '' }; }); + if (pal.sx || pal.sy) check(!!pal.more, 'palette scrolls but shows no scroll affordance (data-more is empty)'); + await page.screenshot({ path: `${OUT}matrix-${w}x${h}-${kind}-${nTowers}-armed.png` }); + + // build a Packet Filter at cell (10,8) with real input + const board = await page.locator('#board').boundingBox(); + const cellPt = async (cx, cy) => { const r = await page.evaluate(([a, b]) => NW.app.renderer.cellToScreen(a, b), [cx, cy]); return { x: board.x + r.x, y: board.y + r.y }; }; + await page.evaluate(() => { document.querySelector('.tbtn[data-type="filter"]').click(); }); + let cp = await cellPt(10, 8); + await tapAt(page, cp.x, cp.y); await sleep(200); + if (touch) { + await must(page, '#btnConfirmBuild', 'build bar Build'); await must(page, '#btnCancelBuild', 'build bar Cancel'); + const bar = await probe(page, '#confirm'); + const cellBox = await page.evaluate(([a, b]) => { const r = NW.app.renderer, p = r.cellToScreen(a, b), s = r.cellSizePx() / 2; const bb = document.getElementById('board').getBoundingClientRect(); return { l: bb.left + p.x - s, r: bb.left + p.x + s, t: bb.top + p.y - s, b: bb.top + p.y + s }; }, [10, 8]); + if (!bar.err) check(bar.r < cellBox.l || bar.l > cellBox.r || bar.b < cellBox.t || bar.t > cellBox.b, 'build bar covers the cell being previewed'); + await page.screenshot({ path: `${OUT}matrix-${w}x${h}-${kind}-${nTowers}-confirm.png` }); + await tapBtn(page, '#btnConfirmBuild', 'build bar Build'); + } + await sleep(150); + check(await page.evaluate(() => NW.app.ctrl.view.towers.length === 1), 'tower was not built'); + if (!touch) await page.keyboard.press('Escape'); + + // select the placed tower (tap on the board) + cp = await cellPt(10, 8); + await tapAt(page, cp.x, cp.y); await sleep(250); + check(await page.evaluate(() => NW.app.selTower > 0), 'tapping the tower did not select it'); + const compact = await page.evaluate(() => matchMedia('(pointer: coarse), (orientation: portrait), (max-width: 760px) and (min-height: 521px), (orientation: landscape) and (max-height: 520px)').matches); + const acts = {}; + for (const a of ['up', 'sell', 'mode']) acts[a] = await must(page, `[data-act="${a}"]`, `selected tower ${a}`); + if (compact) acts.close = await must(page, '[data-act="close"]', 'selected tower close'); + await page.screenshot({ path: `${OUT}matrix-${w}x${h}-${kind}-${nTowers}-selected.png` }); + // the action bar must stay clear of the selected tower + const tb = await page.evaluate(() => { const r = NW.app.renderer, t = NW.app.ctrl.view.towers[0]; if (!t) return null; const p = r.cellToScreen(t.x, t.y), s = r.cellSizePx() / 2, bb = document.getElementById('board').getBoundingClientRect(); return { l: bb.left + p.x - s, r: bb.left + p.x + s, t: bb.top + p.y - s, b: bb.top + p.y + s }; }); + if (compact && tb) for (const [a, p] of Object.entries(acts)) { + if (p.err) continue; + if (!(p.r < tb.l || p.l > tb.r || p.b < tb.t || p.t > tb.b)) fails.push(`action ${a} covers the selected tower`); + } + await allButtonsBigEnough(page, 'tower actions'); + + // upgrade and target with real taps on the buttons + if (acts.up && !acts.up.err) { const c = centre(acts.up); await tapAt(page, c.x, c.y); await sleep(200); } + check(await page.evaluate(() => (NW.app.ctrl.view.towers[0] || {}).level === 2), 'Upgrade tap did not upgrade'); + const am = await probe(page, '[data-act="mode"]'); + if (!am.err) { await tapAt(page, centre(am).x, centre(am).y); await sleep(200); } + check(await page.evaluate(() => (NW.app.ctrl.view.towers[0] || { mode: 'first' }).mode !== 'first'), 'Target tap did not change the targeting mode'); + for (const a of ['up', 'sell', 'mode']) await must(page, `[data-act="${a}"]`, `after upgrade ${a}`); + + // deselect: close button (phones), then tapping empty board + if (compact) { + await tapBtn(page, '[data-act="close"]', 'close'); + check(await page.evaluate(() => NW.app.selTower === 0), 'close button did not deselect'); + cp = await cellPt(10, 8); await tapAt(page, cp.x, cp.y); await sleep(200); + check(await page.evaluate(() => NW.app.selTower > 0), 'could not select the tower again'); + } + const empty = await cellPt(11, 8); // an empty cell next to the tower (the action bar is on the other half of the stage) + await tapAt(page, empty.x, empty.y); await sleep(250); + check(await page.evaluate(() => NW.app.selTower === 0), 'tapping empty board did not deselect'); + // sell + cp = await cellPt(10, 8); await tapAt(page, cp.x, cp.y); await sleep(200); + await tapBtn(page, '[data-act="sell"]', 'Sell'); + check(await page.evaluate(() => NW.app.ctrl.view.towers.length === 0), 'Sell tap did not sell'); + + // end overlay buttons + await page.evaluate(() => { NW.app.ctrl.sim.lives = 0; NW.app.ctrl.sim.state = 'lost'; }); + await sleep(400); + if (await page.evaluate(() => !document.getElementById('end').hidden)) { + await must(page, '#btnAgain', 'end Play again'); await must(page, '#btnEndMenu', 'end Menu'); + await noOverflow(page, 'end'); await allButtonsBigEnough(page, 'end'); + await page.screenshot({ path: `${OUT}matrix-${w}x${h}-${kind}-${nTowers}-end.png` }); + } else fails.push('end overlay did not open when the game was lost'); + for (const e of errors) fails.push(e); + await ctx.close(); + } + + // ------------------------------------------------ co-op host waiting for a partner (real room on the real server) + { + const { ctx, page, errors } = await mk(); + await page.goto(URL); await sleep(250); + await tapBtn(page, '#btnCoop', 'menu Co-op'); + await must(page, '#btnCreate', 'lobby Create room'); await must(page, '#btnJoin', 'lobby Join'); await must(page, '#btnLobbyBack', 'lobby Back'); + await noOverflow(page, 'lobby'); await allButtonsBigEnough(page, 'lobby'); + await page.screenshot({ path: `${OUT}matrix-${w}x${h}-${kind}-${nTowers}-lobby.png` }); + await tapBtn(page, '#btnCreate', 'lobby Create room'); + let joined = false; + for (let i = 0; i < 60 && !joined; i++) { joined = await page.evaluate(() => NW.app.inGame && NW.app.ctrl.kind === 'remote' && NW.app.ctrl.status === 'joined'); if (!joined) await sleep(100); } + if (!joined) fails.push('could not create a co-op room'); + else { + await sleep(300); + const room = await page.evaluate(() => NW.app.ctrl.room); + const chip = await must(page, '#netChip', 'room chip'); + const txt = await page.evaluate(() => document.getElementById('netChip').innerText + ' ' + (document.getElementById('netChip').getAttribute('aria-label') || '')); + check(txt.includes(room), `room chip does not show the room code ${room}: "${txt}"`); + check(/invite|share/i.test(txt), `room chip does not offer to invite/share: "${txt}"`); + await noOverflow(page, 'co-op game'); + const hud = await page.evaluate(() => { const tb = document.getElementById('topbar'); const kids = [...tb.children].filter((c) => !c.hidden && getComputedStyle(c).display !== 'none').map((c) => c.getBoundingClientRect()); return { clipped: kids.some((k) => k.right > innerWidth + 1 || k.left < -1), tbOver: tb.scrollWidth > tb.clientWidth + 1 }; }); + check(!hud.clipped && !hud.tbOver, 'co-op top bar content overflows or is cut off'); + for (const id of ['btnMenu', 'btnWave', 'btnPause', 'btnSound']) await must(page, '#' + id, 'co-op top bar ' + id); + await allButtonsBigEnough(page, 'co-op HUD'); + await page.screenshot({ path: `${OUT}matrix-${w}x${h}-${kind}-${nTowers}-coop.png` }); + void chip; + } + for (const e of errors) fails.push(e); + await page.evaluate(() => { try { NW.app.ctrl.close(); } catch (e) { /* ignore */ } }); // leave the room for good (no 60 s grace period) + await ctx.close(); + } + + if (fails.length) { bad++; console.log('FAIL', tag); for (const f of fails) console.log(' - ' + f); allFails.push(tag + ': ' + fails.length); } + else console.log('ok ', tag); } - if (bad) throw new Error(bad + ' layouts have problems'); - console.log('all layouts ok'); + if (bad) throw new Error(bad + ' of ' + SIZES.length + ' layouts have problems: ' + allFails.join(' | ')); + console.log('all ' + SIZES.length + ' layouts ok'); }; diff --git a/e2e/scenarios/07-ui-info-stable.js b/e2e/scenarios/07-ui-info-stable.js new file mode 100644 index 0000000..a7c2645 --- /dev/null +++ b/e2e/scenarios/07-ui-info-stable.js @@ -0,0 +1,71 @@ +// code-2: the selected-tower panel used to be rebuilt (innerHTML) on every view.rev change. In co-op the partner's actions +// bump rev constantly, so the button under a finger was replaced between press and release and the tap was lost. +// Here a page-side timer hammers rev (a wall is built and sold every 30 ms, standing in for a busy partner) while real +// presses (down, hold 150 ms, up) land on Upgrade and Target. Every one of them must arrive, and the buttons must be the +// very same DOM nodes at the end. On the old code only a small fraction of the presses produced a click. +module.exports = async function ({ browser, url: URL }) { + const assert = (c, m) => { if (!c) throw new Error('ASSERT: ' + m); console.log('ok -', m); }; + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + const errors = []; + for (const [name, opts, touch] of [ + ['desktop mouse', { viewport: { width: 1100, height: 700 } }, false], + ['phone touch', { viewport: { width: 390, height: 844 }, deviceScaleFactor: 2, isMobile: true, hasTouch: true }, true], + ]) { + console.log('=== ' + name); + const ctx = await browser.newContext(opts); + const page = await ctx.newPage(); + page.on('pageerror', (e) => errors.push(`[${name}] pageerror: ${e.message}`)); + page.on('console', (m) => { if (m.type() === 'error') errors.push(`[${name}] console.error: ${m.text()}`); }); + const cdp = touch ? await ctx.newCDPSession(page) : null; + await page.goto(URL); await sleep(300); + await page.evaluate(() => document.getElementById('btnSolo').click()); await sleep(200); + await page.evaluate(() => document.getElementById('btnHelpClose').click()); await sleep(100); + await page.evaluate(() => { const c = NW.app.ctrl; c.sim.gold = 100000; c.send({ c: 'place', type: 'filter', x: 10, y: 8 }); }); + await sleep(200); + const board = await page.locator('#board').boundingBox(); + const cp = await page.evaluate(() => NW.app.renderer.cellToScreen(10, 8)); + if (touch) await page.touchscreen.tap(board.x + cp.x, board.y + cp.y); else await page.mouse.click(board.x + cp.x, board.y + cp.y); + await sleep(250); + assert(await page.evaluate(() => NW.app.selTower > 0), 'tower selected'); + + // watch: clicks that reach an action button, and any action button being removed from the DOM + await page.evaluate(() => { + window.__clicks = { up: 0, mode: 0 }; window.__removed = 0; + document.addEventListener('click', (e) => { const b = e.target.closest && e.target.closest('[data-act]'); if (b && window.__clicks[b.dataset.act] !== undefined) window.__clicks[b.dataset.act]++; }, true); + new MutationObserver((muts) => { for (const m of muts) for (const n of m.removedNodes) if (n.nodeType === 1 && (n.matches('[data-act]') || n.querySelector('[data-act]'))) window.__removed++; }).observe(document.getElementById('info'), { childList: true, subtree: true }); + window.__els = { up: document.querySelector('[data-act="up"]'), mode: document.querySelector('[data-act="mode"]'), sell: document.querySelector('[data-act="sell"]') }; + // the busy partner: build / sell a wall every 30 ms (each one bumps view.rev) + let i = 0; + window.__rev0 = NW.app.ctrl.view.rev; + window.__hammer = setInterval(() => { + const c = NW.app.ctrl, x = 2 + (i % 6), y = 2 + ((i >> 3) % 2), ex = c.view.towers.find((t) => t.x === x && t.y === y); + if (ex) c.send({ c: 'sell', id: ex.id }); else c.send({ c: 'place', type: 'wall', x, y }); + i++; + }, 30); + }); + + const press = async (act) => { + const r = await page.evaluate((a) => { const e = document.querySelector(`[data-act="${a}"]`).getBoundingClientRect(); return { x: e.left + e.width / 2, y: e.top + e.height / 2 }; }, act); + if (touch) { await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x: r.x, y: r.y, id: 1 }] }); await sleep(150); await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] }); } + else { await page.mouse.move(r.x, r.y); await page.mouse.down(); await sleep(150); await page.mouse.up(); } + await sleep(120); + }; + for (let i = 0; i < 2; i++) await press('up'); + for (let i = 0; i < 10; i++) await press('mode'); + const res = await page.evaluate(() => { + clearInterval(window.__hammer); + const t = NW.app.ctrl.view.towers.find((x) => x.id === NW.app.selTower); + return { clicks: window.__clicks, removed: window.__removed, revBumps: NW.app.ctrl.view.rev - window.__rev0, level: t && t.level, mode: t && t.mode, + same: ['up', 'mode', 'sell'].every((k) => document.querySelector(`[data-act="${k}"]`) === window.__els[k]) }; + }); + console.log(JSON.stringify(res)); + assert(res.revBumps > 40, `rev changed ${res.revBumps} times during the presses`); + assert(res.clicks.up === 2 && res.level === 3, `both Upgrade presses arrived (clicks ${res.clicks.up}, level ${res.level})`); + assert(res.clicks.mode === 10, `all 10 Target presses arrived (${res.clicks.mode})`); + assert(res.mode === 'strong', `10 Target taps cycled the mode to ${res.mode}`); + assert(res.removed === 0 && res.same, `no action button was replaced in the DOM (${res.removed} removals)`); + await ctx.close(); + } + if (errors.length) throw new Error('console errors:\n' + errors.join('\n')); + console.log('no console errors'); +}; diff --git a/e2e/scenarios/08-ui-states.js b/e2e/scenarios/08-ui-states.js new file mode 100644 index 0000000..7df6153 --- /dev/null +++ b/e2e/scenarios/08-ui-states.js @@ -0,0 +1,99 @@ +// Small UI states that were broken or missing on phones: toasts under reduced motion (touch-5, visual-6), toasts hidden behind +// the build bar (visual-5), the static low-integrity cue, the paused state (visual-18), the tappable room chip (visual-4). +module.exports = async function ({ browser, url: URL, out: OUT }) { + const failures = []; + const assert = (c, m) => { if (!c) { failures.push(m); console.log('FAIL -', m); } else console.log('ok -', m); }; // collect every failure (the old code fails several) + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + const errors = []; + const phone = { viewport: { width: 390, height: 844 }, deviceScaleFactor: 2, isMobile: true, hasTouch: true }; + const start = async (opts) => { + const ctx = await browser.newContext(opts); + const page = await ctx.newPage(); + page.on('pageerror', (e) => errors.push('pageerror: ' + e.message)); + page.on('console', (m) => { if (m.type() === 'error') errors.push('console.error: ' + m.text()); }); + await page.goto(URL); await sleep(300); + await page.evaluate(() => document.getElementById('btnSolo').click()); await sleep(200); + await page.evaluate(() => document.getElementById('btnHelpClose').click()); await sleep(150); + return { ctx, page }; + }; + const tryTap = (page, sel) => page.tap(sel, { timeout: 3000 }).then(() => true, () => false); // (the old UI has no such button: fail fast instead of waiting 30 s) + const rect = (page, sel) => page.evaluate((s) => { const r = document.querySelector(s).getBoundingClientRect(); return { l: r.left, t: r.top, r: r.right, b: r.bottom }; }, sel); + const overlap = (a, b) => !(a.r <= b.l || a.l >= b.r || a.b <= b.t || a.t >= b.b); + + // ---- reduced motion: the toast text stays visible, the low-integrity cue is static, and the build bar never hides the toast + for (const half of ['upper', 'lower']) { + const { ctx, page } = await start({ ...phone, reducedMotion: 'reduce' }); + await page.evaluate(() => { NW.app.ctrl.sim.gold = 0; }); + await page.evaluate(() => document.querySelector('.tbtn[data-type="filter"]').click()); + const board = await page.locator('#board').boundingBox(); + const cell = await page.evaluate((h) => NW.app.renderer.cellToScreen(h === 'upper' ? 12 : 12, h === 'upper' ? 2 : 13), half); + await page.touchscreen.tap(board.x + cell.x, board.y + cell.y); await sleep(200); // first tap: preview + build bar + await tryTap(page, '#btnConfirmBuild'); await sleep(250); // not enough credits -> toast + const t = await page.evaluate(() => { const e = document.querySelector('.toast'); if (!e) return null; const cs = getComputedStyle(e), r = e.getBoundingClientRect(); return { text: e.textContent, opacity: +cs.opacity, l: r.left, t: r.top, r: r.right, b: r.bottom }; }); + assert(t && /credits/i.test(t.text), `reduced motion (${half} half): toast exists "${t && t.text}"`); + assert(t && t.opacity > 0.9, `reduced motion (${half} half): toast is visible (opacity ${t && t.opacity})`); + const bar = await rect(page, '#confirm'); + assert(t && !overlap(t, bar), `${half} half: the toast does not overlap the build bar`); + // the server (core) stays clear of the toast + const core = await page.evaluate(() => { const b = NW.app.ctrl.board, p = NW.app.renderer.cellToScreen(b.core.x, b.core.y), bb = document.getElementById('board').getBoundingClientRect(), s = NW.app.renderer.cellSizePx() * 0.6; return { l: bb.left + p.x - s, r: bb.left + p.x + s, t: bb.top + p.y - s, b: bb.top + p.y + s }; }); + assert(t && !overlap(t, core), `${half} half: the toast does not cover the server`); + if (half === 'upper') { + await page.evaluate(() => { NW.app.ctrl.sim.lives = 3; }); await sleep(300); + const low = await page.evaluate(() => { const e = document.getElementById('statLives'), cs = getComputedStyle(e); return { cls: e.classList.contains('low'), border: cs.borderTopColor, shadow: cs.boxShadow, anim: cs.animationName }; }); + assert(low.cls && low.border === 'rgb(255, 92, 122)' && low.shadow !== 'none', 'reduced motion: low integrity shows a static red border + glow: ' + JSON.stringify(low)); + } + await page.screenshot({ path: OUT + `ui-states-toast-${half}.png` }); + await ctx.close(); + } + + // ---- paused: dimmed board, a resume pill that works, and a pause button that is not a second play triangle + { + const { ctx, page } = await start(phone); + await page.tap('#btnPause'); await sleep(250); + const p = await page.evaluate(() => ({ paused: NW.app.ctrl.view.paused, tag: !document.getElementById('pausedTag').hidden, tagText: document.getElementById('pausedTag').innerText, stage: document.getElementById('stage').classList.contains('paused'), dim: getComputedStyle(document.getElementById('stage'), '::after').backgroundColor, pressed: document.getElementById('btnPause').getAttribute('aria-pressed'), icon: document.querySelector('#btnPause use').getAttribute('href') })); + assert(p.paused && p.tag && p.stage && p.pressed === 'true', 'paused: pill shown, stage marked, button pressed ' + JSON.stringify(p)); + assert(/resume/i.test(p.tagText) && p.dim !== 'rgba(0, 0, 0, 0)', 'paused: the board is dimmed and the pill says how to resume'); + assert(p.icon === '#i-pause', 'paused: the pause button keeps its pause icon (the Wave button owns the play triangle)'); + await page.screenshot({ path: OUT + 'ui-states-paused.png' }); + const tapped = await tryTap(page, '#pausedTag'); await sleep(250); + assert(tapped && await page.evaluate(() => !NW.app.ctrl.view.paused && document.getElementById('pausedTag').hidden), 'tapping the pill resumes'); + await ctx.close(); + } + + // ---- reconnecting: the whole HUD looks dead (not only the board), apart from the menu and the room chip + { + const { ctx, page } = await start(phone); + await page.evaluate(() => { document.getElementById('reconnect').hidden = false; }); await sleep(250); + const o = await page.evaluate(() => { const g = (id) => { const cs = getComputedStyle(document.getElementById(id)); return { op: +cs.opacity, pe: cs.pointerEvents }; }; return { app: document.getElementById('app').classList.contains('offline'), wave: g('btnWave'), pause: g('btnPause'), palette: g('side'), menu: g('btnMenu') }; }); + assert(o.app && o.wave.pe === 'none' && o.wave.op < 0.6 && o.palette.pe === 'none' && o.menu.pe !== 'none', 'reconnecting: HUD dims and stops taking taps, the menu stays usable ' + JSON.stringify(o)); + await page.screenshot({ path: OUT + 'ui-states-offline.png' }); + await ctx.close(); + } + + // ---- the room chip: shows the code, pulses while alone, copies / shares the invite link when tapped + { + const ctx = await browser.newContext({ ...phone, permissions: ['clipboard-read', 'clipboard-write'] }); + const page = await ctx.newPage(); + page.on('pageerror', (e) => errors.push('pageerror: ' + e.message)); + await page.goto(URL); await sleep(300); + await page.evaluate(() => document.getElementById('btnCoop').click()); await sleep(100); + await page.evaluate(() => document.getElementById('btnCreate').click()); + for (let i = 0; i < 60 && !(await page.evaluate(() => NW.app.inGame && NW.app.ctrl.status === 'joined')); i++) await sleep(100); + await sleep(300); + const room = await page.evaluate(() => NW.app.ctrl.room); + const chip = await page.evaluate(() => { const e = document.getElementById('netChip'), r = e.getBoundingClientRect(); return { text: e.innerText, waiting: e.classList.contains('waiting'), w: r.width, h: r.height, inView: r.left >= 0 && r.right <= innerWidth && r.top >= 0 && r.bottom <= innerHeight }; }); + assert(chip.text.includes(room) && chip.inView && chip.h >= 43.5, `room chip shows ${room}, is on screen and 44px tall (${JSON.stringify(chip)})`); + assert(chip.waiting, 'room chip pulses while waiting for a partner'); + await page.evaluate(() => { navigator.share = undefined; }); + await tryTap(page, '#netChip'); await sleep(400); + const toast = await page.evaluate(() => [...document.querySelectorAll('.toast')].map((t) => t.textContent).join('|')); + assert(/copied/i.test(toast), 'tapping the chip copies the invite link: "' + toast + '"'); + const clip = await page.evaluate(() => navigator.clipboard.readText()).catch(() => ''); + assert(clip.includes('?room=' + room), 'the clipboard holds the invite link: ' + clip); + await page.evaluate(() => { try { NW.app.ctrl.close(); } catch (e) { /* ignore */ } }); + await ctx.close(); + } + if (errors.length) throw new Error('console errors:\n' + errors.join('\n')); + if (failures.length) throw new Error(failures.length + ' UI state checks failed:\n - ' + failures.join('\n - ')); + console.log('no console errors'); +}; diff --git a/e2e/scenarios/09-touch-precision.js b/e2e/scenarios/09-touch-precision.js new file mode 100644 index 0000000..80333d7 --- /dev/null +++ b/e2e/scenarios/09-touch-precision.js @@ -0,0 +1,464 @@ +// Touch precision: a pinch or a pan must never build or move anything, a long press pings, a tap with a little drift still builds, +// the nudge buttons move the pending cell one cell on screen (also when the board is drawn turned 90 degrees), and the partner sees +// where a touch is aiming. Plus the keyboard / wheel / sound fixes that went in with it (touch-1 2 9 10 11 12 16 17, coop-7, +// code-6 8 22 23). Real touch events (CDP) and real clicks, no calls into the game's own handlers. Every failure is collected, so the +// old code lists all of them. +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + +module.exports = async function ({ browser, url: URL, out: OUT }) { + const failures = [], errors = []; + let tag = ''; + const assert = (c, m) => { if (!c) { failures.push(`[${tag}] ${m}`); console.log(`FAIL - [${tag}] ${m}`); } else console.log(`ok - [${tag}] ${m}`); }; + + // a fresh solo game in a phone-sized touch context (or a desktop mouse context) + async function open(w, h, kind) { + const touch = kind !== 'mouse'; + const ctx = await browser.newContext({ viewport: { width: w, height: h }, deviceScaleFactor: 2, isMobile: touch, hasTouch: touch }); + const page = await ctx.newPage(); + page.on('pageerror', (e) => errors.push(`[${tag}] pageerror: ${e.message}`)); + page.on('console', (m) => { if (m.type() === 'error') errors.push(`[${tag}] console.error: ${m.text()}`); }); + const cdp = touch ? await ctx.newCDPSession(page) : null; + await page.goto(URL); await sleep(300); + await page.evaluate(() => document.getElementById('btnSolo').click()); await sleep(200); + await page.evaluate(() => { const b = document.getElementById('btnHelpClose'); if (!document.getElementById('help').hidden) b.click(); }); await sleep(150); + const T = { ctx, page, box: await page.locator('#board').boundingBox() }; + T.touch = (type, pts) => cdp.send('Input.dispatchTouchEvent', { type, touchPoints: pts.map((p, i) => ({ x: p.x, y: p.y, id: p.id || i + 1 })) }); + T.pt = async (cx, cy) => { const r = await page.evaluate(([a, b]) => NW.app.renderer.cellToScreen(a, b), [cx, cy]); return { x: T.box.x + r.x, y: T.box.y + r.y }; }; + T.cs = () => page.evaluate(() => NW.app.renderer.cellSizePx()); + T.st = () => page.evaluate(() => { + const a = NW.app, v = a.ctrl.view, r = a.renderer, c = document.getElementById('confirm'); + return { towers: v.towers.length, walls: v.towers.filter((t) => t.type === 'wall').length, gold: v.gold, pending: a.pending, selType: a.selType, selTower: a.selTower, + zoom: r.zoom, marks: r.marks.length, barHidden: c.hidden, hint: document.getElementById('confirmHint').textContent, wave: v.wave }; + }); + T.tap = async (p, hold) => { await T.touch('touchStart', [p]); await sleep(hold || 40); await T.touch('touchEnd', []); await sleep(70); }; + // arm a tower type; `fresh` re-arms it from scratch (no pending cell left over) + T.arm = async (type, fresh) => { await page.evaluate(([t, f]) => { const b = document.querySelector(`.tbtn[data-type="${t}"]`); if (f && NW.app.selType === t) b.click(); if (NW.app.selType !== t) b.click(); }, [type, !!fresh]); await sleep(80); }; + // a canvas point just inside the stage edge that is NOT a board cell + T.outside = () => page.evaluate(() => { const r = NW.app.renderer, b = NW.app.ctrl.board, W = r.W, H = r.H; const cv = document.getElementById('board'), bb = cv.getBoundingClientRect(); + for (const [x, y] of [[W / 2, 8], [8, H / 2], [W / 2, H - 8], [W - 8, H / 2], [10, 10], [W - 10, 10], [10, H - 10], [W - 10, H - 10]]) { const c = r.screenToCell(x, y); if (!b.inBounds(c.x, c.y) && document.elementFromPoint(bb.left + x, bb.top + y) === cv) return { x, y }; } return null; }); + T.build = (type, x, y) => page.evaluate(([t, a, b]) => NW.app.ctrl.send({ c: 'place', type: t, x: a, y: b }), [type, x, y]); + return T; + } + const close = (T) => T.ctx.close(); + const same = (a, b) => JSON.stringify(a) === JSON.stringify(b); + + for (const [w, h] of [[390, 844], [844, 390]]) { + tag = `${w}x${h}`; + console.log('=== ' + tag); + + // ---- touch-1: Firewall armed, pinch: no wall, no credits spent + { + const T = await open(w, h); await T.arm('wall'); + const a = await T.pt(8, 6), b = await T.pt(12, 6), s0 = await T.st(); + await T.touch('touchStart', [{ ...a, id: 1 }]); await sleep(30); + await T.touch('touchStart', [{ ...a, id: 1 }, { ...b, id: 2 }]); + for (let i = 1; i <= 10; i++) { await T.touch('touchMove', [{ x: a.x - i * 4, y: a.y, id: 1 }, { x: b.x + i * 4, y: b.y, id: 2 }]); await sleep(12); } + await T.touch('touchEnd', []); await sleep(100); + const s = await T.st(); + assert(s.walls === 0 && s.gold === s0.gold, `touch-1: a pinch with the Firewall armed builds no wall and spends nothing (walls ${s.walls}, gold ${s0.gold} -> ${s.gold})`); + assert(s.zoom > 1.2, `touch-1: ...and it still zooms (zoom ${s.zoom.toFixed(2)})`); + await close(T); + } + // ---- touch-2: turret armed with a pending cell: a pinch, or one finger left after it, never moves the pending cell + { + const T = await open(w, h); await T.arm('filter'); + await T.tap(await T.pt(10, 8)); + const p0 = (await T.st()).pending; + assert(p0 && p0.x === 10 && p0.y === 8, 'touch-2: first tap previews the cell (pending 10,8)'); + const a = await T.pt(6, 5), b = await T.pt(14, 5); + await T.touch('touchStart', [{ ...a, id: 1 }]); await sleep(30); + await T.touch('touchStart', [{ ...a, id: 1 }, { ...b, id: 2 }]); + for (let i = 1; i <= 8; i++) { await T.touch('touchMove', [{ x: a.x - i * 3, y: a.y, id: 1 }, { x: b.x + i * 3, y: b.y, id: 2 }]); await sleep(12); } + const mid = (await T.st()).pending; + await T.touch('touchEnd', [{ x: b.x + 24, y: b.y, id: 2 }]); await sleep(40); // finger 1 up, finger 2 stays down + for (let i = 1; i <= 6; i++) { await T.touch('touchMove', [{ x: b.x + 24 + i * 5, y: b.y + i * 3, id: 2 }]); await sleep(12); } + const left = await T.st(); + await T.touch('touchEnd', []); await sleep(100); + const end = await T.st(); + assert(same(mid, p0), `touch-2: pending stays ${JSON.stringify(p0)} during a pinch (${JSON.stringify(mid)})`); + assert(same(left.pending, p0) && same(end.pending, p0) && end.towers === 0, `touch-2: ...and with one finger left and after lifting (${JSON.stringify(left.pending)}, ${JSON.stringify(end.pending)}, towers ${end.towers})`); + assert(!end.barHidden, 'touch-2: the build bar is still up'); + await close(T); + } + // ---- touch-2 (b): a pinch whose first finger lands on a tower must not select it and drop the armed type + { + const T = await open(w, h); await T.build('filter', 9, 6); await T.arm('filter'); + const a = await T.pt(9, 6), b = await T.pt(14, 6); + await T.touch('touchStart', [{ ...a, id: 1 }]); await sleep(30); + await T.touch('touchStart', [{ ...a, id: 1 }, { ...b, id: 2 }]); + for (let i = 1; i <= 6; i++) { await T.touch('touchMove', [{ x: a.x - i * 3, y: a.y, id: 1 }, { x: b.x + i * 3, y: b.y, id: 2 }]); await sleep(12); } + await T.touch('touchEnd', []); await sleep(100); + const s = await T.st(); + assert(s.selType === 'filter' && s.selTower === 0, `touch-2: a pinch that starts on a tower keeps the armed type and selects nothing (selType ${s.selType}, selTower ${s.selTower})`); + await close(T); + } + // ---- touch-12: a third finger (palm) neither freezes the pinch nor makes the zoom jump when it lifts + { + const T = await open(w, h); const c = await T.pt(13, 8); + const f = (dx, dy, id) => ({ x: c.x + dx, y: c.y + dy, id }); + await T.touch('touchStart', [f(-30, 0, 1), f(30, 0, 2)]); + for (let i = 1; i <= 6; i++) { await T.touch('touchMove', [f(-30 - i * 6, 0, 1), f(30 + i * 6, 0, 2)]); await sleep(12); } + const z1 = (await T.st()).zoom; + await T.touch('touchStart', [f(-66, 0, 1), f(66, 0, 2), f(0, 90, 3)]); await sleep(30); + const zs = []; + for (let i = 1; i <= 4; i++) { await T.touch('touchMove', [f(-66 - i * 4, 0, 1), f(66 + i * 4, 0, 2), f(0, 90, 3)]); await sleep(12); zs.push((await T.st()).zoom); } + assert(zs[3] > z1 + 0.15, `touch-12: the pinch keeps tracking the two fingers while a palm rests on the screen (zoom ${z1.toFixed(2)} -> ${zs[3].toFixed(2)})`); + await T.touch('touchEnd', [f(-82, 0, 1), f(82, 0, 2)]); await sleep(40); // the palm lifts + const z2 = (await T.st()).zoom; + await T.touch('touchMove', [f(-84, 0, 1), f(84, 0, 2)]); await sleep(30); + const z3 = (await T.st()).zoom; + assert(Math.abs(z3 - z2) < 0.12, `touch-12: the zoom does not jump when the palm lifts (${z2.toFixed(2)} -> ${z3.toFixed(2)})`); + await T.touch('touchEnd', []); + await close(T); + } + // ---- the cell under the fingertip, after a real pinch-zoom and a two-finger pan (rotated on the tall phone): random taps pick the cell they hit + { + const T = await open(w, h); + const d0 = await T.page.evaluate(() => { const c = document.getElementById('board').getBoundingClientRect(), st = document.getElementById('stage').getBoundingClientRect(), r = NW.app.renderer; return { c: [c.width, c.height], st: [st.width, st.height], r: [r.W, r.H] }; }); + assert(Math.abs(d0.c[0] - d0.r[0]) < 0.6 && Math.abs(d0.c[1] - d0.r[1]) < 0.6 && Math.abs(d0.c[0] - d0.st[0]) < 0.6 && Math.abs(d0.c[1] - d0.st[1]) < 0.6, `hit cell: the canvas, the stage and the renderer agree on the size (${JSON.stringify(d0)})`); + const c = await T.pt(10, 8), f = (dx, dy, id) => ({ x: c.x + dx, y: c.y + dy, id }); + await T.touch('touchStart', [f(-30, 0, 1), f(30, 0, 2)]); + for (let i = 1; i <= 10; i++) { await T.touch('touchMove', [f(-30 - i * 6, 0, 1), f(30 + i * 6, 0, 2)]); await sleep(12); } + for (let i = 1; i <= 8; i++) { await T.touch('touchMove', [f(-90 - i * 5, i * 4, 1), f(90 - i * 5, i * 4, 2)]); await sleep(12); } // pan with both fingers + await T.touch('touchEnd', []); await sleep(150); + const z = await T.page.evaluate(() => ({ zoom: NW.app.renderer.zoom, px: NW.app.renderer.cam.px, py: NW.app.renderer.cam.py, rot: NW.app.renderer.rot })); + assert(z.zoom > 1.8 && (z.px !== 0 || z.py !== 0), `hit cell: zoomed and panned for real (zoom ${z.zoom.toFixed(2)}, pan ${z.px.toFixed(0)},${z.py.toFixed(0)}, rot ${z.rot.toFixed(2)})`); + let seed = 12345; const rand = () => { seed = (seed * 1664525 + 1013904223) >>> 0; return seed / 4294967296; }; + const vis = await T.page.evaluate(() => { // every cell whose centre is comfortably on screen at this zoom and pan + const r = NW.app.renderer, b = NW.app.ctrl.board, out = []; + for (let y = 0; y < b.rows; y++) for (let x = 0; x < b.cols; x++) { const p = r.cellToScreen(x, y), m = r.cellSizePx() * 0.5 + 6; if (p.x >= m && p.y >= m && p.x <= r.W - m && p.y <= r.H - m) out.push({ x, y, sx: p.x, sy: p.y, cs: r.cellSizePx() }); } + return out; + }); + let tried = 0; const wrong = []; + for (let k = vis.length - 1; k > 0; k--) { const j = Math.floor(rand() * (k + 1)); [vis[k], vis[j]] = [vis[j], vis[k]]; } + for (const v of vis) { + if (tried >= 14) break; + await T.arm('filter', true); + const p = { x: T.box.x + v.sx + (rand() - 0.5) * 0.7 * v.cs, y: T.box.y + v.sy + (rand() - 0.5) * 0.7 * v.cs }; + const top = await T.page.evaluate(([x, y]) => { const e = document.elementFromPoint(x, y); return e && e.id; }, [p.x, p.y]); + if (top !== 'board') continue; // (under a floating bar) + await T.tap(p); tried++; + const got = (await T.st()).pending; + if (!got || got.x !== v.x || got.y !== v.y) wrong.push(`${v.x},${v.y} -> ${got ? got.x + ',' + got.y : 'none'}`); + } + assert(tried >= 8 && wrong.length === 0, `hit cell: ${tried} random taps after a pinch-zoom and pan all picked the cell they hit (wrong: ${wrong.join(' ') || 'none'})`); + await close(T); + } + // ---- touch-10: a long press pings whatever is armed, and never builds or moves the pending cell + { + const T = await open(w, h); await T.arm('filter'); + await T.page.evaluate(() => { const c = NW.app.ctrl, o = c.sendMark.bind(c); window.__pings = []; c.sendMark = (x, y) => { window.__pings.push([x, y]); return o(x, y); }; }); // count the real ping calls (marks fade after 1.6 s) + const pings = () => T.page.evaluate(() => window.__pings.map((p) => p.join(','))); + await T.tap(await T.pt(10, 8)); // pending 10,8 + const lp = await T.pt(14, 5); + await T.touch('touchStart', [lp]); await sleep(700); await T.touch('touchEnd', []); await sleep(100); + const s = await T.st(); + assert(same(await pings(), ['14,5']), `touch-10: a long press pings cell 14,5 once with a turret armed (pings ${JSON.stringify(await pings())})`); + assert(same(s.pending, { x: 10, y: 8 }) && s.towers === 0, `touch-10: ...and leaves the pending cell alone (${JSON.stringify(s.pending)}, towers ${s.towers})`); + const on = await T.pt(10, 8); // a long press ON the pending cell must not count as "tap again to build" + await T.touch('touchStart', [on]); await sleep(700); await T.touch('touchEnd', []); await sleep(100); + assert((await T.st()).towers === 0 && (await pings()).length === 2, `touch-10: a long press on the previewed cell pings and does not build it (pings ${(await pings()).length})`); + await T.arm('wall'); + const wp = await T.pt(6, 9); + await T.touch('touchStart', [wp]); await sleep(700); await T.touch('touchEnd', []); await sleep(100); + const s1 = await T.st(); + assert((await pings()).length === 3 && (await pings())[2] === '6,9' && s1.walls === 0, `touch-10: a long press with the Firewall armed pings 6,9 and builds no wall (pings ${JSON.stringify(await pings())}, walls ${s1.walls})`); + await close(T); + } + // ---- touch-11: the second tap on the preview, with the finger drifting across the cell edge but inside the tap slop, still builds + { + const T = await open(w, h); await T.arm('filter'); + const c = await T.pt(10, 8), cs = await T.cs(); + await T.tap(c); + const start = { x: c.x + cs / 2 - 2, y: c.y }; // 2 px inside the cell edge ... + await T.touch('touchStart', [start]); await sleep(40); + await T.touch('touchMove', [{ x: start.x + 4, y: start.y }]); await sleep(40); // ... drifts 4 px: over the edge, under the slop + await T.touch('touchEnd', []); await sleep(120); + const s = await T.st(); + assert(s.towers === 1, `touch-11: tapping the previewed cell again with 4 px of drift builds it (towers ${s.towers}, pending ${JSON.stringify(s.pending)})`); + await close(T); + } + // ---- touch-17: a wall stroke that starts on a turret keeps the tool and paints; a plain tap on the turret still selects it + { + const T = await open(w, h); await T.build('filter', 10, 5); await T.arm('wall'); + const a = await T.pt(10, 5), b = await T.pt(10, 9); + await T.touch('touchStart', [a]); + for (let i = 1; i <= 8; i++) { await T.touch('touchMove', [{ x: a.x + (b.x - a.x) * i / 8, y: a.y + (b.y - a.y) * i / 8 }]); await sleep(16); } + await T.touch('touchEnd', []); await sleep(100); + const s = await T.st(); + assert(s.selType === 'wall' && s.selTower === 0 && s.walls >= 3, `touch-17: the stroke from a turret keeps the Firewall tool and paints (selType ${s.selType}, walls ${s.walls})`); + await T.tap(a); await sleep(100); + const s2 = await T.st(); + assert(s2.selTower > 0 && s2.selType === null, `touch-17: a plain tap on the turret selects it (selTower ${s2.selTower})`); + await close(T); + } + // ---- drag-paint still paints every cell including the first, and tap-confirm still builds + { + const T = await open(w, h); await T.arm('wall'); + const a = await T.pt(8, 5), b = await T.pt(8, 11); + await T.touch('touchStart', [a]); + for (let i = 1; i <= 12; i++) { await T.touch('touchMove', [{ x: a.x + (b.x - a.x) * i / 12, y: a.y + (b.y - a.y) * i / 12 }]); await sleep(14); } + await T.touch('touchEnd', []); await sleep(100); + const cells = await T.page.evaluate(() => NW.app.ctrl.view.towers.filter((t) => t.type === 'wall').map((t) => t.x + ',' + t.y)); + const want = []; for (let y = 5; y <= 11; y++) want.push('8,' + y); + const missing = want.filter((c) => !cells.includes(c)); + assert(missing.length === 0, `drag-paint: every cell of the stroke gets a wall, including the first (missing ${missing.join(' ') || 'none'})`); + await T.arm('filter'); + await T.tap(await T.pt(12, 8)); + const p = await T.st(); + await T.page.tap('#btnConfirmBuild'); await sleep(150); + const s = await T.st(); + assert(p.pending && p.pending.x === 12 && !p.barHidden && s.towers === cells.length + 1, `tap + Build button still builds (towers ${s.towers})`); + await close(T); + } + // ---- code-23: tapping off the board clears the pending cell and hides the build bar + { + const T = await open(w, h); await T.arm('filter'); + await T.tap(await T.pt(10, 8)); + const before = await T.st(); + const out = await T.outside(); + await T.tap({ x: T.box.x + out.x, y: T.box.y + out.y }); + const s = await T.st(); + assert(!before.barHidden && s.pending === null && s.barHidden, `code-23: a tap outside the board clears the pending cell (pending ${JSON.stringify(s.pending)}, bar hidden ${s.barHidden})`); + await close(T); + } + // ---- pointercancel: a cancelled aim drag puts the pending cell back; a cancelled stroke stops; the next tap works + { + const T = await open(w, h); await T.arm('filter'); + await T.tap(await T.pt(10, 8)); + const a = await T.pt(14, 5), b = await T.pt(15, 6); + await T.touch('touchStart', [a]); await sleep(30); + await T.touch('touchMove', [{ x: a.x + 12, y: a.y + 12 }]); await sleep(30); + const dragging = (await T.st()).pending; + await T.touch('touchCancel', []); await sleep(60); + const s = await T.st(); + assert(!same(dragging, { x: 10, y: 8 }), `pointercancel: (the aim drag did move the pending cell: ${JSON.stringify(dragging)})`); + assert(same(s.pending, { x: 10, y: 8 }), `pointercancel: a cancelled aim drag restores the pending cell (${JSON.stringify(s.pending)})`); + await T.tap(await T.pt(12, 8)); + await T.tap(await T.pt(12, 8)); + assert((await T.st()).towers === 1, 'pointercancel: a fresh tap-tap builds normally afterwards'); + await T.arm('wall'); + const w0 = (await T.st()).walls, c0 = await T.pt(6, 3), c1 = await T.pt(6, 6), c2 = await T.pt(6, 9); + await T.touch('touchStart', [c0]); await T.touch('touchMove', [c1]); await sleep(30); + await T.touch('touchCancel', []); await sleep(40); + const w1 = (await T.st()).walls; + await T.touch('touchStart', [c1]); await sleep(20); await T.touch('touchEnd', []); await sleep(60); // (a tap: one wall at most) + assert(w1 > w0, `pointercancel: the stroke before the cancel painted (${w0} -> ${w1})`); + await close(T); + } + // ---- touch-16: a stroke that is rejected cell after cell plays the error sound once + { + const T = await open(w, h); + await T.page.evaluate(() => { NW.app.ctrl.sim.gold = 12; window.__sfx = {}; const o = NW.Audio.sfx; NW.Audio.sfx = function (n) { window.__sfx[n] = (window.__sfx[n] || 0) + 1; return o.apply(this, arguments); }; }); + await T.arm('wall'); + const a = await T.pt(5, 4), b = await T.pt(5, 13); + await T.touch('touchStart', [a]); + for (let i = 1; i <= 3; i++) { await T.touch('touchMove', [{ x: a.x + (b.x - a.x) * i / 3, y: a.y + (b.y - a.y) * i / 3 }]); await sleep(20); } + await T.touch('touchEnd', []); await sleep(100); + const n = await T.page.evaluate(() => window.__sfx.error || 0); + assert(n >= 1 && n <= 1, `touch-16: one error sound for the whole stroke, not one per cell (${n})`); + await close(T); + } + // ---- coop-7: the partner builds on the previewed cell -> the preview is dropped with a toast; aiming over your own tower is not + { + const T = await open(w, h); await T.arm('filter'); + await T.tap(await T.pt(10, 8)); + await T.build('wall', 10, 8); await sleep(250); + const s = await T.st(); + const toast = await T.page.evaluate(() => [...document.querySelectorAll('.toast')].map((t) => t.textContent).join('|')); + assert(s.pending === null && s.barHidden && /just built there/.test(toast), `coop-7: a tower appearing on the previewed cell drops the preview with a toast (pending ${JSON.stringify(s.pending)}, "${toast}")`); + await T.build('filter', 12, 8); + await T.tap(await T.pt(11, 5)); + const a = await T.pt(11, 5), b = await T.pt(12, 8); // drag-aim the preview onto the tower you already own + await T.touch('touchStart', [a]); await sleep(30); + for (let i = 1; i <= 6; i++) { await T.touch('touchMove', [{ x: a.x + (b.x - a.x) * i / 6, y: a.y + (b.y - a.y) * i / 6 }]); await sleep(20); } + await T.touch('touchEnd', []); await sleep(300); + const s2 = await T.st(); + assert(same(s2.pending, { x: 12, y: 8 }), `coop-7: aiming at a cell that already holds a tower is not wiped (${JSON.stringify(s2.pending)})`); + await close(T); + } + await sleep(50); + } + + // ================================================================ nudge buttons (several sizes, also rotated) + for (const [w, h] of [[390, 844], [844, 390], [360, 640], [568, 320], [320, 568]]) { + tag = `nudge ${w}x${h}`; + console.log('=== ' + tag); + const T = await open(w, h); const page = T.page; + await T.arm('filter'); + const info = () => page.evaluate(() => { + const r = NW.app.renderer, p = NW.app.pending; if (!p) return null; + const s = r.cellToScreen(p.x, p.y), b = document.getElementById('board').getBoundingClientRect(), c = document.getElementById('confirm').getBoundingClientRect(); + return { x: p.x, y: p.y, sx: s.x + b.left, sy: s.y + b.top, cs: r.cellSizePx(), bar: { l: c.left, t: c.top, r: c.right, b: c.bottom }, hint: (document.getElementById('app').dataset.barrows === '0' ? document.getElementById('hint') : document.getElementById('confirmHint')).textContent, rot: r.rot }; + }); + const btnRect = (dir) => page.evaluate((d) => { + const el = document.querySelector(`#nudge [data-dx="${d[0]}"][data-dy="${d[1]}"]`); if (!el) return null; + const r = el.getBoundingClientRect(), hit = (x, y) => { const e = document.elementFromPoint(x, y); return e && (e === el || el.contains(e)); }; + return { l: r.left, t: r.top, r: r.right, b: r.bottom, w: r.width, h: r.height, on: r.left >= 0 && r.top >= 0 && r.right <= innerWidth && r.bottom <= innerHeight, + free: hit(r.left + 5, r.top + 5) && hit(r.right - 5, r.bottom - 5) && hit((r.left + r.right) / 2, (r.top + r.bottom) / 2) }; + }, dir); + const tapBtn = async (dir) => { const r = await btnRect(dir); await page.touchscreen.tap((r.l + r.r) / 2, (r.t + r.b) / 2); await sleep(90); }; + const overlap = (a, r, pad) => !(a.r + pad <= r.l || a.l - pad >= r.r || a.b + pad <= r.t || a.t - pad >= r.b); + + // the buttons exist, are big, on screen, uncovered, and never cover the cell being aimed at (five different cells) + let all = true, why = ''; + for (const [cx, cy] of [[3, 3], [16, 3], [3, 11], [16, 11], [10, 7]]) { + await T.arm('filter', true); // (a fresh preview each time: the bar covers part of the other half) + await T.tap(await T.pt(cx, cy)); + const i = await info(); + if (!i) { all = false; why += ` no pending at ${cx},${cy};`; continue; } + for (const d of [[-1, 0], [0, -1], [0, 1], [1, 0]]) { + const r = await btnRect(d); + if (!r) { all = false; why += ` button ${d} missing;`; continue; } + if (!r.on || !r.free || r.w < 43.5 || r.h < 43.5) { all = false; why += ` button ${d} at cell ${cx},${cy}: on=${r.on} free=${r.free} ${r.w}x${r.h};`; } + } + const cell = { l: i.sx - i.cs / 2, r: i.sx + i.cs / 2, t: i.sy - i.cs / 2, b: i.sy + i.cs / 2 }; + if (overlap(i.bar, cell, 0)) { all = false; why += ` the build bar covers cell ${cx},${cy};`; } + } + assert(all, `nudge: four on-screen, uncovered buttons of at least 44 px, and the bar never covers the aimed cell${why}`); + await page.screenshot({ path: `${OUT}touch-nudge-${w}x${h}.png` }); + if (!all) { await close(T); continue; } // (no buttons: the rest of this size cannot run) + + // each button moves the cell by one cell in that SCREEN direction (the board may be turned 90 degrees) + const dirs = { left: [-1, 0], up: [0, -1], down: [0, 1], right: [1, 0] }; + let ok = true, detail = ''; + for (const [name, d] of Object.entries(dirs)) { + const i0 = await info(); await tapBtn(d); const i1 = await info(); + const ex = i0.cs * d[0], ey = i0.cs * d[1]; + if (!i1 || Math.abs((i1.sx - i0.sx) - ex) > 1.5 || Math.abs((i1.sy - i0.sy) - ey) > 1.5) { ok = false; detail += ` ${name}: moved (${(i1.sx - i0.sx).toFixed(1)}, ${(i1.sy - i0.sy).toFixed(1)}) not (${ex.toFixed(1)}, ${ey.toFixed(1)});`; } + } + assert(ok, `nudge: left/up/down/right move the cell one cell on screen (rot ${(await info()).rot.toFixed(2)})${detail}`); + + // Build builds at the nudged cell + const i2 = await info(), t0 = (await T.st()).towers; + await page.tap('#btnConfirmBuild'); await sleep(150); + const built = await page.evaluate(() => NW.app.ctrl.view.towers.map((t) => t.x + ',' + t.y)); + assert((await T.st()).towers === t0 + 1 && built.includes(i2.x + ',' + i2.y), `nudge: Build builds at the nudged cell ${i2.x},${i2.y}`); + + // the preview and route hint follow: nudge onto a dead node and the hint turns into the reason + const dead = await page.evaluate(() => { + const b = NW.app.ctrl.board, r = NW.app.renderer; + for (let y = 0; y < b.rows; y++) for (let x = 0; x < b.cols; x++) { + if (b.obst[y * b.cols + x]) continue; + const n = r.stepCell(x, y, 0, -1); + if (b.inBounds(n.x, n.y) && b.obst[n.y * b.cols + n.x] && !NW.app.ctrl.view.towers.some((t) => t.x === x && t.y === y)) return { x, y, nx: n.x, ny: n.y }; + } + return null; + }); + await T.arm('filter', true); + if (dead) { + await T.tap(await T.pt(dead.x, dead.y)); + const h0 = (await info()).hint; await tapBtn([0, -1]); const i3 = await info(); + assert(i3.x === dead.nx && i3.y === dead.ny && /dead|✕/.test(i3.hint) && h0 !== i3.hint, `nudge: the route hint follows the nudged cell ("${h0}" -> "${i3.hint}")`); + } + // the edge of the board: nudging past it stays put (no error, no off-board cell) + await T.tap(await T.pt(0, 0)); + const e0 = await info(); for (let k = 0; k < 2; k++) { await tapBtn([-1, 0]); await tapBtn([0, -1]); } const e1 = await info(); + assert(e1 && e1.x >= 0 && e1.y >= 0, `nudge: the cell stays on the board when nudged past the edge (${e1 && e1.x},${e1 && e1.y})`); + + // the bar does not hop to the other half while you nudge across the middle: tap down, down, down... on the SAME button + await T.arm('filter', true); + await T.tap(await T.pt(2, 2)); + let flips = 0, landed = 0, steps = 0, covered = false, lastBar = (await info()).bar.t; + for (let k = 0; k < 12; k++) { + const i0 = await info(); if (!i0) break; + const r = await btnRect([0, 1]); if (!r) break; + await page.touchscreen.tap((r.l + r.r) / 2, (r.t + r.b) / 2); await sleep(90); + const i1 = await info(); steps++; + if (i1 && Math.abs((i1.sy - i0.sy) - i0.cs) < 1.5) landed++; + if (i1 && Math.abs(i1.bar.t - lastBar) > 2) { flips++; lastBar = i1.bar.t; } + if (i1 && overlap(i1.bar, { l: i1.sx - i1.cs / 2, r: i1.sx + i1.cs / 2, t: i1.sy - i1.cs / 2, b: i1.sy + i1.cs / 2 }, 0)) covered = true; + if (i1 && (i1.y >= 15 || i1.x >= 19)) break; + } + assert(landed >= 6 && flips <= 1 && !covered, `nudge: ${landed}/${steps} taps on the same button each moved the cell, the bar flipped ${flips}x and never covered the cell`); + await close(T); + } + + // ================================================================ co-op: the partner sees the touch aim and it goes away again (touch-9) + { + tag = 'coop 390x844'; + console.log('=== ' + tag); + const T = await open(390, 844); const page = T.page; + await page.evaluate(() => document.getElementById('btnMenu').click()); await sleep(100); + await page.evaluate(() => document.getElementById('btnCoop').click()); await sleep(100); + await page.fill('#inName', 'Tess'); + await page.evaluate(() => document.getElementById('btnCreate').click()); + await page.waitForFunction(() => NW.app.ctrl && NW.app.ctrl.kind === 'remote' && NW.app.ctrl.room && !document.getElementById('lobby').hidden === false, null, { timeout: 8000 }).catch(() => {}); + await sleep(600); + const remote = await page.evaluate(() => NW.app.ctrl.kind === 'remote' && !!NW.app.ctrl.room); + assert(remote, 'co-op room created'); + if (remote) { + T.box = await page.locator('#board').boundingBox(); + await page.evaluate(() => { const c = NW.app.ctrl; window.__cur = []; const o = c._send.bind(c); c._send = (m) => { if (m.t === 'cursor') window.__cur.push({ x: m.x, y: m.y }); return o(m); }; }); + const cur = () => page.evaluate(() => window.__cur.slice()); + await T.arm('filter'); + await T.tap(await T.pt(10, 8)); await sleep(150); + let c = await cur(); + assert(c.some((m) => m.x === 10.5 && m.y === 8.5), `touch-9: a plain tap shows a cursor on the partner's board (${JSON.stringify(c.slice(-2))})`); + await page.tap('#btnCancelBuild'); await sleep(150); + c = await cur(); + assert(c.length && c[c.length - 1].x === null, `touch-9: Cancel clears it (last ${JSON.stringify(c[c.length - 1])})`); + await T.arm('wall'); const before = (await cur()).length; + const a = await T.pt(6, 4), b = await T.pt(6, 9); + await T.touch('touchStart', [a]); + for (let i = 1; i <= 8; i++) { await T.touch('touchMove', [{ x: a.x + (b.x - a.x) * i / 8, y: a.y + (b.y - a.y) * i / 8 }]); await sleep(40); } + c = await cur(); + const during = c.slice(before).some((m) => m.x !== null); + await T.touch('touchEnd', []); await sleep(150); + c = await cur(); + assert(during && c[c.length - 1].x === null, `touch-9: a wall stroke shows the cursor and lifting the finger clears it (shown ${during}, last ${JSON.stringify(c[c.length - 1])})`); + // a clear straight after a move is not swallowed by the 70 ms throttle + const r = await page.evaluate(() => { const c = NW.app.ctrl; c.lastCursor = -1e9; window.__cur.length = 0; c.sendCursor(3, 3); c.sendCursor(null, null); return window.__cur.slice(); }); + assert(r.length === 2 && r[1].x === null, `touch-9: sendCursor(null) bypasses the throttle (${JSON.stringify(r)})`); + } + await close(T); + } + + // ================================================================ desktop: keyboard, wheel, mouse + { + tag = 'desktop 1280x800'; + console.log('=== ' + tag); + // code-6: a held Space is one wave + let T = await open(1280, 800, 'mouse'); let page = T.page; + await page.keyboard.down(' '); + for (let i = 0; i < 20; i++) { await page.keyboard.down(' '); await sleep(15); } + await page.keyboard.up(' '); await sleep(150); + let s = await T.st(); + assert(s.wave === 1, `code-6: holding Space (20 key repeats) starts one wave (wave ${s.wave})`); + // code-8: Enter on the focused Menu button opens the menu instead of starting a wave + await page.focus('#btnMenu'); await page.keyboard.press('Enter'); await sleep(200); + const menuOpen = await page.evaluate(() => !document.getElementById('menu').hidden); + s = await T.st(); + assert(menuOpen && s.wave === 1, `code-8: Enter on the focused Menu button opens the menu and starts no wave (menu open ${menuOpen}, wave ${s.wave})`); + await page.keyboard.press('Escape'); await sleep(100); + // code-22: the wheel zooms in proportion to the scroll distance + const c = await T.pt(10, 8); + await page.mouse.move(c.x, c.y); + for (let i = 0; i < 6; i++) await page.mouse.wheel(0, -1); + await sleep(100); + const z1 = (await T.st()).zoom; + assert(z1 < 1.05, `code-22: six tiny wheel events barely zoom (zoom ${z1.toFixed(3)})`); + await page.mouse.wheel(0, -100); await sleep(100); + const z2 = (await T.st()).zoom; + assert(z2 > 1.08 && z2 < 1.3, `code-22: one 100-unit wheel notch is about 1.16x (zoom ${z2.toFixed(3)})`); + await close(T); + + // touch-17 with the mouse: press on a turret with the Firewall armed and drag + T = await open(1280, 800, 'mouse'); page = T.page; + await T.build('filter', 10, 5); await T.arm('wall'); + const a = await T.pt(10, 5), b = await T.pt(10, 9); + await page.mouse.move(a.x, a.y); await page.mouse.down(); + for (let i = 1; i <= 8; i++) { await page.mouse.move(a.x + (b.x - a.x) * i / 8, a.y + (b.y - a.y) * i / 8); await sleep(16); } + await page.mouse.up(); await sleep(100); + s = await T.st(); + assert(s.selType === 'wall' && s.selTower === 0 && s.walls >= 3, `touch-17 (mouse): a stroke from a turret keeps the Firewall tool and paints (selType ${s.selType}, walls ${s.walls})`); + await page.mouse.click(a.x, a.y); await sleep(100); + s = await T.st(); + assert(s.selTower > 0, `touch-17 (mouse): a plain click on the turret selects it (selTower ${s.selTower})`); + await close(T); + } + + if (errors.length) failures.push('console errors:\n' + errors.join('\n')); + if (failures.length) throw new Error(failures.length + ' check(s) failed:\n ' + failures.join('\n ')); + console.log('touch precision: all checks passed'); +}; diff --git a/public/css/style.css b/public/css/style.css index 61086ca..8a91cc0 100644 --- a/public/css/style.css +++ b/public/css/style.css @@ -1,11 +1,20 @@ -/* Netwall - styles. Dark "network operations" theme. Mobile-first: portrait phones, landscape phones, desktop. */ +/* Netwall - styles. Dark "network operations" theme. Mobile-first: portrait phones, landscape phones, desktop. + * + * Layout modes (see main.js layoutApp for the JS half): + * wide stage | side panel (320px). Desktop and tablets in landscape. Tower actions live in the side panel. + * stacked top bar / stage / side panel. Portrait phones and narrow windows: (orientation: portrait), (max-width: 760px) and (min-height: 521px) + * short stage | narrow side panel, one-row top bar. Landscape phones: (orientation: landscape) and (max-height: 520px) + * compact #app[data-ui="compact"]: stacked OR short OR a coarse pointer. Here the selected tower's actions float over the + * stage as a bar (placed on the half of the stage away from the tower), and every target is at least 44px. + * Everything that has to be reachable (primary buttons, tower actions, room code) is positioned, never scrolled to. + */ :root { --bg: #070b16; --panel: #0c1322; --panel2: #111b30; --line: #1d2c4c; --text: #d3e6ff; - --dim: #7f97bd; + --dim: #8ea6cc; --cyan: #4de3ff; --amber: #ffd24d; --red: #ff5c7a; @@ -16,11 +25,13 @@ --safe-b: env(safe-area-inset-bottom, 0px); --safe-l: env(safe-area-inset-left, 0px); --btn: 40px; + --tile-h: 66px; + --bar-h: 54px; + --nudge-h: 52px; /* the build bar is this much taller than the tower bar: it has a row of nudge buttons */ --aspect: 26 / 16; --font: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; --mono: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace; } -@media (pointer: coarse) { :root { --btn: 46px; } } * { box-sizing: border-box; -webkit-tap-highlight-color: transparent; } html, body { @@ -40,7 +51,7 @@ svg.ic { width: 1.25em; height: 1.25em; flex: none; } grid-template-columns: minmax(0, 1fr) var(--side-w); grid-template-rows: auto minmax(0, 1fr); grid-template-areas: "top top" "stage side"; - padding: var(--safe-t) var(--safe-r) var(--safe-b) var(--safe-l); + padding: var(--safe-t) var(--safe-r) var(--safe-b) var(--safe-l); /* the one place the safe-area insets are applied */ background: radial-gradient(1200px 600px at 20% -10%, #0f1f3d 0%, transparent 60%), radial-gradient(900px 500px at 100% 110%, #1b1035 0%, transparent 55%), var(--bg); @@ -48,18 +59,19 @@ svg.ic { width: 1.25em; height: 1.25em; flex: none; } #topbar { grid-area: top; display: flex; align-items: center; flex-wrap: wrap; gap: 6px 8px; padding: 6px 10px; background: rgba(8, 13, 26, .85); border-bottom: 1px solid var(--line); } #stage { grid-area: stage; position: relative; min-width: 0; min-height: 0; overflow: hidden; touch-action: none; } #side > * { flex: none; } -#side { grid-area: side; display: flex; flex-direction: column; gap: 10px; padding: 10px; overflow-y: auto; border-left: 1px solid var(--line); background: rgba(8, 13, 26, .7); -webkit-overflow-scrolling: touch; } +/* (no transform / filter / mask / contain on #side or #info: the tower action bar is position:fixed inside them) */ +#side { grid-area: side; display: flex; flex-direction: column; gap: 10px; padding: 10px; overflow-y: auto; border-left: 1px solid var(--line); background: rgba(8, 13, 26, .7); } #board { position: absolute; inset: 0; width: 100%; height: 100%; display: block; touch-action: none; outline: none; } -/* portrait phones / narrow windows: board on top, panels underneath */ +/* stacked: portrait phones and narrow windows. main.js sets --stage-h so the stage hugs the board (no dead bands) and the side panel gets the rest */ @media (orientation: portrait), (max-width: 760px) and (min-height: 521px) { - #app { grid-template-columns: minmax(0, 1fr); grid-template-rows: auto auto minmax(0, 1fr); grid-template-areas: "top" "stage" "side"; } - #stage { aspect-ratio: var(--aspect-p, 16 / 26); max-height: 58dvh; width: 100%; } - #side { border-left: 0; border-top: 1px solid var(--line); padding: 8px 10px calc(8px + var(--safe-b)); gap: 8px; } + #app { grid-template-columns: minmax(0, 1fr); grid-template-rows: auto var(--stage-h, 56dvh) minmax(0, 1fr); grid-template-areas: "top" "stage" "side"; } + #stage { width: 100%; } + #side { border-left: 0; border-top: 1px solid var(--line); padding: 0 10px 8px; gap: 8px; } } /* landscape phones: short viewport, narrow side panel */ @media (orientation: landscape) and (max-height: 520px) { - :root { --side-w: 236px; --btn: 40px; } + :root { --side-w: 236px; --btn: 40px; --tile-h: 58px; } #topbar { padding: 3px 8px; gap: 4px 6px; flex-wrap: nowrap; } #side { gap: 6px; padding: 6px; } } @@ -72,82 +84,139 @@ svg.ic { width: 1.25em; height: 1.25em; flex: none; } .stat .lbl { color: var(--dim); font-size: 11px; letter-spacing: .12em; } #statLives { color: var(--red); } #statGold { color: var(--amber); } -#statLives.low { animation: pulse 0.8s infinite; } -@keyframes pulse { 50% { background: #3a1020; } } +#statLives.low { border-color: var(--red); box-shadow: 0 0 0 2px rgba(255, 92, 122, .35); background: #2a0e18; animation: pulse 0.8s infinite; } /* static cue first, the pulse is extra */ +@keyframes pulse { 50% { background: #4a1426; } } .spacer { flex: 1 1 8px; } -.chip { display: flex; align-items: center; gap: 6px; padding: 0 10px; height: var(--btn); border-radius: 10px; background: var(--panel); border: 1px solid var(--line); font-family: var(--mono); font-size: 13px; color: var(--cyan); } +button.chip { gap: 6px; padding: 0 10px; border-radius: 10px; background: var(--panel); font-family: var(--mono); font-size: 13px; color: var(--cyan); } +button.chip .share { width: 1.1em; height: 1.1em; opacity: .85; } +button.chip:hover { background: #15233f; } .chip #netPing { color: var(--dim); } .chip.bad #netPing { color: var(--red); } +.chip.waiting { border-color: var(--amber); color: var(--amber); animation: glow 1.4s infinite; } /* alone in the room: tap to invite */ button { min-height: var(--btn); border-radius: 10px; border: 1px solid var(--line); background: var(--panel2); padding: 0 14px; display: inline-flex; align-items: center; justify-content: center; gap: 8px; touch-action: manipulation; transition: background .12s, border-color .12s, transform .05s; } button:hover { border-color: #35538a; background: #15233f; } button:active { transform: translateY(1px); } -button:disabled { opacity: .4; cursor: default; } +button:disabled { opacity: 1; cursor: default; color: #8da3c8; background: #0c1426; border-color: #172540; } button:focus-visible, input:focus-visible { outline: 2px solid var(--cyan); outline-offset: 2px; } button.icon { min-width: var(--btn); padding: 0 8px; font-family: var(--mono); font-size: 13px; } button.icon.toggle[aria-pressed="true"] { background: #0f3550; border-color: var(--cyan); color: var(--cyan); } +button#btnPause[aria-pressed="true"] { background: #3a2c08; border-color: var(--amber); color: var(--amber); } button.primary { background: linear-gradient(#1b7a96, #135872); border-color: #2fb4d6; color: #eaffff; font-weight: 600; } -button.primary:hover { background: linear-gradient(#2290b0, #176b8a); } +button.primary:hover { background: linear-gradient(#1b7a96, #135872); border-color: #8fe6ff; } button.danger { color: var(--red); } button.big { min-height: calc(var(--btn) + 6px); font-size: 16px; padding: 0 20px; } button.link { background: none; border: 0; color: var(--dim); text-decoration: underline; min-height: 36px; padding: 0 8px; } button.link:hover { color: var(--text); background: none; } button.floating { position: absolute; right: 8px; bottom: 8px; background: rgba(12, 19, 34, .85); } +#btnWave { white-space: nowrap; min-width: 0; } /* long label ("Wave 12 · 28s") shrinks with an ellipsis instead of wrapping or pushing Sound off screen */ +#btnWaveText { overflow: hidden; text-overflow: ellipsis; } #btnWave.attn { animation: glow 1.4s infinite; } @keyframes glow { 50% { box-shadow: 0 0 0 4px rgba(77, 227, 255, .25); } } @media (orientation: portrait), (max-width: 760px) and (min-height: 521px) { #topbar { padding: 6px 8px; } .stat { padding: 0 8px; font-size: 15px; } - #btnWave { flex: 1 1 auto; } - .spacer { flex: 0 0 0; } + #btnWave { flex: 1 1 130px; } + .spacer { display: none; } + button.chip { margin-left: auto; font-size: 12.5px; padding: 0 8px; } + .chip #netPing { display: none; } } /* ---------------------------------------------------------------- stage overlays */ -.hint { position: absolute; top: 8px; left: 50%; transform: translateX(-50%); max-width: calc(100% - 20px); padding: 6px 12px; border-radius: 999px; background: rgba(8, 13, 26, .92); border: 1px solid var(--line); font-family: var(--mono); font-size: 13px; pointer-events: none; white-space: nowrap; } +.hint { position: absolute; top: 8px; left: 50%; transform: translateX(-50%); max-width: calc(100% - 20px); padding: 6px 12px; border-radius: 999px; background: rgba(8, 13, 26, .92); border: 1px solid var(--line); font-family: var(--mono); font-size: 13px; pointer-events: none; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .hint.ok { color: var(--green); border-color: #1c6a55; } .hint.bad { color: var(--red); border-color: #6a2336; } .hint.info { color: var(--cyan); } -.paused-tag { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); padding: 10px 26px; border-radius: 999px; background: rgba(8, 13, 26, .88); border: 1px solid var(--amber); color: var(--amber); font-weight: 800; letter-spacing: .3em; font-size: 18px; pointer-events: none; z-index: 2; } +/* paused: the board is dimmed and the pill is a button that resumes */ +#stage.paused::after { content: ""; position: absolute; inset: 0; background: rgba(4, 7, 14, .5); pointer-events: none; z-index: 1; } +.paused-tag { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); padding: 8px 22px 8px 16px; min-height: 52px; border-radius: 999px; background: rgba(8, 13, 26, .94); border: 2px solid var(--amber); color: var(--amber); font-weight: 800; letter-spacing: .24em; font-size: 17px; z-index: 2; } +.paused-tag:hover { background: rgba(30, 24, 8, .96); border-color: var(--amber); } +.paused-tag span { display: flex; flex-direction: column; align-items: flex-start; line-height: 1.15; } +.paused-tag small { font-size: 11px; letter-spacing: .08em; font-weight: 600; color: #e8d9a0; } +.paused-tag .ic { width: 1.5em; height: 1.5em; } .banner { position: absolute; left: 0; right: 0; top: 34%; text-align: center; pointer-events: none; font-weight: 800; font-size: clamp(22px, 5vw, 44px); letter-spacing: .14em; color: var(--cyan); text-shadow: 0 0 24px rgba(77, 227, 255, .6); opacity: 0; transform: scale(.96); transition: opacity .3s, transform .3s; } .banner.show { opacity: 1; transform: none; } .banner.boss { color: var(--red); text-shadow: 0 0 24px rgba(255, 92, 122, .7); } -#toasts { position: absolute; left: 0; right: 0; bottom: 10px; display: flex; flex-direction: column; align-items: center; gap: 6px; pointer-events: none; } -.toast { padding: 7px 14px; background: rgba(8, 13, 26, .94); border: 1px solid var(--line); border-radius: 10px; font-size: 14px; animation: toast 2.6s forwards; max-width: calc(100% - 24px); text-align: center; } +/* toasts sit under the route hint at the top, and drop below the action bar when that one is at the top (never behind it, never on the server) */ +#toasts { position: absolute; left: 0; right: 0; top: 46px; display: flex; flex-direction: column; align-items: center; gap: 6px; pointer-events: none; z-index: 5; } +#app[data-ui="compact"][data-bar="top"] #toasts { top: calc(var(--bar-h) + 18px); } +#app[data-ui="compact"][data-bar="top"][data-conf] #toasts { top: calc(var(--bar-h) + var(--nudge-h) + 18px); } +.toast { padding: 7px 14px; background: rgba(8, 13, 26, .96); border: 1px solid var(--line); border-radius: 10px; font-size: 14px; animation: toast 2.6s forwards; max-width: calc(100% - 24px); text-align: center; } .toast.bad { border-color: #6a2336; color: #ffb3c1; } .toast.good { border-color: #1c6a55; color: #aef5d6; } -@keyframes toast { 0% { opacity: 0; transform: translateY(8px); } 8% { opacity: 1; transform: none; } 80% { opacity: 1; } 100% { opacity: 0; } } -.confirm { position: absolute; left: 50%; bottom: 10px; transform: translateX(-50%); display: flex; gap: 8px; padding: 6px; border-radius: 14px; background: rgba(8, 13, 26, .94); border: 1px solid var(--line); z-index: 3; white-space: nowrap; } -.confirm.top { bottom: auto; top: 52px; } -.confirm .primary.big { min-width: 120px; } -.reconnect { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; gap: 12px; background: rgba(5, 8, 16, .72); z-index: 4; font-size: 16px; } -.spinner { width: 22px; height: 22px; border: 3px solid var(--line); border-top-color: var(--cyan); border-radius: 50%; animation: spin .8s linear infinite; } +@keyframes toast { 0% { opacity: 0; transform: translateY(-8px); } 8% { opacity: 1; transform: none; } 80% { opacity: 1; } 100% { opacity: 0; } } +/* touch build bar: cancel, the route text (what the hint pill shows on desktop), and Build. Same slot and size as the tower action bar. */ +.confirm { position: absolute; left: 50%; bottom: 8px; transform: translateX(-50%); width: min(calc(100% - 16px), 480px); height: calc(var(--bar-h) + var(--nudge-h)); display: flex; flex-wrap: wrap; align-content: center; align-items: center; gap: 6px 8px; padding: 5px; border-radius: 14px; background: rgba(8, 13, 26, .96); border: 1px solid #2c4372; box-shadow: 0 6px 22px rgba(0, 0, 0, .5); z-index: 3; } +.confirm.top { bottom: auto; top: 8px; } +.confirm button { min-height: 44px; flex: none; } +.confirm .primary.big { min-width: 112px; padding: 0 12px; font-size: 15px; } +.chint { flex: 1 1 0; min-width: 0; text-align: center; font-family: var(--mono); font-size: 12.5px; line-height: 1.2; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; } +/* nudge row: one cell left / up / down / right, for fine aim when a cell is only 12 to 20 px (the arrow is the up icon turned) */ +.nudge { flex: 1 1 100%; display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; } +.nudge button { width: 100%; padding: 0; } +/* a stage wide enough for it (tablets, landscape phones) keeps the build bar one row: cancel, route text, arrows, Build */ +#app[data-barrows="1"] { --nudge-h: 0px; } +#app[data-barrows="1"] .confirm { flex-wrap: nowrap; } +#app[data-barrows="1"] #confirmHint { order: 1; } +#app[data-barrows="1"] .nudge { order: 2; flex: 0 0 auto; grid-template-columns: repeat(4, 44px); gap: 4px; } +#app[data-barrows="1"] #btnConfirmBuild { order: 3; } +/* a stage too short for two rows (320x568): one row, no route text in the bar (it goes to the pill at the top) and a check-only Build, so the bar leaves the board free */ +#app[data-barrows="0"] { --nudge-h: 0px; } +#app[data-barrows="0"] .confirm { flex-wrap: nowrap; gap: 4px; justify-content: space-between; } +#app[data-barrows="0"] #confirmHint, #app[data-barrows="0"] #confirmText { display: none; } +#app[data-barrows="0"] .nudge { order: 2; flex: 0 0 auto; grid-template-columns: repeat(4, 44px); gap: 4px; } +#app[data-barrows="0"] #btnConfirmBuild { order: 3; min-width: 44px; padding: 0; } +#app[data-barrows="0"][data-bar="top"] .hint { top: calc(var(--bar-h) + 16px); } +.nudge [data-dx="-1"] .ic { transform: rotate(-90deg); } .nudge [data-dx="1"] .ic { transform: rotate(90deg); } .nudge [data-dy="1"] .ic { transform: rotate(180deg); } +.chint.ok { color: var(--green); } .chint.bad { color: var(--red); } .chint.info { color: var(--cyan); } +#app[data-ui="compact"][data-bar="bottom"] #btnFit { bottom: auto; top: 8px; } /* keep the reset-zoom button out from under the bar */ +.reconnect { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; gap: 12px; background: rgba(5, 8, 16, .78); z-index: 4; font-size: 16px; padding: 0 16px; text-align: center; } +.spinner { width: 22px; height: 22px; flex: none; border: 3px solid var(--line); border-top-color: var(--cyan); border-radius: 50%; animation: spin .8s linear infinite; } @keyframes spin { to { transform: rotate(360deg); } } +/* offline: the rest of the HUD looks dead too (only the menu and the room chip stay usable) */ +#app.offline #side, #app.offline #topbar > :not(#btnMenu):not(#netChip) { opacity: .45; pointer-events: none; } -/* ---------------------------------------------------------------- side panel */ +/* ---------------------------------------------------------------- side panel: palette */ #side h4 { margin: 0 0 6px; font-size: 11px; letter-spacing: .14em; color: var(--dim); text-transform: uppercase; font-weight: 600; } #palette { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 6px; } -.tbtn { position: relative; flex-direction: column; gap: 2px; padding: 6px 4px 5px; min-height: 66px; text-align: center; line-height: 1.15; } +#palette.many { grid-template-columns: repeat(4, minmax(0, 1fr)); } /* more than 6 towers */ +.tbtn { position: relative; flex-direction: column; gap: 2px; padding: 6px 4px 5px; min-height: var(--tile-h); text-align: center; line-height: 1.15; } .tbtn canvas { width: 34px; height: 34px; pointer-events: none; } .tbtn .nm { font-size: 11.5px; color: var(--text); } .tbtn .cost { font-family: var(--mono); font-size: 12px; color: var(--amber); } -.tbtn .key { position: absolute; top: 3px; left: 5px; font-family: var(--mono); font-size: 10px; color: var(--dim); } +.tbtn .key { position: absolute; top: 3px; left: 5px; font-family: var(--mono); font-size: 11px; color: #9db4d8; } .tbtn.sel { border-color: var(--cyan); background: #0f3550; box-shadow: inset 0 0 0 1px var(--cyan); } -.tbtn.poor .cost { color: var(--red); } -.tbtn.poor { opacity: .72; } +.tbtn.poor .nm { color: #9fb2d4; } +.tbtn.poor .cost { color: #ff8fa3; } +.tbtn.poor canvas { opacity: .6; } @media (pointer: coarse) { .tbtn .key { display: none; } } +/* scroll affordance: main.js sets data-more="start|end|both" on a palette that has hidden tiles; the edge fades out */ +#palette[data-more="end"] { -webkit-mask-image: linear-gradient(var(--fade-dir, to right), #000 calc(100% - 30px), transparent); mask-image: linear-gradient(var(--fade-dir, to right), #000 calc(100% - 30px), transparent); } +#palette[data-more="start"] { -webkit-mask-image: linear-gradient(var(--fade-dir, to right), transparent, #000 30px); mask-image: linear-gradient(var(--fade-dir, to right), transparent, #000 30px); } +#palette[data-more="both"] { -webkit-mask-image: linear-gradient(var(--fade-dir, to right), transparent, #000 30px, #000 calc(100% - 30px), transparent); mask-image: linear-gradient(var(--fade-dir, to right), transparent, #000 30px, #000 calc(100% - 30px), transparent); } +/* stacked: one scrolling row of tiles pinned to the top of the side panel (thumb reach), wrapping grid when there is room */ @media (orientation: portrait), (max-width: 760px) and (min-height: 521px) { - #palette { position: sticky; top: -8px; z-index: 2; margin: -8px -10px 0; padding: 8px 10px 6px; background: rgba(8, 13, 26, .97); } - #palette { display: flex; overflow-x: auto; gap: 6px; padding-bottom: 2px; scrollbar-width: none; scroll-snap-type: x proximity; scroll-padding: 0 10px; } + #palette { position: sticky; top: 0; z-index: 2; margin: 0 -10px; padding: 8px 10px 6px; background: #0a101f; display: flex; overflow-x: auto; gap: 6px; scrollbar-width: none; scroll-snap-type: x proximity; scroll-padding: 0 10px; overscroll-behavior-x: contain; } #palette::-webkit-scrollbar { display: none; } .tbtn { flex: 0 0 76px; min-height: 72px; scroll-snap-align: start; } + #palette.many { grid-template-columns: none; } } +@media (min-width: 640px) and (orientation: portrait), (min-width: 640px) and (max-width: 760px) and (min-height: 521px) { + #palette { display: grid; grid-template-columns: repeat(auto-fill, minmax(84px, 1fr)); overflow: visible; mask-image: none; -webkit-mask-image: none; } + #palette.many { grid-template-columns: repeat(auto-fill, minmax(84px, 1fr)); } + .tbtn { flex: none; } +} +/* short landscape: a few rows of tiles in the narrow column; a long palette scrolls vertically with a fade */ @media (orientation: landscape) and (max-height: 520px) { - #palette { grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 4px; } - .tbtn { min-height: 58px; padding: 3px 2px; } + #palette { gap: 4px; max-height: calc(var(--tile-h) * 3.5 + 12px); overflow-y: auto; scrollbar-width: none; overscroll-behavior: contain; --fade-dir: to bottom; } + #palette::-webkit-scrollbar { display: none; } + #palette.many { gap: 3px; } + .tbtn { padding: 3px 2px; } .tbtn canvas { width: 26px; height: 26px; } } +/* ---------------------------------------------------------------- side panel: info, actions, wave, players */ .panel { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 10px; } #info:empty { display: none; } .info-head { display: flex; align-items: center; gap: 10px; margin-bottom: 6px; } @@ -160,27 +229,62 @@ button.floating { position: absolute; right: 8px; bottom: 8px; background: rgba( .kvp span:first-child { color: var(--dim); } .kv .up { color: var(--green); } .actions { display: flex; flex-wrap: wrap; gap: 6px; } -.actions button { flex: 1 1 auto; font-size: 14px; } +.actions button { flex: 1 1 auto; font-size: 14px; min-width: 0; white-space: nowrap; } .actions .cost { font-family: var(--mono); color: var(--amber); } +.actions .mv { overflow: hidden; text-overflow: ellipsis; } +.actions [data-act="close"] { display: none; } +/* wide layout: the actions stay at the bottom edge of the side panel even when a tall palette pushes them down */ +#app:not([data-ui="compact"]) .actions { position: sticky; bottom: 0; background: var(--panel); padding-top: 6px; margin-top: -2px; } .byline { font-size: 11.5px; color: var(--dim); margin-top: 6px; display: flex; align-items: center; gap: 6px; } .dot { width: 9px; height: 9px; border-radius: 50%; display: inline-block; flex: none; } +/* compact UI: the tower actions are a bar over the stage, on the half away from the tower (data-bar, set by main.js layoutBars) */ +#app[data-ui="compact"] #info .actions { + position: fixed; z-index: 6; flex-wrap: nowrap; gap: 6px; padding: 5px; height: var(--bar-h); + left: calc(var(--st-l, 0px) + var(--st-w, 100vw) / 2); transform: translateX(-50%); width: min(calc(var(--st-w, 100vw) - 16px), 480px); + top: calc(var(--st-t, 0px) + var(--st-h, 120px) - var(--bar-h) - 8px); + border-radius: 14px; background: rgba(8, 13, 26, .96); border: 1px solid #2c4372; box-shadow: 0 6px 22px rgba(0, 0, 0, .5); +} +#app[data-ui="compact"][data-bar="top"] #info .actions { top: calc(var(--st-t, 0px) + 8px); } +#app[data-ui="compact"] #info .actions button { min-height: 44px; padding: 0 8px; gap: 5px; flex: 1 1 0; font-size: 14px; } +#app[data-ui="compact"] #info .actions [data-act="up"] { flex-grow: 1.1; } +#app[data-ui="compact"] #info .actions [data-act="mode"] { flex-grow: 1.4; } +#app[data-ui="compact"] #info .actions [data-act="close"] { display: inline-flex; flex: 0 0 44px; min-width: 44px; padding: 0; } +#app[data-ui="compact"][data-barw="s"] #info .actions [data-act="up"] .w, #app[data-ui="compact"][data-barw="s"] #info .actions [data-act="mode"] .w { display: none; } +#app[data-ui="compact"] #info .panel { padding: 8px 10px; } +#app[data-ui="compact"] .kv { display: flex; flex-wrap: wrap; gap: 2px 14px; margin-bottom: 4px; } +#app[data-ui="compact"] .kvp { display: inline-flex; gap: 6px; } +#app[data-ui="compact"] .info .desc { font-size: 12.5px; margin: 0 0 4px; } +#app[data-ui="compact"] .info-head { margin-bottom: 4px; } +#app[data-ui="compact"] .info-head canvas { width: 32px; height: 32px; } + #nextwave .panel { padding: 8px 10px; } .wv { display: flex; flex-wrap: wrap; gap: 6px 10px; align-items: center; font-family: var(--mono); font-size: 12.5px; } .wv .e { display: inline-flex; align-items: center; gap: 4px; } -.wv .e i { width: 10px; height: 10px; border-radius: 3px; display: inline-block; } +.wv .e i { width: 12px; height: 12px; display: inline-block; background: var(--c); flex: none; } /* shape per enemy kind, not just a colour (see .sh-*) */ +.wv .e i.sh-ping, .wv .e i.sh-worm { border-radius: 50%; } +.wv .e i.sh-trojan { clip-path: polygon(25% 5%, 75% 5%, 100% 50%, 75% 95%, 25% 95%, 0 50%); } +.wv .e i.sh-spam { clip-path: polygon(0 20%, 60% 20%, 60% 0, 100% 50%, 60% 100%, 60% 80%, 0 80%); } +.wv .e i.sh-spoof { clip-path: polygon(50% 0, 100% 50%, 50% 100%, 0 50%); } +.wv .e i.sh-rootkit { clip-path: polygon(30% 0, 70% 0, 100% 30%, 100% 70%, 70% 100%, 30% 100%, 0 70%, 0 30%); width: 14px; height: 14px; } .wv .tag { padding: 1px 6px; border-radius: 6px; font-size: 11px; border: 1px solid; } .wv .tag.air { color: #e29bff; border-color: #5b3a73; } .wv .tag.boss { color: var(--red); border-color: #6a2336; } +/* stacked / short: while a tower or build type is selected the wave panel makes room for its stats */ +#app[data-ui="compact"] #info:not(:empty) ~ #nextwave { display: none; } #players .pl { display: flex; align-items: center; gap: 8px; padding: 3px 0; font-size: 13.5px; } #players .pl .off { color: var(--dim); font-size: 12px; } #players .pl .you { color: var(--dim); font-size: 12px; } #players .actions { margin-top: 6px; } -/* ---------------------------------------------------------------- overlays (menus) */ -.overlay { position: absolute; inset: 0; z-index: 10; display: flex; align-items: center; justify-content: center; padding: 14px; background: rgba(4, 7, 14, .78); backdrop-filter: blur(5px); -webkit-backdrop-filter: blur(5px); overflow-y: auto; } -.card { width: min(560px, 100%); max-height: 100%; overflow-y: auto; margin: auto; padding: 20px 20px 16px; border-radius: 18px; background: linear-gradient(#0f1830, #0a1124); border: 1px solid #25396a; box-shadow: 0 20px 60px rgba(0, 0, 0, .6), 0 0 0 1px rgba(77, 227, 255, .06); } +/* ---------------------------------------------------------------- overlays (menu, lobby, help, end) + * .card is a flex column: .card-body scrolls, .card-foot (the primary buttons) is always visible. */ +.overlay { position: absolute; inset: 0; z-index: 10; display: flex; align-items: center; justify-content: center; padding: max(14px, var(--safe-t)) max(14px, var(--safe-r)) max(14px, var(--safe-b)) max(14px, var(--safe-l)); background: rgba(4, 7, 14, .78); backdrop-filter: blur(5px); -webkit-backdrop-filter: blur(5px); overflow: hidden; } +.card { width: min(560px, 100%); max-height: 100%; min-height: 0; display: flex; flex-direction: column; overflow: hidden; border-radius: 18px; background: linear-gradient(#0f1830, #0a1124); border: 1px solid #25396a; box-shadow: 0 20px 60px rgba(0, 0, 0, .6), 0 0 0 1px rgba(77, 227, 255, .06); } .card.wide { width: min(680px, 100%); } +.card-body { flex: 1 1 auto; min-height: 0; overflow-y: auto; overscroll-behavior: contain; padding: 20px 20px 10px; } +.card-foot { flex: none; padding: 10px 20px 14px; border-top: 1px solid #1a2a50; background: #0a1124; } +.card-foot > .row:first-child, .card-foot > .opts + .row { margin-top: 0; } .card h1 { margin: 0; font-size: clamp(30px, 8vw, 46px); letter-spacing: .26em; font-weight: 800; color: #eaffff; text-shadow: 0 0 22px rgba(77, 227, 255, .55); } .card h2 { margin: 0 0 8px; font-size: 24px; } .card h3 { margin: 0 0 6px; font-size: 14px; letter-spacing: .08em; text-transform: uppercase; color: var(--dim); } @@ -190,30 +294,41 @@ button.floating { position: absolute; right: 8px; bottom: 8px; background: rgba( .muted { color: var(--dim); } .small { font-size: 13px; } .row { display: flex; gap: 10px; justify-content: center; flex-wrap: wrap; margin-top: 12px; } -.row.small { margin-top: 6px; } -.row > .big { flex: 1 1 200px; } -.msg { min-height: 1.4em; text-align: center; color: var(--amber); margin: 8px 0 0; } +.row.small { margin-top: 4px; } +.row > .big { flex: 1 1 180px; } +.opts { display: flex; gap: 8px; justify-content: center; flex-wrap: wrap; margin-bottom: 10px; } /* difficulty selector goes here */ +.opts:empty { display: none; } +.msg { min-height: 1.4em; text-align: center; color: var(--amber); margin: 0 0 4px; } .msg.bad { color: var(--red); } +.msg:empty { min-height: 0; margin: 0; } .resume { width: 100%; margin-top: 10px; border-color: var(--cyan); color: var(--cyan); } -.maps { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; margin-bottom: 4px; } +/* map picker: wrapping grid that copes with any number of maps (scrolls inside the card body) */ +.maps { display: grid; grid-template-columns: repeat(auto-fill, minmax(96px, 1fr)); gap: 8px; margin-bottom: 4px; } .mapcard { flex-direction: column; align-items: stretch; gap: 4px; padding: 8px; text-align: left; min-height: 0; border-radius: 12px; } .mapcard canvas { width: 100%; aspect-ratio: 26 / 16; border-radius: 6px; background: #060a14; } .mapcard .nm { font-weight: 700; font-size: 13.5px; min-height: 2.6em; } -.mapcard .df { font-size: 11px; color: var(--dim); letter-spacing: .06em; } +.mapcard .df { font-size: 11px; color: #9db4d8; letter-spacing: .06em; } .mapcard .df b { color: var(--amber); letter-spacing: 1px; } .mapcard[aria-checked="true"] { border-color: var(--cyan); background: #0f3550; box-shadow: inset 0 0 0 1px var(--cyan); } +.mapcard[aria-checked="true"] .nm::before { content: "\2713\00a0"; color: var(--cyan); } .mapdesc { text-align: center; color: var(--dim); font-size: 13px; min-height: 2.6em; margin: 6px 0 4px; } -@media (max-width: 480px) { .mapcard .df { display: none; } .mapcard .nm { font-size: 12.5px; } .card { padding: 16px 14px 12px; } } +@media (max-width: 480px) { .mapcard .df { display: none; } .mapcard .nm { font-size: 12.5px; min-height: 2.4em; } .card-body { padding: 14px 14px 8px; } .card-foot { padding: 8px 14px 12px; } } .field { display: block; margin: 12px 0; } .field span { display: block; font-size: 12px; color: var(--dim); margin-bottom: 4px; letter-spacing: .06em; } input { width: 100%; min-height: var(--btn); border-radius: 10px; border: 1px solid var(--line); background: #070d1b; color: var(--text); padding: 0 12px; font: inherit; font-size: 16px; /* >=16px stops iOS zooming on focus */ } -input.code { text-align: center; letter-spacing: .5em; font-family: var(--mono); font-size: 22px; text-transform: uppercase; padding-left: .5em; margin-bottom: 8px; } +input::placeholder { color: #8397bb; } +input.code { text-align: center; letter-spacing: .5em; font-family: var(--mono); font-size: 22px; text-transform: uppercase; padding-left: .5em; } +.joinrow { display: flex; gap: 8px; margin-top: auto; } +.joinrow input { flex: 1 1 auto; min-width: 0; } +.joinrow button { flex: 0 0 auto; } .split { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; } .split .col { display: flex; flex-direction: column; gap: 6px; padding: 12px; border-radius: 12px; background: rgba(255, 255, 255, .02); border: 1px solid var(--line); } -.split .col button { margin-top: auto; } -@media (max-width: 480px) { .split { grid-template-columns: 1fr; } } +.split .col > button { margin-top: auto; } +.roomlist { margin-top: 12px; } +@media (max-width: 480px) { .split { grid-template-columns: 1fr; gap: 10px; } } +@media (max-height: 640px) { .lead { display: none; } .field { margin: 8px 0; } .split .col { padding: 10px; } } /* small phones: the intro text makes way for the buttons */ .howto { padding-left: 18px; margin: 10px 0 0; display: grid; gap: 8px; } .howto li { color: #bcd3f5; } @@ -225,56 +340,87 @@ input.code { text-align: center; letter-spacing: .5em; font-family: var(--mono); .stats div { display: flex; justify-content: space-between; padding: 4px 0; border-bottom: 1px solid var(--line); } .stats span { color: var(--dim); } +/* short landscape: compact menus so the title, a row of maps and the buttons all fit in 320px */ +@media (orientation: landscape) and (max-height: 520px) { + .overlay { padding: max(6px, var(--safe-t)) max(8px, var(--safe-r)) max(6px, var(--safe-b)) max(8px, var(--safe-l)); } + .card-body { padding: 8px 16px 6px; } + .card-foot { padding: 6px 16px 8px; } + .card h1 { font-size: 24px; letter-spacing: .2em; } + .card h2 { font-size: 19px; margin-bottom: 4px; } + .logo { gap: 10px; } .logo-mark { width: 28px; height: 28px; } + .tag { margin: 2px 0 6px; font-size: 13px; } + .maps { display: flex; overflow-x: auto; scroll-snap-type: x proximity; scrollbar-width: none; padding-bottom: 2px; } + .maps::-webkit-scrollbar { display: none; } + .mapcard { flex: 0 0 118px; scroll-snap-align: start; padding: 5px; gap: 2px; } + .mapcard .nm { min-height: 0; font-size: 12px; } + .mapcard .df { display: none; } + .mapdesc { min-height: 0; margin: 4px 0 0; font-size: 12px; } + .row { margin-top: 6px; gap: 8px; } .row.small { margin-top: 0; } + .row > .big { flex: 1 1 140px; } + .lead { display: none; } + .field { margin: 6px 0; display: flex; align-items: center; gap: 10px; } .field span { margin: 0; flex: none; } + .split { gap: 8px; } .split .col { padding: 6px 8px; gap: 4px; } .split .col h3 { margin-bottom: 0; font-size: 12px; } + .split .col .small { display: none; } + .resume { margin-top: 6px; } + .stats { margin: 6px 0 2px; font-size: 13px; } + .stats div { padding: 2px 0; } + .howto { gap: 5px; font-size: 13.5px; } + button.link { min-height: 32px; } +} + /* the board gets the whole stage while a menu is shown behind blurred overlays; hide HUD chrome pre-game */ #app[data-screen="menu"] #side, #app[data-screen="menu"] #topbar > :not(#btnMenu) { visibility: hidden; } -@media (prefers-reduced-motion: reduce) { *, *::before, *::after { animation-duration: .01ms !important; animation-iteration-count: 1 !important; transition-duration: .01ms !important; } } - -/* compact info panel on stacked (portrait / narrow) layouts: must come after the base rules above */ -@media (orientation: portrait), (max-width: 760px) and (min-height: 521px) { - .kv { display: flex; flex-wrap: wrap; gap: 2px 14px; margin-bottom: 6px; } - .kvp { display: inline-flex; gap: 6px; } - .info .desc { font-size: 12.5px; margin: 0 0 4px; } - .info-head { margin-bottom: 4px; } - .info-head canvas { width: 32px; height: 32px; } - .panel { padding: 8px 10px; } - .actions button { min-height: 42px; } +/* reduced motion: less movement, never less information (toasts and the low-integrity cue stay visible) */ +@media (prefers-reduced-motion: reduce) { + .toast { animation: none; } + #btnWave.attn, #statLives.low, .chip.waiting { animation: none; } + .banner { transition: none; } + button { transition: none; } + .spinner { animation-duration: 2.4s; } } -/* stacked layouts: keep the top bar to two rows even with the co-op chip */ -@media (orientation: portrait), (max-width: 760px) and (min-height: 521px) { - .chip { padding: 0 8px; font-size: 12.5px; } - .chip #netPing { display: none; } - #netChip { margin-left: auto; } - .spacer { display: none; } - #btnWave { flex: 1 1 130px; } -} - -/* narrow portrait phones: the room chip moves into the players panel, stats shrink so the bar stays two rows */ +/* narrow portrait phones: the room chip shrinks to its code + share icon, stats shrink so the bar stays two rows */ @media (max-width: 420px) { - #netChip { display: none; } + button.chip > svg:first-child { display: none; } .stat { padding: 0 7px; gap: 4px; font-size: 14px; } .stat .lbl { font-size: 10px; letter-spacing: .06em; } #topbar { gap: 5px 6px; padding: 5px 6px; } } /* small landscape phones: one slim top bar, narrower side panel */ @media (orientation: landscape) and (max-height: 520px) and (max-width: 700px) { - :root { --side-w: 200px; --btn: 38px; } - #netChip { display: none; } + :root { --side-w: 200px; } .stat .lbl { display: none; } - .stat { padding: 0 6px; font-size: 14px; } + .stat { padding: 0 5px; font-size: 14px; } button.icon { min-width: 36px; padding: 0 6px; } - #topbar { gap: 4px; padding: 3px 6px; } + #topbar { gap: 3px; padding: 3px 6px; } + #btnWave { padding: 0 8px; gap: 5px; } .tbtn .nm { font-size: 10.5px; } + button.chip { padding: 0 6px; font-size: 12px; gap: 4px; } .chip #netPing { display: none; } button.chip > svg { display: none; } } - +@media (orientation: landscape) and (max-height: 520px) and (min-width: 701px) { .chip #netPing { display: none; } } /* very small phones (320px) */ @media (max-width: 340px) { - :root { --btn: 38px; } .stat .lbl { display: none; } .stat { padding: 0 6px; } #btnWave { flex: 1 1 80px; padding: 0 8px; } button.icon { min-width: 38px; padding: 0 4px; } #topbar { gap: 4px; padding: 4px; } } + +/* touch: every target is at least 44px (declared last so no layout rule above can shrink it) */ +@media (pointer: coarse) { + :root { --btn: 44px; } + button.icon { min-width: 44px; } + button.link { min-height: 44px; } + button.chip { min-width: 44px; } +} + +/* Windows high contrast: selection must not depend on colours the UA replaces */ +@media (forced-colors: active) { + .tbtn.sel, .mapcard[aria-checked="true"], button.toggle[aria-pressed="true"], button#btnPause[aria-pressed="true"] { outline: 3px solid Highlight; outline-offset: -3px; forced-color-adjust: none; background: Highlight; color: HighlightText; } + .tbtn.sel .nm, .tbtn.sel .cost, .mapcard[aria-checked="true"] .df, .mapcard[aria-checked="true"] .df b { color: HighlightText; } + .overlay { background: Canvas; } + #side { border-color: CanvasText; } +} diff --git a/public/index.html b/public/index.html index 734797d..f20f2d3 100644 --- a/public/index.html +++ b/public/index.html @@ -35,6 +35,7 @@ + @@ -46,12 +47,12 @@
WAVE0
20
0
- +
- + @@ -59,14 +60,21 @@ - +
- + - +