diff --git a/.gitignore b/.gitignore index ea918a3..0316d97 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,7 @@ node_modules/ .env # local scratch /tmp/ + +# e2e screenshots +/e2e/out/ +*.pid diff --git a/README.md b/README.md index c795684..0fdee96 100644 --- a/README.md +++ b/README.md @@ -91,8 +91,12 @@ reconnects automatically and resumes the same seat for a minute. ## Tests ```bash -npm test +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 ``` -Covers the rules (placement validation, route sealing, corner cutting, targeting, waves, economy) and the server -(protocol, rooms, reconnects, security checks, static files, dual stack). +`npm run e2e` drives Chromium through Playwright (a devDependency). Install the browser once with +`npx playwright-core install chromium-headless-shell` (on a minimal Debian also `npx playwright-core install-deps` +as root). It starts its own server on a random port and writes screenshots to `e2e/out/`. diff --git a/deploy/netwall.service b/deploy/netwall.service new file mode 100644 index 0000000..395d4fa --- /dev/null +++ b/deploy/netwall.service @@ -0,0 +1,71 @@ +# Netwall systemd unit (Debian 13 LXC; see docs/DEPLOY.md). +# +# install -m 0644 deploy/netwall.service /etc/systemd/system/netwall.service +# systemctl daemon-reload && systemctl enable --now netwall +# journalctl -u netwall -f +# +# Expects the app in /opt/netwall (server/, public/, node_modules/) and Debian's /usr/bin/node (Node 20). + +[Unit] +Description=Netwall - co-op tower defence (Node server) +Documentation=file:///opt/netwall/docs/DEPLOY.md +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +User=netwall +Group=netwall +WorkingDirectory=/opt/netwall +ExecStart=/usr/bin/node /opt/netwall/server/index.js + +# ---- configuration (see docs/DEPLOY.md, "Configuration") -------------------------------------- +Environment=NODE_ENV=production +# Port to listen on. 8080 is unprivileged, so the service needs no capabilities. +Environment=PORT=8080 +# "::" = one dual-stack socket for IPv4 + IPv6 (falls back to 0.0.0.0 if the kernel has no IPv6). +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 +#Environment=ALLOWED_ORIGINS=https://game.example.com +#Environment=MAX_CONN_PER_IP=40 +#Environment=GRACE_MS=60000 + +# ---- lifecycle --------------------------------------------------------------------------------- +Restart=on-failure +RestartSec=2 +# SIGTERM closes all sockets and exits 0 within about a second; SIGKILL after 10 s as a backstop. +TimeoutStopSec=10 + +# ---- hardening that works in any container (no mount namespaces needed) ----------------------- +NoNewPrivileges=yes +CapabilityBoundingSet= +AmbientCapabilities= +# AF_NETLINK: Node's os.networkInterfaces() (start-up banner) and glibc's resolver use it. +RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX AF_NETLINK +RestrictRealtime=yes +RestrictSUIDSGID=yes +LockPersonality=yes +SystemCallArchitectures=native +UMask=0077 +# Do NOT add MemoryDenyWriteExecute=yes: V8's JIT needs writable+executable memory and Node would crash. + +# ---- optional extra hardening: needs mount namespaces ------------------------------------------ +# In an unprivileged Proxmox LXC these fail with "status=226/NAMESPACE" unless the container has the +# "Nesting" feature enabled (Proxmox: container > Options > Features > Nesting; then restart the CT). +# The app writes nothing to disk, so a read-only file system view is fine for it. +#ProtectSystem=strict +#ProtectHome=yes +#PrivateTmp=yes +#PrivateDevices=yes +#ProtectKernelTunables=yes +#ProtectKernelModules=yes +#ProtectKernelLogs=yes +#ProtectControlGroups=yes +#ProtectClock=yes +#ProtectHostname=yes + +[Install] +WantedBy=multi-user.target diff --git a/docs/DEPLOY.md b/docs/DEPLOY.md new file mode 100644 index 0000000..28a92c3 --- /dev/null +++ b/docs/DEPLOY.md @@ -0,0 +1,287 @@ +# Deploying Netwall + +Netwall is one Node process: it serves the static game from `public/` and a WebSocket endpoint at `/ws` that runs +the co-op rooms. There is no database and no build step; games live in memory (a restart ends every running game). + +``` + phone / laptop ──https──▶ nginx Proxy Manager (TLS, :443) ──http + WebSocket──▶ Debian 13 LXC: node :8080 + ◀──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. + +## 1. Requirements + +* Debian 13 (trixie) LXC, with its own IPv4 (and optionally IPv6) address on a network the proxy can reach. +* Node 18 or newer. Debian 13 ships Node 20.19 as `nodejs`. The server is plain CommonJS with one runtime + dependency (`ws`). +* A DNS name for the game (for example `game.example.com`) pointing at the proxy. + +## 2. Install in the LXC + +Run as root inside the container. + +```sh +apt update +apt install -y nodejs npm # Debian 13: Node 20.19 +node --version + +# a dedicated, login-less user that only runs the game +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) +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 + +# quick manual test as the service user (Ctrl-C to stop) +runuser -u netwall -- env PORT=8080 node server/index.js +``` + +When run directly the server prints `http://localhost:PORT/` and one URL per non-internal interface address +(IPv4 as `http://a.b.c.d:PORT/`, IPv6 as `http://[addr]:PORT/`, link-local `fe80::` skipped). + +## 3. systemd service + +```sh +install -m 0644 /opt/netwall/deploy/netwall.service /etc/systemd/system/netwall.service +systemctl daemon-reload +systemctl enable --now netwall +systemctl status netwall +journalctl -u netwall -f # live log +``` + +`deploy/netwall.service` runs as user `netwall`, `Restart=on-failure`, and sets the environment below. Edit the +`Environment=` lines (or use `systemctl edit netwall` and put them in an override) and `systemctl restart netwall`. + +Hardening in the unit: `NoNewPrivileges`, an empty capability set (port 8080 needs none), `RestrictAddressFamilies`, +`RestrictRealtime`, `RestrictSUIDSGID`, `LockPersonality`, `SystemCallArchitectures=native`, `UMask=0077`. They need +no mount namespaces, so they should work in an LXC without extra settings; the unit has not been started in one yet, +so if `systemctl status netwall` shows a sandboxing error, comment the offending line out. A second block (`ProtectSystem=strict`, `PrivateTmp`, ...) is +left commented out: in an unprivileged Proxmox LXC it fails with `status=226/NAMESPACE` unless the container has +**Options > Features > Nesting** enabled. Turn nesting on, uncomment the block and restart if you want it. +Do not add `MemoryDenyWriteExecute=yes`; V8's JIT needs writable+executable memory. + +## 4. Configuration + +Environment variables, read when the server is started directly (`node server/index.js`): + +| Variable | Default | Meaning | +|---|---|---| +| `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". | +| `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). | + +Fixed in code (options of `createServer()`, not environment variables): at most 50 rooms, 20 snapshots/s per room, +a WebSocket ping every 25 s, client frames at most 2048 bytes, 60 messages/s per socket (burst 120), a socket that does +not `join` within 10 s is closed. When all 50 rooms exist, a room in which nobody is online (it is only being held for +its `GRACE_MS`) is deleted to make room for a new one, longest-abandoned first, so on a full server the grace period is +not guaranteed; rooms with somebody online are never evicted (the newcomer gets `too_many_rooms`). + +What the server does, relevant to a proxy setup: + +* **Real client IP** is used only for the log and the per-IP cap. With `TRUST_PROXY=auto` and a private/loopback peer + 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. +* **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`. +* **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. +* **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 + `Cache-Control: no-cache` (revalidated by ETag), range requests (needed for audio on iOS Safari) and a strict + Content-Security-Policy. The server does not compress responses. +* Logs go to stdout (journald): room created/deleted, players joining/leaving, refused WebSockets. Player IP + addresses appear in the log. There is no per-request access log. +* **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. + +## 5. nginx Proxy Manager (NPM) + +In NPM, **Hosts > Proxy Hosts > Add Proxy Host**. + +**Details tab** + +| Field | Value | +|---|---| +| 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 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) | + +**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. + +**Advanced tab** (Custom Nginx Configuration): paste + +```nginx +proxy_read_timeout 3600s; +proxy_send_timeout 3600s; +``` + +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/`. + +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`. + +Optional, in the same Advanced box, to compress text for phones on mobile data (the Node server does not): + +```nginx +gzip on; +gzip_types text/css text/javascript application/javascript application/json image/svg+xml; +``` + +## 6. Dual stack (IPv4 + IPv6) + +* **The app side is automatic.** `HOST=::` (the default) is a single dual-stack socket: IPv4 clients arrive as + `::ffff:a.b.c.d` and are logged as plain IPv4. Check both families from inside the LXC: + + ```sh + curl -i http://127.0.0.1:8080/healthz + curl -gi 'http://[::1]:8080/healthz' + ``` + +* **Public side.** Publish an `AAAA` record for `game.example.com` pointing at the proxy's IPv6 address, next to the + `A` record, **after** ports 80 and 443 really answer over IPv6 (router/firewall rules, NPM's container having an + IPv6 address). A published but broken `AAAA` breaks IPv6 visitors and certificate issuance. The proxy-to-LXC hop + can stay IPv4; that is independent of what visitors use. +* **Firewall.** Only the proxy should reach port 8080 (everybody else goes through TLS). Inside the LXC, for example + with nftables (`apt install nftables`; keep your SSH rule): + + ```text + # /etc/nftables.conf (excerpt) + table inet filter { + chain input { + type filter hook input priority 0; policy drop; + ct state established,related accept + iif lo accept + meta l4proto { icmp, ipv6-icmp } accept + tcp dport 22 accept + ip saddr 192.168.1.10 tcp dport 8080 accept # the NPM host (IPv4) + ip6 saddr fd00::10 tcp dport 8080 accept # the NPM host (IPv6), if it reaches the LXC over IPv6 + } + } + ``` + + `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. +* **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 `::` + (`EAFNOSUPPORT`, `EADDRNOTAVAIL`, ...); the server then logs + `IPv6 is not available (...); falling back to 0.0.0.0 (IPv4 only)` and listens on IPv4. You can also set + `HOST=0.0.0.0`. `EADDRINUSE` (something else on the port) is an error and never triggers the fallback. + +## 7. Under a path prefix (`https://example.com/netwall/`) + +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): + +```nginx +location = /netwall { return 301 /netwall/; } +location /netwall/ { + proxy_pass http://192.168.1.50:8080/; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection $http_connection; + 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. + +## 8. Verify + +```sh +# from anywhere +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.) +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('unexpected-response',(q,r)=>{console.log('HTTP',r.statusCode);process.exit(1)}); +ws.on('error',e=>{console.log(e.message);process.exit(1)}); +" +# prints: 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 + +| 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. | +| 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`. | +| `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. | +| `status=226/NAMESPACE` when starting the service | You enabled the optional namespace-based hardening in an LXC without Nesting. Enable Proxmox **Options > Features > Nesting** for the container, or comment that block out again. | +| Old version of the game after an update | NPM *Cache Assets* is on, or a browser/service layer ignores `no-cache`. Switch Cache Assets off, hard-reload. | +| Phone loses the game when it sleeps | Expected: the socket dies. The client reconnects with the same player id and gets its slot back if that happens within `GRACE_MS` (60 s by default). Raise `GRACE_MS` for longer. | +| `Cannot find module 'ws'` | `npm install --omit=dev` was not run in `/opt/netwall`. | + +## 10. Updating + +```sh +systemctl stop netwall +# replace server/ and public/ (rsync as in section 2), then +cd /opt/netwall && npm install --omit=dev +systemctl start netwall +``` + +Running games end with the restart. For a quiet moment: `journalctl -u netwall | grep -E 'created|deleted'` +shows which rooms are open. diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index 6cad108..961be2d 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -37,8 +37,9 @@ at a domain root and under a path prefix the proxy strips. 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). * **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 first address of - `X-Forwarded-For` (else `X-Real-IP`) as the client IP; otherwise use the TCP peer and ignore those headers. + means: if the TCP peer is loopback / RFC1918 / `fc00::/7` / link-local, 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 @@ -91,6 +92,10 @@ Success: reply to the joiner ``` then broadcast `{ t:'players', players:[...] }` to all *other* players. +`pid` is the reconnect secret (whoever presents it takes the slot), so in every `players` list it is the viewer's own +pid for the viewer's own entry and an opaque, stable per-room alias for the other player's entry. Compare entries by +`pid` within the lists you receive and find yourself with `you.pid`; never expect to see the other player's real pid. + * A player owns a **slot** (0 or 1), the lowest free one, kept until they leave for good. * **Host** = creator; if the host leaves for good the other player becomes host. * **Reconnect**: a `join` whose `pid` already holds a slot in that room re-binds to it (`resumed:true`); the old diff --git a/e2e/run.js b/e2e/run.js new file mode 100644 index 0000000..3454fd2 --- /dev/null +++ b/e2e/run.js @@ -0,0 +1,49 @@ +'use strict'; +/* + * End-to-end browser tests (desktop, phone touch, co-op with two browsers) driven by Playwright. + * + * npm install # installs playwright-core (devDependency) + * npx playwright-core install chromium-headless-shell # once, downloads the browser + * npm run e2e [-- name-filter] + * + * Starts the real server on a random port, runs every scenario in e2e/scenarios, saves screenshots to e2e/out/. + * Set E2E_URL to test an already running server instead (needed for the co-op scenario to see that server). + */ +const fs = require('fs'); +const path = require('path'); + +async function main() { + let chromium; + try { ({ chromium } = require('playwright-core')); } catch (e) { + console.error('playwright-core is not installed: run "npm install" first (it is a devDependency).'); process.exit(2); + } + const filter = process.argv[2] || ''; + const out = path.join(__dirname, 'out') + path.sep; + fs.mkdirSync(out, { recursive: true }); + + let srv = null, url = process.env.E2E_URL; + if (!url) { + const { createServer } = require('../server'); + srv = await createServer({ port: 0, host: '127.0.0.1', log: () => {} }); + url = 'http://127.0.0.1:' + srv.port + '/'; + } + const browser = await chromium.launch({ args: ['--no-sandbox'] }); + const files = fs.readdirSync(path.join(__dirname, 'scenarios')).filter((f) => f.endsWith('.js') && f.includes(filter)).sort(); + let failed = 0; + for (const f of files) { + const t0 = Date.now(); + process.stdout.write('\n=== ' + f + '\n'); + try { + await require('./scenarios/' + f)({ browser, url, out }); + console.log('PASS ' + f + ' (' + ((Date.now() - t0) / 1000).toFixed(1) + 's)'); + } catch (e) { + failed++; + console.log('FAIL ' + f + ': ' + e.message); + } + } + await browser.close(); + if (srv) await srv.close(); + console.log('\n' + (failed ? failed + ' scenario(s) failed' : 'all ' + files.length + ' scenarios passed')); + process.exit(failed ? 1 : 0); +} +main().catch((e) => { console.error(e); process.exit(1); }); diff --git a/e2e/scenarios/01-smoke.js b/e2e/scenarios/01-smoke.js new file mode 100644 index 0000000..f416303 --- /dev/null +++ b/e2e/scenarios/01-smoke.js @@ -0,0 +1,47 @@ +module.exports = async function ({ browser, url: URL, out: OUT }) { + const errors = []; + const setups = [ + ['desktop', { viewport: { width: 1280, height: 800 } }], + ['phone-portrait', { viewport: { width: 390, height: 844 }, deviceScaleFactor: 2, isMobile: true, hasTouch: true }], + ['phone-landscape', { viewport: { width: 844, height: 390 }, deviceScaleFactor: 2, isMobile: true, hasTouch: true }], + ]; + for (const [name, opts] of setups) { + const ctx = await browser.newContext(opts); + const page = await ctx.newPage(); + page.on('console', m => { if (m.type() === 'error' || m.type() === 'warning') errors.push(`[${name}] console.${m.type()}: ${m.text()}`); }); + page.on('pageerror', e => errors.push(`[${name}] pageerror: ${e.message}\n${e.stack}`)); + await page.goto(URL); + await page.waitForTimeout(600); + await page.screenshot({ path: OUT + name + '-1-menu.png' }); + await page.click('#btnSolo'); + await page.waitForTimeout(400); + await page.screenshot({ path: OUT + name + '-2-help.png' }); + await page.click('#btnHelpClose'); + await page.waitForTimeout(300); + // build a bit + const box = await page.locator('#board').boundingBox(); + const cell = async (cx, cy) => { + const r = await page.evaluate(([cx, cy]) => { const r = window.NW.app.renderer; const p = r.cellToScreen(cx, cy); return p; }, [cx, cy]); + return { x: box.x + r.x, y: box.y + r.y }; + }; + await page.click('.tbtn[data-type="wall"]'); + for (let y = 2; y <= 12; y++) { const p = await cell(12, y); await page.mouse.click(p.x, p.y); } + await page.click('.tbtn[data-type="filter"]'); + const isTouch = !!opts.hasTouch; + for (const [cx, cy] of [[10, 12], [14, 12], [13, 9]]) { + const p = await cell(cx, cy); + if (isTouch) { await page.touchscreen.tap(p.x, p.y); await page.waitForTimeout(80); await page.touchscreen.tap(p.x, p.y); } + else { await page.mouse.click(p.x, p.y); } + await page.waitForTimeout(80); + } + await page.screenshot({ path: OUT + name + '-3-built.png' }); + await page.click('#btnWave'); + await page.waitForTimeout(4000); + await page.screenshot({ path: OUT + name + '-4-wave.png' }); + const st = await page.evaluate(() => { const v = window.NW.app.ctrl.view; return { gold: v.gold, lives: v.lives, wave: v.wave, towers: v.towers.length, monsters: v.monsters.length }; }); + console.log(name, JSON.stringify(st)); + 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/02-touch.js b/e2e/scenarios/02-touch.js new file mode 100644 index 0000000..3b0e5be --- /dev/null +++ b/e2e/scenarios/02-touch.js @@ -0,0 +1,78 @@ +const assert = (c, m) => { if (!c) throw new Error('ASSERT: ' + m); console.log('ok -', m); }; +module.exports = async function ({ browser, url: URL, out: OUT }) { + const errors = []; + for (const [name, opts] of [['portrait', { viewport: { width: 390, height: 844 } }], ['landscape', { viewport: { width: 844, height: 390 } }]]) { + console.log('=== ' + name); + const ctx = await browser.newContext({ ...opts, deviceScaleFactor: 2, isMobile: true, hasTouch: true }); + 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 = await ctx.newCDPSession(page); + const touch = (type, pts) => cdp.send('Input.dispatchTouchEvent', { type, touchPoints: pts.map((p, i) => ({ x: p.x, y: p.y, id: i + 1 })) }); + await page.goto(URL); await page.waitForTimeout(400); + await page.tap('#btnSolo'); await page.waitForTimeout(300); + await page.tap('#btnHelpClose'); await page.waitForTimeout(200); + const box = 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: box.x + r.x, y: box.y + r.y }; }; + const state = () => page.evaluate(() => { const a = NW.app, v = a.ctrl.view; return { towers: v.towers.length, gold: v.gold, pending: a.pending, selType: a.selType, zoom: a.renderer.zoom, rot: a.renderer.rot, confirmHidden: document.getElementById('confirm').hidden, marks: a.renderer.marks.length, hint: document.getElementById('hint').textContent }; }); + + // 1) drag-paint walls with one finger + await page.tap('.tbtn[data-type="wall"]'); + const a = await cellPt(8, 5), b = await cellPt(8, 11); + await touch('touchStart', [a]); + for (let i = 1; i <= 12; i++) await touch('touchMove', [{ x: a.x + (b.x - a.x) * i / 12, y: a.y + (b.y - a.y) * i / 12 }]); + await touch('touchEnd', []); + let s = await state(); + assert(s.towers >= 7, `drag painted a wall line (${s.towers} walls)`); + + // 2) turret: first tap previews (no build), confirm bar appears, tapping the check builds it + await page.tap('.tbtn[data-type="filter"]'); + const t1 = await cellPt(10, 8); + await page.touchscreen.tap(t1.x, t1.y); await page.waitForTimeout(150); + let s2 = await state(); + assert(s2.towers === s.towers && s2.pending && s2.pending.x === 10 && s2.pending.y === 8, 'first tap only previews'); + assert(!s2.confirmHidden, 'confirm bar is visible'); + assert(/Route|Need|✕/.test(s2.hint), 'hint shows route info: ' + s2.hint); + await page.screenshot({ path: OUT + `touch-${name}-1-preview.png` }); + await page.tap('#btnConfirmBuild'); await page.waitForTimeout(150); + let s3 = await state(); + assert(s3.towers === s.towers + 1, 'confirm builds the tower'); + // tap-again-to-build + const t2 = await cellPt(10, 10); + await page.touchscreen.tap(t2.x, t2.y); await page.waitForTimeout(120); + await page.touchscreen.tap(t2.x, t2.y); await page.waitForTimeout(150); + let s4 = await state(); + assert(s4.towers === s.towers + 2, 'tapping the previewed cell again builds'); + + // 3) tapping an existing tower selects it (even with a build type active) + await page.touchscreen.tap(t1.x, t1.y); await page.waitForTimeout(150); + const sel = await page.evaluate(() => ({ t: NW.app.selTower, type: NW.app.selType, info: document.getElementById('info').innerText.slice(0, 60) })); + assert(sel.t && !sel.type, 'tap on tower selects it: ' + JSON.stringify(sel.info)); + await page.screenshot({ path: OUT + `touch-${name}-2-selected.png` }); + await page.tap('#info [data-act="up"]'); await page.waitForTimeout(150); + const lv = await page.evaluate(() => NW.app.ctrl.view.towers.find(t => t.id === NW.app.selTower).level); + assert(lv === 2, 'upgrade via info panel'); + + // 4) pinch zoom with two fingers, then reset + const c = await cellPt(13, 8); + await touch('touchStart', [{ x: c.x - 30, y: c.y }, { x: c.x + 30, y: c.y }]); + for (let i = 1; i <= 10; i++) await touch('touchMove', [{ x: c.x - 30 - i * 8, y: c.y }, { x: c.x + 30 + i * 8, y: c.y }]); + await touch('touchEnd', []); + const z = (await state()).zoom; + assert(z > 1.8, 'pinch zoomed in (zoom ' + z.toFixed(2) + ')'); + assert(!(await page.locator('#btnFit').isHidden()), 'fit button visible when zoomed'); + await page.screenshot({ path: OUT + `touch-${name}-3-zoomed.png` }); + await page.tap('#btnFit'); await page.waitForTimeout(100); + assert((await state()).zoom === 1, 'fit resets zoom'); + + // 5) long-press pings the map + await page.evaluate(() => { NW.app.selType = null; NW.app.selTower = 0; }); + const lp = await cellPt(15, 4); + await touch('touchStart', [lp]); await page.waitForTimeout(650); await touch('touchEnd', []); + assert((await state()).marks >= 1, 'long-press creates a map ping'); + console.log('rotation', (await state()).rot); + 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/03-endflow.js b/e2e/scenarios/03-endflow.js new file mode 100644 index 0000000..2ed187f --- /dev/null +++ b/e2e/scenarios/03-endflow.js @@ -0,0 +1,53 @@ +const assert = (c, m) => { if (!c) throw new Error('ASSERT: ' + m); console.log('ok -', m); }; +const sleep = (ms) => new Promise(r => setTimeout(r, ms)); +async function until(fn, ms, what) { const t0 = Date.now(); for (;;) { try { const v = await fn(); if (v) return v; } catch (e) {} if (Date.now() - t0 > ms) throw new Error('TIMEOUT: ' + what); await sleep(50); } } +module.exports = async function ({ browser, url: URL, out: OUT }) { + const errors = []; + const ctx = await browser.newContext({ viewport: { width: 1100, height: 700 } }); + 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.click('.mapcard[data-map="hub"]'); + assert((await page.evaluate(() => NW.app.ctrl.board.mapId)) === 'hub', 'map picker switches the preview board to hub'); + assert((await page.evaluate(() => NW.app.ctrl.board.spawns.length)) === 3, 'hub has 3 gateways'); + await page.click('#btnSolo'); await sleep(200); await page.click('#btnHelpClose'); + + // lose + await page.evaluate(() => { NW.app.ctrl.sim.lives = 1; }); + await page.click('#btnSpeed'); await page.click('#btnSpeed'); + await page.click('#btnWave'); + await until(() => page.evaluate(() => !document.getElementById('end').hidden), 60000, 'end overlay after losing'); + assert((await page.evaluate(() => document.getElementById('endTitle').textContent)) === 'Breach!', 'lose title'); + await page.screenshot({ path: OUT + 'end-lose.png' }); + await page.click('#btnAgain'); await sleep(300); + let st = await page.evaluate(() => ({ s: NW.app.ctrl.view.state, hidden: document.getElementById('end').hidden, lives: NW.app.ctrl.view.lives, towers: NW.app.ctrl.view.towers.length, map: NW.app.ctrl.board.mapId })); + assert(st.s === 'playing' && st.hidden && st.lives === 20 && st.towers === 0 && st.map === 'hub', 'play again resets the same map: ' + JSON.stringify(st)); + + // win (set winWave to 1) + await page.evaluate(() => { NW.app.ctrl.sim.winWave = 1; }); + await page.click('#btnWave'); + await until(() => page.evaluate(() => !document.getElementById('end').hidden), 90000, 'end overlay after winning'); + assert((await page.evaluate(() => document.getElementById('endTitle').textContent)) === 'Server secured!', 'win title'); + assert(!(await page.locator('#btnContinue').isHidden()), 'keep going button shown'); + await page.screenshot({ path: OUT + 'end-win.png' }); + await page.click('#btnContinue'); await sleep(300); + st = await page.evaluate(() => ({ s: NW.app.ctrl.view.state, hidden: document.getElementById('end').hidden })); + assert(st.s === 'playing' && st.hidden, 'continue resumes endless play'); + await page.keyboard.press('Space'); await sleep(300); + assert((await page.evaluate(() => NW.app.ctrl.view.wave)) === 2, 'space starts the next wave'); + // keyboard shortcuts + await page.keyboard.press('2'); + assert((await page.evaluate(() => NW.app.selType)) === 'filter', 'key 2 selects filter'); + await page.keyboard.press('Escape'); + assert((await page.evaluate(() => NW.app.selType)) === null, 'escape clears'); + await page.keyboard.press('p'); assert((await page.evaluate(() => NW.app.ctrl.view.paused)) === true, 'p pauses'); + await page.keyboard.press('p'); + // menu while playing + await page.click('#btnMenu'); await sleep(200); + assert(!(await page.locator('#btnCloseMenu').isHidden()), 'menu has back-to-game while playing'); + await page.keyboard.press('Escape'); await sleep(200); + assert(await page.locator('#menu').isHidden(), 'escape closes the menu'); + if (errors.length) throw new Error('console errors:\n' + errors.join('\n')); + console.log('no console errors'); +}; diff --git a/e2e/scenarios/04-coop.js b/e2e/scenarios/04-coop.js new file mode 100644 index 0000000..b7adc86 --- /dev/null +++ b/e2e/scenarios/04-coop.js @@ -0,0 +1,94 @@ +const assert = (c, m) => { if (!c) throw new Error('ASSERT: ' + m); console.log('ok -', m); }; +const sleep = (ms) => new Promise(r => setTimeout(r, ms)); +async function until(fn, ms, what) { const t0 = Date.now(); for (;;) { try { const v = await fn(); if (v) return v; } catch (e) {} if (Date.now() - t0 > ms) throw new Error('TIMEOUT: ' + what); await sleep(50); } } +module.exports = async function ({ browser, url: URL, out: OUT }) { + const errors = []; + const mk = async (name, opts) => { + 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()}`); }); + return { ctx, page, name }; + }; + const A = await mk('host-desktop', { viewport: { width: 1280, height: 800 } }); + const B = await mk('guest-phone', { viewport: { width: 390, height: 844 }, deviceScaleFactor: 2, isMobile: true, hasTouch: true }); + + // host creates a room + await A.page.goto(URL); await sleep(300); + await A.page.click('#btnCoop'); + await A.page.fill('#inName', 'Alice'); + await A.page.click('#btnCreate'); + await until(() => A.page.evaluate(() => NW.app.ctrl.kind === 'remote' && NW.app.ctrl.status === 'joined'), 5000, 'host joined'); + const room = await A.page.evaluate(() => NW.app.ctrl.room); + assert(/^[A-Z0-9]{4}$/.test(room), 'room code ' + room); + + // guest opens the invite link + await B.page.goto(URL + '?room=' + room); await sleep(300); + assert(await B.page.inputValue('#inCode') === room, 'invite link prefilled the code'); + await B.page.fill('#inName', 'Bob'); + await B.page.tap('#btnJoin'); + await until(() => B.page.evaluate(() => NW.app.ctrl.kind === 'remote' && NW.app.ctrl.status === 'joined'), 5000, 'guest joined'); + await until(() => A.page.evaluate(() => NW.app.ctrl.players.length === 2), 3000, 'host sees 2 players'); + const slots = await Promise.all([A, B].map(p => p.page.evaluate(() => NW.app.ctrl.you.slot))); + assert(slots[0] === 0 && slots[1] === 1, 'slots 0 and 1: ' + slots); + assert((await B.page.evaluate(() => NW.app.renderer.rot)) > 0, 'guest phone portrait board rotated'); + + const boxA = await A.page.locator('#board').boundingBox(), boxB = await B.page.locator('#board').boundingBox(); + const cellPt = async (p, box, cx, cy) => { const r = await p.page.evaluate(([a, b]) => NW.app.renderer.cellToScreen(a, b), [cx, cy]); return { x: box.x + r.x, y: box.y + r.y }; }; + + // host builds walls, guest sees them + await A.page.click('.tbtn[data-type="wall"]'); + for (let y = 3; y <= 9; y++) { const p = await cellPt(A, boxA, 12, y); await A.page.mouse.click(p.x, p.y); } + await until(() => B.page.evaluate(() => NW.app.ctrl.view.towers.filter(t => t.type === 'wall').length === 7), 3000, 'guest sees 7 walls'); + // both mirrored boards must converge on the same maze (each applies server changes with its own display delay) + await until(async () => { + const [ra, rb] = await Promise.all([A, B].map((p) => p.page.evaluate(() => NW.app.ctrl.board.routeLen))); + return Math.abs(ra - rb) < 1e-6 && ra > 26; + }, 3000, 'mirrored boards agree on the route length'); + console.log('ok - mirrored boards agree on the route length'); + + // guest builds a turret (tap, tap), host sees it owned by slot 1 + await B.page.tap('.tbtn[data-type="filter"]'); + const gp = await cellPt(B, boxB, 11, 6); + await B.page.touchscreen.tap(gp.x, gp.y); await sleep(150); await B.page.touchscreen.tap(gp.x, gp.y); + await until(() => A.page.evaluate(() => NW.app.ctrl.view.towers.some(t => t.type === 'filter' && t.owner === 1)), 3000, 'host sees guest turret with owner 1'); + await until(async () => (await A.page.evaluate(() => NW.app.ctrl.view.gold)) === 80 && (await B.page.evaluate(() => NW.app.ctrl.view.gold)) === 80, 3000, 'shared credits 140-35-25=80 on both screens'); + console.log('ok - shared credit pool'); + + // cursors and pings + const mp = await cellPt(A, boxA, 6, 6); + await A.page.mouse.move(mp.x, mp.y); await A.page.mouse.move(mp.x + 5, mp.y + 5); + await until(() => B.page.evaluate(() => NW.app.ctrl.view.cursors.some(c => c.slot === 0)), 3000, 'guest sees host cursor'); + await A.page.keyboard.down('Alt'); await A.page.mouse.click(mp.x, mp.y); await A.page.keyboard.up('Alt'); + await until(() => B.page.evaluate(() => NW.app.renderer.marks.length > 0), 3000, 'guest sees host ping'); + + // either player starts the wave; both see monsters; kills are shared + await B.page.tap('#btnWave'); + await until(() => A.page.evaluate(() => NW.app.ctrl.view.monsters.length > 0), 4000, 'host sees monsters'); + await sleep(2500); + await A.page.screenshot({ path: OUT + 'coop-host.png' }); + await B.page.screenshot({ path: OUT + 'coop-guest.png' }); + const mA = await A.page.evaluate(() => NW.app.ctrl.view.monsters.length), mB = await B.page.evaluate(() => NW.app.ctrl.view.monsters.length); + assert(Math.abs(mA - mB) <= 2 && mA > 0, `both see the same monsters (${mA} vs ${mB})`); + + // pause is shared; speed is shared + await A.page.click('#btnPause'); + await until(() => B.page.evaluate(() => NW.app.ctrl.view.paused === true), 3000, 'guest sees pause'); + await B.page.tap('#btnPause'); + await until(() => A.page.evaluate(() => NW.app.ctrl.view.paused === false), 3000, 'host sees resume'); + const rtt = await A.page.evaluate(() => NW.app.ctrl.rtt); + console.log('rtt ms', rtt); + + // guest's connection drops: auto reconnect resumes the same seat + await B.page.evaluate(() => NW.app.ctrl.ws.close()); + await until(() => B.page.evaluate(() => NW.app.ctrl.status === 'reconnecting'), 2000, 'guest shows reconnecting').catch(() => console.log('(reconnect was instant)')); + await until(() => B.page.evaluate(() => NW.app.ctrl.status === 'joined' && NW.app.ctrl.you.slot === 1), 8000, 'guest resumed seat'); + const towersB = await B.page.evaluate(() => NW.app.ctrl.view.towers.length); + assert(towersB === 8, 'state restored after reconnect (' + towersB + ' towers)'); + + // host leaves -> guest becomes host + await A.page.evaluate(() => NW.app.ctrl.close()); + await until(() => B.page.evaluate(() => NW.app.ctrl.players.length === 1 && NW.app.ctrl.you.host), 4000, 'guest promoted to host'); + + if (errors.length) throw new Error('console errors:\n' + errors.join('\n')); + console.log('no console errors'); +}; diff --git a/e2e/scenarios/05-layout-matrix.js b/e2e/scenarios/05-layout-matrix.js new file mode 100644 index 0000000..e9c905e --- /dev/null +++ b/e2e/scenarios/05-layout-matrix.js @@ -0,0 +1,32 @@ +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]]; +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(); + } + if (bad) throw new Error(bad + ' layouts have problems'); + console.log('all layouts ok'); +}; diff --git a/package-lock.json b/package-lock.json index 0a35fb2..5336be0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,10 +10,26 @@ "dependencies": { "ws": "^8.18.0" }, + "devDependencies": { + "playwright-core": "^1.49.0" + }, "engines": { "node": ">=18" } }, + "node_modules/playwright-core": { + "version": "1.64.0", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.0.tgz", + "integrity": "sha512-T9r+MZkTECl2+oUcZ26YgZzTrYidTsIhYYkJix+6iDOymOb1FB2RLLSOxRGnZGv5DStt+aduIVbt+E8WygXYpg==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/ws": { "version": "8.22.0", "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz", diff --git a/package.json b/package.json index 9c898b3..ae9d02f 100644 --- a/package.json +++ b/package.json @@ -6,10 +6,16 @@ "main": "server/index.js", "scripts": { "start": "node server/index.js", - "test": "node --test" + "test": "node --test", + "e2e": "node e2e/run.js" + }, + "engines": { + "node": ">=18" }, - "engines": { "node": ">=18" }, "dependencies": { "ws": "^8.18.0" + }, + "devDependencies": { + "playwright-core": "^1.49.0" } } diff --git a/public/assets/music/tracks.json b/public/assets/music/tracks.json index 0aca0d7..db767ef 100644 --- a/public/assets/music/tracks.json +++ b/public/assets/music/tracks.json @@ -1,8 +1,8 @@ { - "_help": "Put your music files in this folder and name them here, for example \"battle\": \"my-song.mp3\". Leave a track as null to use the built-in synth melody.", - "theme": null, - "battle": null, - "boss": null, - "win": null, - "lose": null + "_help": "Name your music files here, for example \"battle\": \"my-song.mp3\". Leave a track as null to use the built-in synth melody.", + "theme": "menu.mp3", + "battle": "battle.mp3", + "boss": "boss.mp3", + "win": "win.mp3", + "lose": "lose.mp3" } diff --git a/public/css/style.css b/public/css/style.css index 43ec97c..61086ca 100644 --- a/public/css/style.css +++ b/public/css/style.css @@ -108,6 +108,7 @@ button.floating { position: absolute; right: 8px; bottom: 8px; background: rgba( .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; } .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); } diff --git a/public/icons/icon-192.png b/public/icons/icon-192.png index b077faf..5acaa41 100644 Binary files a/public/icons/icon-192.png and b/public/icons/icon-192.png differ diff --git a/public/icons/icon-512.png b/public/icons/icon-512.png index e336af1..e986cce 100644 Binary files a/public/icons/icon-512.png and b/public/icons/icon-512.png differ diff --git a/public/icons/icon-maskable-512.png b/public/icons/icon-maskable-512.png index 410b049..de567b5 100644 Binary files a/public/icons/icon-maskable-512.png and b/public/icons/icon-maskable-512.png differ diff --git a/public/icons/icon.svg b/public/icons/icon.svg index 4a14515..dac009a 100644 --- a/public/icons/icon.svg +++ b/public/icons/icon.svg @@ -4,20 +4,16 @@ - + - - - + + - - - - - - - - - + + + + + + diff --git a/public/index.html b/public/index.html index 95f6d7d..734797d 100644 --- a/public/index.html +++ b/public/index.html @@ -59,6 +59,7 @@ +