Add co-op server, deploy docs, e2e suite and wire in the music tracks
- server/: Node (ws) static server + authoritative co-op rooms; dual-stack listen, proxy-aware client IP and Origin check, keep-alive pings, per-socket rate limits, graceful shutdown; 59 node:test tests - docs/DEPLOY.md + deploy/netwall.service: Debian 13 LXC, systemd, nginx Proxy Manager walk-through, path prefix, troubleshooting - e2e/: Playwright suite (smoke, touch, end flow, two-browser co-op incl. reconnect, 14-size layout matrix); npm run e2e - Music: tracks.json now points at the uploaded theme/battle/boss/win/lose files; stingers fade out when a new game starts - PAUSED indicator, refreshed icon Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Tb8pW2KAN4oFkh1aK1BfD8
4
.gitignore
vendored
|
|
@ -4,3 +4,7 @@ node_modules/
|
|||
.env
|
||||
# local scratch
|
||||
/tmp/
|
||||
|
||||
# e2e screenshots
|
||||
/e2e/out/
|
||||
*.pid
|
||||
|
|
|
|||
10
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/`.
|
||||
|
|
|
|||
71
deploy/netwall.service
Normal file
|
|
@ -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
|
||||
287
docs/DEPLOY.md
Normal file
|
|
@ -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@<lxc>:/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://<lxc>: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.
|
||||
|
|
@ -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
|
||||
|
|
|
|||
49
e2e/run.js
Normal file
|
|
@ -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); });
|
||||
47
e2e/scenarios/01-smoke.js
Normal file
|
|
@ -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');
|
||||
};
|
||||
78
e2e/scenarios/02-touch.js
Normal file
|
|
@ -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');
|
||||
};
|
||||
53
e2e/scenarios/03-endflow.js
Normal file
|
|
@ -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');
|
||||
};
|
||||
94
e2e/scenarios/04-coop.js
Normal file
|
|
@ -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');
|
||||
};
|
||||
32
e2e/scenarios/05-layout-matrix.js
Normal file
|
|
@ -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');
|
||||
};
|
||||
16
package-lock.json
generated
|
|
@ -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",
|
||||
|
|
|
|||
10
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"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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); }
|
||||
|
|
|
|||
|
Before Width: | Height: | Size: 22 KiB After Width: | Height: | Size: 24 KiB |
|
Before Width: | Height: | Size: 113 KiB After Width: | Height: | Size: 116 KiB |
|
Before Width: | Height: | Size: 75 KiB After Width: | Height: | Size: 80 KiB |
|
|
@ -4,20 +4,16 @@
|
|||
</defs>
|
||||
<rect width="512" height="512" rx="112" fill="url(#g)"/>
|
||||
<rect x="20" y="20" width="472" height="472" rx="94" fill="none" stroke="#4de3ff" stroke-opacity=".4" stroke-width="6"/>
|
||||
<!-- firewall bricks with a gap the route squeezes through -->
|
||||
<!-- two wall rows with staggered gaps: the route has to snake through -->
|
||||
<g fill="#12305e" stroke="#5aa9ff" stroke-width="7" stroke-linejoin="round">
|
||||
<rect x="96" y="112" width="96" height="58" rx="10"/><rect x="208" y="112" width="96" height="58" rx="10"/><rect x="320" y="112" width="96" height="58" rx="10"/>
|
||||
<rect x="152" y="186" width="96" height="58" rx="10"/><rect x="264" y="186" width="96" height="58" rx="10"/>
|
||||
<rect x="96" y="260" width="96" height="58" rx="10"/><rect x="320" y="260" width="96" height="58" rx="10"/>
|
||||
<rect x="150" y="126" width="96" height="56" rx="10"/><rect x="258" y="126" width="96" height="56" rx="10"/><rect x="366" y="126" width="96" height="56" rx="10"/>
|
||||
<rect x="46" y="218" width="96" height="56" rx="10"/><rect x="154" y="218" width="96" height="56" rx="10"/><rect x="262" y="218" width="96" height="56" rx="10"/>
|
||||
</g>
|
||||
<!-- the long route -->
|
||||
<path d="M70 372 H256 V288 M256 288 H288 M288 288 V216 M288 216 H128 M128 216 V142 H460" fill="none" stroke="#4de3ff" stroke-width="9" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="2 22" opacity=".0"/>
|
||||
<path d="M66 366 H236 V290 H292 V214 H132 V140 H236 V86" fill="none" stroke="#4de3ff" stroke-width="10" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="1 24" opacity="0"/>
|
||||
<path d="M64 390 H224 V342 H296 V288 H224 V226 H128 V140" fill="none" stroke="#ffd24d" stroke-width="0" />
|
||||
<path d="M60 392 C 150 392 150 340 232 340 S 300 290 300 250 S 120 250 120 214" fill="none" stroke="#4de3ff" stroke-width="11" stroke-linecap="round" stroke-dasharray="1 26" opacity=".95"/>
|
||||
<circle cx="60" cy="392" r="20" fill="#ff5c7a"/><circle cx="60" cy="392" r="9" fill="#2a0c18"/>
|
||||
<!-- the server -->
|
||||
<rect x="396" y="334" width="76" height="96" rx="14" fill="#0d2038" stroke="#4de3ff" stroke-width="8"/>
|
||||
<g stroke="#4de3ff" stroke-width="7" stroke-linecap="round"><path d="M414 358h24M414 380h24M414 402h24"/></g>
|
||||
<g fill="#35e0a1"><circle cx="458" cy="358" r="5"/><circle cx="458" cy="380" r="5"/><circle cx="458" cy="402" r="5"/></g>
|
||||
<path d="M74 404 H414 V200 H98 V74 H388" fill="none" stroke="#4de3ff" stroke-width="11" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="1 25"/>
|
||||
<!-- gateway and server -->
|
||||
<circle cx="74" cy="404" r="22" fill="#ff5c7a"/><circle cx="74" cy="404" r="9" fill="#2a0c18"/>
|
||||
<rect x="392" y="36" width="72" height="84" rx="14" fill="#0d2038" stroke="#4de3ff" stroke-width="8"/>
|
||||
<g stroke="#4de3ff" stroke-width="7" stroke-linecap="round"><path d="M410 60h22M410 78h22M410 96h22"/></g>
|
||||
<g fill="#35e0a1"><circle cx="448" cy="60" r="4.5"/><circle cx="448" cy="78" r="4.5"/><circle cx="448" cy="96" r="4.5"/></g>
|
||||
</svg>
|
||||
|
|
|
|||
|
Before Width: | Height: | Size: 2.1 KiB After Width: | Height: | Size: 1.5 KiB |
|
|
@ -59,6 +59,7 @@
|
|||
<canvas id="board" aria-label="Game board" role="img"></canvas>
|
||||
<div id="hint" class="hint" hidden></div>
|
||||
<div id="banner" class="banner" aria-live="polite"></div>
|
||||
<div id="pausedTag" class="paused-tag" hidden>PAUSED</div>
|
||||
<div id="toasts" aria-live="polite"></div>
|
||||
<button id="btnFit" class="icon floating" aria-label="Reset zoom" hidden><svg class="ic"><use href="#i-fit"/></svg></button>
|
||||
<div id="confirm" class="confirm" hidden>
|
||||
|
|
|
|||
|
|
@ -242,6 +242,7 @@
|
|||
|
||||
function applyMusic() {
|
||||
if (!unlocked) return;
|
||||
if (wanted) stopStinger(0.8);
|
||||
if (!wanted || muted) { stopCurrent(0.4); return; }
|
||||
if (current && current.name === wanted) return;
|
||||
const name = wanted;
|
||||
|
|
@ -264,10 +265,15 @@
|
|||
});
|
||||
}
|
||||
|
||||
let stingEl = null;
|
||||
function stopStinger(fade) {
|
||||
const el = stingEl; stingEl = null;
|
||||
if (el) fadeEl(el, 0, (fade || 0.6) * 1000, () => { try { el.pause(); } catch (e) { /* ignore */ } });
|
||||
}
|
||||
function stinger(name) {
|
||||
if (muted || !unlocked) return;
|
||||
fileFor(name, (el) => {
|
||||
if (el) { try { el.currentTime = 0; el.volume = Math.min(1, 0.9 * Math.max(0.3, musicVol)); el.play().catch(() => {}); } catch (e) { /* ignore */ } return; }
|
||||
if (el) { try { stopStinger(0.2); stingEl = el; el.currentTime = 0; el.volume = Math.min(1, 0.9 * Math.max(0.3, musicVol)); el.play().catch(() => {}); } catch (e) { /* ignore */ } return; }
|
||||
if (name === 'win') { [0, 4, 7, 12, 16, 19, 24].forEach((n, i) => tone(NOTE(69 + n), 0.3, 'triangle', 0.22, 0, i * 0.11)); }
|
||||
else { [0, -3, -7, -12, -17].forEach((n, i) => tone(NOTE(60 + n), 0.5, 'sawtooth', 0.2, NOTE(58 + n), i * 0.22)); }
|
||||
});
|
||||
|
|
@ -300,6 +306,7 @@
|
|||
unlock,
|
||||
stinger,
|
||||
get muted() { return muted; },
|
||||
get now() { return current ? { name: current.name, kind: current.kind } : null; }, // for tests / debugging
|
||||
setMuted(m) {
|
||||
muted = !!m; save();
|
||||
if (master) master.gain.value = muted ? 0 : 0.9;
|
||||
|
|
|
|||
|
|
@ -379,7 +379,7 @@
|
|||
if (L.attn !== attn) { L.attn = attn; $('btnWave').classList.toggle('attn', attn); }
|
||||
if (L.auto !== view.auto) { L.auto = view.auto; $('btnAuto').setAttribute('aria-pressed', view.auto ? 'true' : 'false'); }
|
||||
if (L.speed !== view.speed) { L.speed = view.speed; $('speedText').textContent = view.speed + '×'; }
|
||||
if (L.paused !== view.paused) { L.paused = view.paused; $('btnPause').innerHTML = '<svg class="ic"><use href="#i-' + (view.paused ? 'play' : 'pause') + '"/></svg>'; $('btnPause').setAttribute('aria-label', view.paused ? 'Resume' : 'Pause'); }
|
||||
if (L.paused !== view.paused) { L.paused = view.paused; $('pausedTag').hidden = !view.paused; $('btnPause').innerHTML = '<svg class="ic"><use href="#i-' + (view.paused ? 'play' : 'pause') + '"/></svg>'; $('btnPause').setAttribute('aria-label', view.paused ? 'Resume' : 'Pause'); }
|
||||
if (L.muted !== Audio.muted) { L.muted = Audio.muted; $('btnSound').innerHTML = '<svg class="ic"><use href="#i-' + (Audio.muted ? 'mute' : 'sound') + '"/></svg>'; }
|
||||
// palette affordability
|
||||
const gold = view.gold;
|
||||
|
|
|
|||
315
server/index.js
Normal file
|
|
@ -0,0 +1,315 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Netwall server: static files + one WebSocket endpoint (/ws) running authoritative co-op game rooms.
|
||||
* See docs/PROTOCOL.md (wire contract) and docs/DEPLOY.md (running it behind nginx Proxy Manager).
|
||||
*
|
||||
* const { createServer } = require('./server');
|
||||
* const srv = await createServer({ port: 8080 }); // srv.port, srv.addresses, srv.close(), srv.rooms
|
||||
*
|
||||
* Run directly: PORT=8080 HOST=:: TRUST_PROXY=auto ALLOWED_ORIGINS=https://game.example.com node server/index.js
|
||||
*/
|
||||
const http = require('http');
|
||||
const path = require('path');
|
||||
const { WebSocketServer } = require('ws');
|
||||
const TD = require('../public/js/sim.js');
|
||||
const { RoomManager } = require('./room');
|
||||
const { createStaticHandler, applySecurityHeaders, CSP } = require('./static');
|
||||
const { parseTrustProxy, clientIp, originAllowed, TokenBucket, listenDual, listUrls } = require('./net');
|
||||
|
||||
const MAX_PAYLOAD = 2048; // bytes per client frame
|
||||
const RATE_PER_SEC = 60, RATE_BURST = 120;
|
||||
const MAX_BAD_MESSAGES = 20;
|
||||
const PID_RE = /^[A-Za-z0-9_-]{8,40}$/;
|
||||
const ROOM_RE = /^[A-Za-z0-9]{4}$/;
|
||||
const NAME_STRIP = new RegExp('[\\u0000-\\u001f\\u007f-\\u009f\\u200b-\\u200f\\u2028-\\u202e\\u2066-\\u2069\\ufeff]', 'g');
|
||||
// Close codes for a failed join (the 'error' message carries the machine-readable code).
|
||||
const JOIN_CLOSE = { bad_request: 4400, bad_map: 4400, no_room: 4404, full: 4409, too_many_rooms: 4503 };
|
||||
|
||||
const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
|
||||
const noop = () => {};
|
||||
|
||||
function cleanName(v) {
|
||||
if (typeof v !== 'string') return 'Player';
|
||||
const s = Array.from(v.replace(NAME_STRIP, '').trim()).slice(0, 16).join('').trim();
|
||||
return s || 'Player';
|
||||
}
|
||||
|
||||
function defaultLog(msg) { console.log(new Date().toISOString() + ' ' + msg); }
|
||||
|
||||
async function createServer(userOpts) {
|
||||
const o = {
|
||||
port: 8080, host: '::', publicDir: path.join(__dirname, '..', 'public'),
|
||||
graceMs: 60000, snapshotHz: 20, maxRooms: 50,
|
||||
trustProxy: 'auto', allowedOrigins: [], maxConnPerIp: 40, pingMs: 25000, log: defaultLog,
|
||||
joinTimeoutMs: 10000, // not in the protocol's option list: lets tests shorten the 10 s join window
|
||||
};
|
||||
for (const k of Object.keys(userOpts || {})) if (userOpts[k] !== undefined) o[k] = userOpts[k];
|
||||
o.trustProxy = parseTrustProxy(o.trustProxy);
|
||||
o.allowedOrigins = (o.allowedOrigins || []).map(String).filter(Boolean);
|
||||
o.snapshotHz = Math.min(60, Math.max(1, Number(o.snapshotHz) || 20));
|
||||
const log = typeof o.log === 'function' ? o.log : noop;
|
||||
|
||||
const manager = new RoomManager({ maxRooms: o.maxRooms, graceMs: o.graceMs, snapshotHz: o.snapshotHz, log });
|
||||
const serveStatic = createStaticHandler(o.publicDir);
|
||||
const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_PAYLOAD, perMessageDeflate: false });
|
||||
wss.on('error', (err) => log('websocket server error: ' + (err && err.message)));
|
||||
|
||||
let closing = false;
|
||||
const ipCount = new Map(); // client ip -> open websockets
|
||||
const sockets = new Set(); // every raw TCP socket, so close() can finish the job
|
||||
|
||||
// ---------------------------------------------------------------- HTTP
|
||||
const server = http.createServer((req, res) => {
|
||||
applySecurityHeaders(res);
|
||||
const pathOnly = (req.url || '').split(/[?#]/)[0];
|
||||
if (pathOnly === '/healthz') {
|
||||
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
||||
res.writeHead(405, { Allow: 'GET, HEAD', 'Content-Length': 0 });
|
||||
return res.end();
|
||||
}
|
||||
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8', 'Content-Length': 2, 'Cache-Control': 'no-store' });
|
||||
return res.end(req.method === 'HEAD' ? undefined : 'ok');
|
||||
}
|
||||
if (pathOnly === '/ws') { // a plain GET of the socket endpoint
|
||||
res.writeHead(426, { Upgrade: 'websocket', Connection: 'Upgrade', 'Content-Type': 'text/plain; charset=utf-8', 'Content-Length': 17 });
|
||||
return res.end(req.method === 'HEAD' ? undefined : 'Upgrade Required\n');
|
||||
}
|
||||
serveStatic(req, res).catch((err) => {
|
||||
log('static error: ' + (err && err.message));
|
||||
if (!res.headersSent) { res.writeHead(500, { 'Content-Length': 0 }); res.end(); } else res.destroy();
|
||||
});
|
||||
});
|
||||
// Longer than the typical 60 s idle timeout of reverse proxies, so a keep-alive upstream connection is
|
||||
// never closed from under them (the classic intermittent 502).
|
||||
server.keepAliveTimeout = 65000;
|
||||
server.headersTimeout = 66000;
|
||||
server.on('connection', (s) => { sockets.add(s); s.once('close', () => sockets.delete(s)); });
|
||||
|
||||
// ---------------------------------------------------------------- WebSocket upgrade
|
||||
function refuse(socket, status, text) {
|
||||
socket.end('HTTP/1.1 ' + status + ' ' + text + '\r\nConnection: close\r\nContent-Length: 0\r\n' +
|
||||
'X-Content-Type-Options: nosniff\r\nReferrer-Policy: no-referrer\r\nContent-Security-Policy: ' + CSP + '\r\n\r\n');
|
||||
}
|
||||
|
||||
server.on('upgrade', (req, socket, head) => {
|
||||
socket.on('error', noop);
|
||||
if (closing) return refuse(socket, 503, 'Service Unavailable');
|
||||
if ((req.url || '').split('?')[0] !== '/ws') return refuse(socket, 404, 'Not Found');
|
||||
if (!originAllowed(req, o)) {
|
||||
log('refused websocket from ' + clientIp(req, o.trustProxy) + ': Origin ' + JSON.stringify(req.headers.origin) +
|
||||
' does not match Host ' + JSON.stringify(req.headers.host) + ' (see ALLOWED_ORIGINS)');
|
||||
return refuse(socket, 403, 'Forbidden');
|
||||
}
|
||||
const ip = clientIp(req, o.trustProxy);
|
||||
if (o.maxConnPerIp > 0 && (ipCount.get(ip) || 0) >= o.maxConnPerIp) {
|
||||
log('refused websocket from ' + ip + ': too many connections');
|
||||
return refuse(socket, 429, 'Too Many Requests');
|
||||
}
|
||||
ipCount.set(ip, (ipCount.get(ip) || 0) + 1);
|
||||
socket.once('close', () => {
|
||||
const n = (ipCount.get(ip) || 1) - 1;
|
||||
if (n > 0) ipCount.set(ip, n); else ipCount.delete(ip);
|
||||
});
|
||||
wss.handleUpgrade(req, socket, head, (ws) => onConnection(ws, ip));
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- one socket
|
||||
function send(ctx, obj) {
|
||||
if (ctx.ws.readyState === 1) { try { ctx.ws.send(JSON.stringify(obj)); } catch (e) { /* closing */ } }
|
||||
}
|
||||
|
||||
// Close from our side. Anything the client still sends afterwards is ignored.
|
||||
function kill(ctx, code, reason) {
|
||||
if (ctx.dead) return;
|
||||
ctx.dead = true;
|
||||
try { ctx.ws.close(code, reason); } catch (e) { /* already closed */ }
|
||||
ctx.killTimer = setTimeout(() => { try { ctx.ws.terminate(); } catch (e) { /* gone */ } }, 2000);
|
||||
}
|
||||
|
||||
function failJoin(ctx, code, msg) {
|
||||
send(ctx, { t: 'error', code, msg });
|
||||
kill(ctx, JOIN_CLOSE[code] || 4400, code);
|
||||
}
|
||||
|
||||
function onConnection(ws, ip) {
|
||||
const ctx = {
|
||||
ws, ip, bucket: new TokenBucket(RATE_PER_SEC, RATE_BURST), bad: 0,
|
||||
player: null, room: null, dead: false, alive: true, joinTimer: null, killTimer: null,
|
||||
};
|
||||
ws.ctx = ctx;
|
||||
ws.on('error', noop); // oversize frames etc.: ws closes the socket itself right after
|
||||
ws.on('pong', () => { ctx.alive = true; });
|
||||
// A bug must never take the whole process (and every other room) down: drop just this socket.
|
||||
ws.on('message', (data, isBinary) => {
|
||||
try { onMessage(ctx, data, isBinary); } catch (err) {
|
||||
log('error handling a message from ' + ip + ': ' + (err && err.stack || err));
|
||||
kill(ctx, 1011, 'internal error');
|
||||
}
|
||||
});
|
||||
ws.on('close', () => { try { onClose(ctx); } catch (err) { log('error in close handler: ' + (err && err.stack || err)); } });
|
||||
ctx.joinTimer = setTimeout(() => {
|
||||
ctx.joinTimer = null;
|
||||
if (!ctx.player) kill(ctx, 4408, 'join timeout');
|
||||
}, o.joinTimeoutMs);
|
||||
}
|
||||
|
||||
function onClose(ctx) {
|
||||
ctx.dead = true;
|
||||
if (ctx.joinTimer) { clearTimeout(ctx.joinTimer); ctx.joinTimer = null; }
|
||||
if (ctx.killTimer) { clearTimeout(ctx.killTimer); ctx.killTimer = null; }
|
||||
if (ctx.room && ctx.player) ctx.room.disconnect(ctx);
|
||||
}
|
||||
|
||||
function malformed(ctx) {
|
||||
if (!ctx.player) return failJoin(ctx, 'bad_request', 'expected a valid join message');
|
||||
if (++ctx.bad > MAX_BAD_MESSAGES) kill(ctx, 4400, 'too many malformed messages');
|
||||
}
|
||||
|
||||
function onMessage(ctx, data, isBinary) {
|
||||
if (ctx.dead) return;
|
||||
if (!ctx.bucket.take()) { log('rate limit exceeded by ' + ctx.ip); return kill(ctx, 4429, 'rate limit'); }
|
||||
if (isBinary) return malformed(ctx);
|
||||
let msg;
|
||||
try { msg = JSON.parse(data.toString('utf8')); } catch (e) { return malformed(ctx); }
|
||||
if (!msg || typeof msg !== 'object' || Array.isArray(msg) || typeof msg.t !== 'string') return malformed(ctx);
|
||||
if (!ctx.player) {
|
||||
if (msg.t !== 'join') return malformed(ctx);
|
||||
return handleJoin(ctx, msg);
|
||||
}
|
||||
if (msg.t === 'leave') {
|
||||
const room = ctx.room;
|
||||
room.leave(ctx);
|
||||
kill(ctx, 1000, 'left');
|
||||
return;
|
||||
}
|
||||
if (!ctx.room.handleMessage(ctx.player, msg)) malformed(ctx);
|
||||
}
|
||||
|
||||
function handleJoin(ctx, msg) {
|
||||
if (closing) return kill(ctx, 1001, 'server shutting down');
|
||||
if (typeof msg.pid !== 'string' || !PID_RE.test(msg.pid)) return failJoin(ctx, 'bad_request', 'pid must match ^[A-Za-z0-9_-]{8,40}$');
|
||||
const creating = msg.room === undefined || msg.room === null;
|
||||
if (!creating && (typeof msg.room !== 'string' || !ROOM_RE.test(msg.room))) return failJoin(ctx, 'bad_request', 'room must be 4 letters or digits');
|
||||
const name = cleanName(msg.name);
|
||||
|
||||
let room, why;
|
||||
if (creating) {
|
||||
let map = 'open';
|
||||
if (msg.map !== undefined && msg.map !== null) {
|
||||
if (typeof msg.map !== 'string' || !hasOwn(TD.MAPS, msg.map)) return failJoin(ctx, 'bad_map', 'unknown map');
|
||||
map = msg.map;
|
||||
}
|
||||
room = manager.create(map);
|
||||
if (!room) return failJoin(ctx, 'too_many_rooms', 'the server has reached its room limit');
|
||||
why = 'created';
|
||||
} else {
|
||||
room = manager.get(msg.room.toUpperCase());
|
||||
if (!room) return failJoin(ctx, 'no_room', 'no such room');
|
||||
}
|
||||
|
||||
const r = room.join(msg.pid, name, ctx);
|
||||
if (!r) return failJoin(ctx, 'full', 'both slots in this room are taken');
|
||||
ctx.player = r.player;
|
||||
ctx.room = room;
|
||||
if (ctx.joinTimer) { clearTimeout(ctx.joinTimer); ctx.joinTimer = null; }
|
||||
send(ctx, room.joinedMsg(r.player, r.resumed));
|
||||
room.broadcastPlayers(ctx);
|
||||
room.log(name + ' ' + (r.resumed ? 'resumed' : (why || 'joined')) + ' as slot ' + r.player.slot + (r.player.host ? ' (host)' : '') + ' from ' + ctx.ip);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- listen / close
|
||||
const bound = await listenDual(server, o.port, o.host, log);
|
||||
const addr = server.address();
|
||||
const port = addr && typeof addr === 'object' ? addr.port : o.port;
|
||||
server.on('error', (err) => log('http server error: ' + (err && err.message))); // e.g. EMFILE while accepting
|
||||
|
||||
// ---------------------------------------------------------------- keep-alive
|
||||
// Protocol-level ping every pingMs; a socket that did not pong since the previous round is terminated
|
||||
// (it then enters the room's grace period). Keeps idle proxies (nginx proxy_read_timeout) happy.
|
||||
let pingTimer = null;
|
||||
if (o.pingMs > 0) {
|
||||
pingTimer = setInterval(() => {
|
||||
for (const ws of wss.clients) {
|
||||
const ctx = ws.ctx;
|
||||
if (!ctx) continue;
|
||||
if (!ctx.alive) { ws.terminate(); continue; }
|
||||
ctx.alive = false;
|
||||
try { ws.ping(); } catch (e) { /* closing */ }
|
||||
}
|
||||
}, o.pingMs);
|
||||
}
|
||||
|
||||
let closePromise = null;
|
||||
function close() {
|
||||
if (closePromise) return closePromise;
|
||||
closePromise = (async () => {
|
||||
closing = true;
|
||||
if (pingTimer) { clearInterval(pingTimer); pingTimer = null; }
|
||||
manager.close();
|
||||
const stopped = new Promise((resolve) => server.close(() => resolve()));
|
||||
for (const ws of wss.clients) {
|
||||
const ctx = ws.ctx;
|
||||
if (ctx) { ctx.dead = true; if (ctx.joinTimer) clearTimeout(ctx.joinTimer); }
|
||||
try { ws.close(1001, 'server shutting down'); } catch (e) { /* closing */ }
|
||||
}
|
||||
const deadline = Date.now() + 1000;
|
||||
while (wss.clients.size && Date.now() < deadline) await new Promise((r) => setTimeout(r, 10));
|
||||
for (const ws of wss.clients) { try { ws.terminate(); } catch (e) { /* gone */ } }
|
||||
if (typeof server.closeAllConnections === 'function') server.closeAllConnections();
|
||||
for (const s of sockets) s.destroy();
|
||||
await new Promise((r) => wss.close(() => r()));
|
||||
await stopped;
|
||||
})();
|
||||
return closePromise;
|
||||
}
|
||||
|
||||
return { port, host: bound, addresses: [bound], close, rooms: manager.rooms, options: o };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- run directly
|
||||
function envInt(name, def) {
|
||||
const v = process.env[name];
|
||||
if (v === undefined || v === '') return def;
|
||||
const n = Number(v);
|
||||
if (!Number.isInteger(n) || n < 0) throw new Error(name + ' must be a non-negative integer (got ' + JSON.stringify(v) + ')');
|
||||
return n;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const opts = {
|
||||
port: envInt('PORT', 8080),
|
||||
host: process.env.HOST || '::',
|
||||
trustProxy: process.env.TRUST_PROXY || 'auto',
|
||||
allowedOrigins: (process.env.ALLOWED_ORIGINS || '').split(',').map((s) => s.trim()).filter(Boolean),
|
||||
};
|
||||
if (process.env.MAX_CONN_PER_IP) opts.maxConnPerIp = envInt('MAX_CONN_PER_IP', 40);
|
||||
if (process.env.GRACE_MS) opts.graceMs = envInt('GRACE_MS', 60000);
|
||||
const srv = await createServer(opts);
|
||||
const shownProxy = parseTrustProxy(opts.trustProxy);
|
||||
console.log('Netwall is listening on ' + (srv.host.includes(':') ? '[' + srv.host + ']' : srv.host) + ':' + srv.port +
|
||||
(srv.host === '::' ? ' (dual stack: IPv4 + IPv6)' : srv.host === '0.0.0.0' ? ' (IPv4 only)' : ''));
|
||||
console.log(' trust proxy: ' + shownProxy + ', extra allowed origins: ' + (opts.allowedOrigins.join(', ') || '(none)'));
|
||||
console.log('Open:');
|
||||
for (const u of listUrls(srv.host, srv.port)) console.log(' ' + u);
|
||||
|
||||
let stopping = false;
|
||||
const stop = (sig) => {
|
||||
if (stopping) { console.log('second ' + sig + ', exiting now'); process.exit(0); }
|
||||
stopping = true;
|
||||
console.log('received ' + sig + ', shutting down');
|
||||
const force = setTimeout(() => { console.log('shutdown timed out, exiting'); process.exit(0); }, 5000);
|
||||
force.unref();
|
||||
srv.close().then(() => process.exit(0), (err) => { console.error(err); process.exit(0); });
|
||||
};
|
||||
process.on('SIGINT', () => stop('SIGINT'));
|
||||
process.on('SIGTERM', () => stop('SIGTERM'));
|
||||
}
|
||||
|
||||
module.exports = { createServer, cleanName };
|
||||
|
||||
if (require.main === module) {
|
||||
main().catch((err) => {
|
||||
console.error('Netwall failed to start: ' + (err && err.message || err));
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
225
server/net.js
Normal file
|
|
@ -0,0 +1,225 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Networking helpers: client IP / reverse-proxy awareness, Origin check, token bucket,
|
||||
* dual-stack listen and the "what URLs can I open" list for the start-up banner.
|
||||
* No dependencies beyond Node core.
|
||||
*/
|
||||
const net = require('net');
|
||||
const os = require('os');
|
||||
const { performance } = require('perf_hooks');
|
||||
|
||||
// ---------------------------------------------------------------- addresses
|
||||
// "::ffff:1.2.3.4" -> "1.2.3.4"; strips an IPv6 zone ("fe80::1%eth0"); lower-cases.
|
||||
function normalizeIp(addr) {
|
||||
if (typeof addr !== 'string') return '';
|
||||
let a = addr.trim().toLowerCase();
|
||||
const z = a.indexOf('%');
|
||||
if (z >= 0) a = a.slice(0, z);
|
||||
if (a.startsWith('::ffff:') && net.isIPv4(a.slice(7))) a = a.slice(7);
|
||||
return a;
|
||||
}
|
||||
|
||||
// Loopback, RFC1918, link-local, unique-local (fc00::/7) and the unspecified address.
|
||||
function isPrivateIp(addr) {
|
||||
const ip = normalizeIp(addr);
|
||||
if (net.isIPv4(ip)) {
|
||||
const [a, b] = ip.split('.').map(Number);
|
||||
return a === 127 || a === 10 || a === 0 ||
|
||||
(a === 172 && b >= 16 && b <= 31) ||
|
||||
(a === 192 && b === 168) ||
|
||||
(a === 169 && b === 254);
|
||||
}
|
||||
if (net.isIPv6(ip)) {
|
||||
if (ip === '::1' || ip === '::') return true;
|
||||
const first = ip.startsWith('::') ? 0 : parseInt(ip.split(':')[0], 16);
|
||||
if ((first & 0xfe00) === 0xfc00) return true; // fc00::/7
|
||||
if ((first & 0xffc0) === 0xfe80) return true; // fe80::/10
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// 'auto' | true | false, also from env-style strings ('1', '0', 'true', 'off' ...).
|
||||
function parseTrustProxy(v) {
|
||||
if (v === undefined || v === null || v === '') return 'auto';
|
||||
if (v === true || v === false) return v;
|
||||
if (typeof v === 'number') return v !== 0;
|
||||
const s = String(v).trim().toLowerCase();
|
||||
if (s === 'auto') return 'auto';
|
||||
if (['1', 'true', 'yes', 'on'].includes(s)) return true;
|
||||
if (['0', 'false', 'no', 'off'].includes(s)) return false;
|
||||
throw new Error('invalid trustProxy value: ' + JSON.stringify(v) + " (use 'auto', '1' or '0')");
|
||||
}
|
||||
|
||||
function peerIp(req) {
|
||||
return normalizeIp(req.socket && req.socket.remoteAddress) || 'unknown';
|
||||
}
|
||||
|
||||
// Does this request come from a proxy whose X-Forwarded-* headers we believe?
|
||||
function isTrustedPeer(req, trustProxy) {
|
||||
if (trustProxy === true) return true;
|
||||
if (trustProxy === false) return false;
|
||||
return isPrivateIp(peerIp(req));
|
||||
}
|
||||
|
||||
// One entry of a forwarding header ("203.0.113.9", "[2001:db8::5]:443", "1.2.3.4:5555") -> bare IP or null.
|
||||
function parseForwardedEntry(raw) {
|
||||
let a = String(raw).trim();
|
||||
if (!a) return null;
|
||||
if (a[0] === '[') { const e = a.indexOf(']'); if (e < 0) return null; a = a.slice(1, e); }
|
||||
else if (/^\d+\.\d+\.\d+\.\d+:\d+$/.test(a)) a = a.slice(0, a.lastIndexOf(':'));
|
||||
a = normalizeIp(a);
|
||||
return net.isIP(a) ? a : null;
|
||||
}
|
||||
|
||||
// First address of a header value like "203.0.113.9, 10.0.0.2" (used for X-Real-IP, which holds one address).
|
||||
function firstForwardedIp(value) {
|
||||
return typeof value === 'string' ? parseForwardedEntry(value.split(',')[0]) : null;
|
||||
}
|
||||
|
||||
// The client address in an X-Forwarded-For built by proxies that APPEND (nginx $proxy_add_x_forwarded_for, which is
|
||||
// what nginx Proxy Manager does): everything left of the proxy's own entry is whatever the client chose to send, so
|
||||
// the first entry is forgeable (it lets a client dodge the per-IP cap or use up somebody else's). Walk from the
|
||||
// right instead, skip the private addresses of our own proxy hops and take the first public one. A chain that is
|
||||
// private all the way (LAN clients) yields its rightmost entry, i.e. what the nearest proxy saw; junk -> null.
|
||||
function forwardedClientIp(value) {
|
||||
if (typeof value !== 'string') return null;
|
||||
const parts = value.split(',');
|
||||
let nearest = null;
|
||||
for (let i = parts.length - 1; i >= 0; i--) {
|
||||
const ip = parseForwardedEntry(parts[i]);
|
||||
if (!ip) return nearest;
|
||||
if (!isPrivateIp(ip)) return ip;
|
||||
if (!nearest) nearest = ip;
|
||||
}
|
||||
return nearest;
|
||||
}
|
||||
|
||||
// The address used for logging and the per-IP socket cap.
|
||||
function clientIp(req, trustProxy) {
|
||||
const peer = peerIp(req);
|
||||
if (!isTrustedPeer(req, trustProxy)) return peer;
|
||||
return forwardedClientIp(req.headers['x-forwarded-for']) ||
|
||||
firstForwardedIp(req.headers['x-real-ip']) || peer;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Origin check
|
||||
// Scheme-less, lower-case "host[:port]" with the default ports 80 / 443 dropped.
|
||||
// Accepts a bare host ("Game.Example.com:443"), a Host header, or a full origin ("https://x.example").
|
||||
function normalizeHost(s) {
|
||||
if (typeof s !== 'string') return null;
|
||||
let v = s.trim();
|
||||
if (!v) return null;
|
||||
if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(v)) {
|
||||
if (!/^[a-z0-9._:\[\]-]+$/i.test(v)) return null; // a bare host[:port], nothing else
|
||||
v = 'http://' + v;
|
||||
}
|
||||
let u;
|
||||
try { u = new URL(v); } catch (e) { return null; }
|
||||
if (!u.hostname) return null;
|
||||
const port = u.port; // '' for the scheme's own default
|
||||
const h = u.hostname.toLowerCase(); // IPv6 keeps its brackets
|
||||
return port && port !== '80' && port !== '443' ? h + ':' + port : h;
|
||||
}
|
||||
|
||||
// Returns true when a WebSocket upgrade with this Origin may proceed.
|
||||
// no Origin header -> true (non-browser clients)
|
||||
// Origin host == Host -> true
|
||||
// Origin host == X-Forwarded-Host (first) -> true, only when the peer is a trusted proxy
|
||||
// Origin host in allowedOrigins -> true
|
||||
function originAllowed(req, opts) {
|
||||
const origin = req.headers.origin;
|
||||
if (origin === undefined) return true;
|
||||
const o = (typeof origin === 'string' && origin.toLowerCase() !== 'null' && /^[a-z][a-z0-9+.-]*:\/\//i.test(origin))
|
||||
? normalizeHost(origin) : null;
|
||||
if (!o) return false;
|
||||
if (o === normalizeHost(req.headers.host)) return true;
|
||||
if (isTrustedPeer(req, opts.trustProxy)) {
|
||||
const xfh = req.headers['x-forwarded-host'];
|
||||
if (typeof xfh === 'string' && o === normalizeHost(xfh.split(',')[0])) return true;
|
||||
}
|
||||
for (const a of opts.allowedOrigins || []) if (o === normalizeHost(a)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- token bucket
|
||||
class TokenBucket {
|
||||
constructor(ratePerSec, burst) {
|
||||
this.rate = ratePerSec; this.burst = burst;
|
||||
this.tokens = burst; this.last = performance.now();
|
||||
}
|
||||
// true when the event is allowed. `now` (ms) defaults to a monotonic clock: with Date.now() a wall-clock step
|
||||
// backwards (NTP, a VM resume) would stop the refill for as long as the step is large and get sockets closed 4429.
|
||||
take(now) {
|
||||
now = now === undefined ? performance.now() : now;
|
||||
const dt = now - this.last;
|
||||
if (dt > 0) { this.tokens = Math.min(this.burst, this.tokens + dt * this.rate / 1000); this.last = now; }
|
||||
if (this.tokens < 1) return false;
|
||||
this.tokens -= 1;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- listen
|
||||
const V6_FALLBACK_CODES = new Set(['EAFNOSUPPORT', 'EADDRNOTAVAIL', 'EPROTONOSUPPORT', 'ENOTSUP', 'EINVAL', 'ENOPROTOOPT', 'EPFNOSUPPORT']);
|
||||
|
||||
function listenOnce(server, opts) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const onError = (err) => { server.removeListener('listening', onListening); reject(err); };
|
||||
const onListening = () => { server.removeListener('error', onError); resolve(); };
|
||||
server.once('error', onError);
|
||||
server.once('listening', onListening);
|
||||
try { server.listen(opts); } catch (err) { onError(err); }
|
||||
});
|
||||
}
|
||||
|
||||
// Binds `host`. The default '::' is bound dual-stack (ipv6Only:false: one socket for IPv4 and IPv6);
|
||||
// if IPv6 is unavailable (EAFNOSUPPORT, EADDRNOTAVAIL, ...) it falls back to 0.0.0.0. Any other host is
|
||||
// used as given, and any other failure (EADDRINUSE, EACCES) is rejected, never papered over.
|
||||
// Resolves to the host that ended up bound.
|
||||
async function listenDual(server, port, host, log) {
|
||||
if (host !== '::') { await listenOnce(server, { port, host }); return host; }
|
||||
try {
|
||||
await listenOnce(server, { port, host: '::', ipv6Only: false });
|
||||
return '::';
|
||||
} catch (err) {
|
||||
if (!err || !V6_FALLBACK_CODES.has(err.code)) throw err;
|
||||
if (log) log('IPv6 is not available (' + err.code + '); falling back to 0.0.0.0 (IPv4 only)');
|
||||
await listenOnce(server, { port, host: '0.0.0.0' });
|
||||
return '0.0.0.0';
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- start-up banner
|
||||
function fmtUrl(host, port) {
|
||||
return 'http://' + (host.includes(':') ? '[' + host + ']' : host) + ':' + port + '/';
|
||||
}
|
||||
|
||||
// os.networkInterfaces() throws in some sandboxes (seccomp / RestrictAddressFamilies without AF_NETLINK, certain
|
||||
// containers). The banner is cosmetic, so that must never stop a server that is already listening.
|
||||
function interfaces() {
|
||||
try { return os.networkInterfaces(); } catch (e) { return {}; }
|
||||
}
|
||||
|
||||
// URLs worth printing for a server bound to `bound` on `port`.
|
||||
function listUrls(bound, port, ifaces) {
|
||||
const out = ['http://localhost:' + port + '/'];
|
||||
if (bound !== '::' && bound !== '0.0.0.0') {
|
||||
if (bound !== '127.0.0.1' && bound !== '::1') out.push(fmtUrl(bound, port));
|
||||
return out;
|
||||
}
|
||||
ifaces = ifaces || interfaces();
|
||||
for (const name of Object.keys(ifaces)) {
|
||||
for (const a of ifaces[name] || []) {
|
||||
if (a.internal) continue;
|
||||
const v4 = a.family === 'IPv4' || a.family === 4;
|
||||
if (v4) out.push(fmtUrl(a.address, port));
|
||||
else if (bound === '::' && !/^fe80:/i.test(a.address)) out.push(fmtUrl(a.address.split('%')[0], port));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
normalizeIp, isPrivateIp, parseTrustProxy, peerIp, isTrustedPeer, firstForwardedIp, forwardedClientIp, clientIp,
|
||||
normalizeHost, originAllowed, TokenBucket, listenDual, listUrls, fmtUrl,
|
||||
};
|
||||
411
server/room.js
Normal file
|
|
@ -0,0 +1,411 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Rooms: one authoritative Sim per room, two player slots, fixed-step tick loop and snapshot broadcast.
|
||||
* A "conn" is the per-socket context object created in index.js ({ ws, player, room, dead, ... }); this file
|
||||
* only touches conn.ws, conn.player and conn.room and never throws on a dead socket.
|
||||
*/
|
||||
const crypto = require('crypto');
|
||||
const TD = require('../public/js/sim.js'); // fixed path on purpose: independent of publicDir
|
||||
|
||||
const CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
|
||||
const CMDS = new Set(['place', 'sell', 'upgrade', 'target', 'wave', 'auto', 'continue']);
|
||||
const OPEN = 1; // WebSocket.OPEN
|
||||
const LOOP_MS = 8; // global tick loop period
|
||||
const MAX_CATCHUP_S = 0.25; // clamp one loop iteration (stalled event loop)
|
||||
const STEP_BUDGET_NS = 20000000n; // never spend more than 20 ms stepping one room per iteration
|
||||
const MARK_GAP_MS = 400;
|
||||
const MAX_BUFFERED = 512 * 1024; // a socket this far behind is dropped; it reconnects and resumes
|
||||
const MAX_MONSTER_LOAD = 1500; // monsters + queued spawns; refuse 'wave' beyond this (CPU/bandwidth guard)
|
||||
|
||||
const ALIAS_KEY = crypto.randomBytes(32); // per process; see Room.alias()
|
||||
const nowMs = () => Number(process.hrtime.bigint() / 1000000n);
|
||||
|
||||
const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
|
||||
const finite = (v) => typeof v === 'number' && Number.isFinite(v);
|
||||
const clamp = (v, lo, hi) => (v < lo ? lo : v > hi ? hi : v);
|
||||
const round2 = (v) => Math.round(v * 100) / 100;
|
||||
|
||||
function sendRaw(conn, str) {
|
||||
const ws = conn && conn.ws;
|
||||
if (!ws || ws.readyState !== OPEN) return false;
|
||||
try { ws.send(str); return true; } catch (e) { return false; }
|
||||
}
|
||||
|
||||
class Room {
|
||||
constructor(manager, code, mapId) {
|
||||
this.manager = manager;
|
||||
this.code = code;
|
||||
this.sim = new TD.Sim({ map: mapId });
|
||||
this.speed = 1;
|
||||
this.paused = false;
|
||||
this.seq = 0;
|
||||
this.players = [null, null]; // slot -> player
|
||||
this.acc = 0; // accumulated game seconds not yet stepped
|
||||
this.lastNs = null; // hrtime of the previous loop iteration
|
||||
this.nextSnapNs = 0n;
|
||||
this.lastSentRev = this.sim.rev; // 'tw' is attached only when rev moves past this
|
||||
this.destroyed = false;
|
||||
this.createdAt = Date.now();
|
||||
this.emptySince = null; // nowMs() when the last online player went away; null while somebody is online
|
||||
}
|
||||
|
||||
log(msg) { this.manager.log('[' + this.code + '] ' + msg); }
|
||||
|
||||
// ---------------------------------------------------------------- players
|
||||
onlinePlayers() { return this.players.filter((p) => p && p.conn); }
|
||||
anyPlayers() { return this.players.some(Boolean); }
|
||||
|
||||
// A pid is the reconnect secret (whoever presents it takes over the slot), so it only ever goes to its owner.
|
||||
// The other player appears under a stable alias: unguessable, different per room, useless as a pid.
|
||||
alias(pid) {
|
||||
return crypto.createHmac('sha256', ALIAS_KEY).update(this.code + ':' + pid).digest('base64url').slice(0, 22);
|
||||
}
|
||||
|
||||
// The player list as `viewer` may see it: their own entry carries their pid, everyone else's an alias.
|
||||
publicPlayers(viewer) {
|
||||
const out = [];
|
||||
for (const p of this.players) {
|
||||
if (p) out.push({ pid: p === viewer ? p.pid : p.alias, slot: p.slot, name: p.name, host: p.host, online: !!p.conn });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
send(player, obj) { return !!player && sendRaw(player.conn, JSON.stringify(obj)); }
|
||||
|
||||
// Same string to everyone online (optionally except one conn).
|
||||
broadcast(obj, exceptConn) {
|
||||
const str = JSON.stringify(obj);
|
||||
for (const p of this.players) if (p && p.conn && p.conn !== exceptConn) sendRaw(p.conn, str);
|
||||
}
|
||||
|
||||
// One message per recipient (each sees their own pid), to everyone online except `exceptConn`.
|
||||
broadcastPlayers(exceptConn) {
|
||||
for (const p of this.players) {
|
||||
if (p && p.conn && p.conn !== exceptConn) this.send(p, { t: 'players', players: this.publicPlayers(p) });
|
||||
}
|
||||
}
|
||||
|
||||
stateMsg(extra) {
|
||||
return Object.assign({ t: 'state', state: this.sim.fullState(), snap: this.sim.snapshot(), speed: this.speed, paused: this.paused }, extra);
|
||||
}
|
||||
|
||||
joinedMsg(player, resumed) {
|
||||
return {
|
||||
t: 'joined', room: this.code, resumed,
|
||||
you: { pid: player.pid, slot: player.slot, host: player.host },
|
||||
players: this.publicPlayers(player),
|
||||
state: this.sim.fullState(), snap: this.sim.snapshot(), speed: this.speed, paused: this.paused,
|
||||
};
|
||||
}
|
||||
|
||||
// Binds `conn` to a slot. Returns { player, resumed } or null when both slots belong to other pids.
|
||||
join(pid, name, conn) {
|
||||
let p = this.players.find((x) => x && x.pid === pid);
|
||||
let resumed = false;
|
||||
if (p) {
|
||||
resumed = true;
|
||||
if (p.graceTimer) { clearTimeout(p.graceTimer); p.graceTimer = null; }
|
||||
const old = p.conn;
|
||||
p.conn = conn;
|
||||
p.name = name;
|
||||
if (old && old !== conn) { // a second tab / a reconnect racing the dead socket
|
||||
old.player = null; old.room = null; old.dead = true;
|
||||
try { old.ws.close(4001, 'replaced by a newer connection'); } catch (e) { /* already closing */ }
|
||||
}
|
||||
} else {
|
||||
const slot = this.players.indexOf(null);
|
||||
if (slot < 0) return null;
|
||||
p = {
|
||||
pid, alias: this.alias(pid), slot, name, host: !this.players.some((x) => x && x.host),
|
||||
conn, cursor: null, lastMarkAt: -Infinity, graceTimer: null,
|
||||
};
|
||||
this.players[slot] = p;
|
||||
}
|
||||
p.cursor = null;
|
||||
this.touchPresence();
|
||||
return { player: p, resumed };
|
||||
}
|
||||
|
||||
// Keeps `emptySince` in step with who is online (the manager evicts the longest-abandoned room first).
|
||||
touchPresence() {
|
||||
if (this.onlinePlayers().length) this.emptySince = null;
|
||||
else if (this.emptySince === null) this.emptySince = nowMs();
|
||||
}
|
||||
|
||||
// The socket of `conn` closed (not a deliberate leave): keep the slot for graceMs.
|
||||
disconnect(conn) {
|
||||
const p = conn.player;
|
||||
if (this.destroyed || !p || p.conn !== conn) return;
|
||||
p.conn = null;
|
||||
p.cursor = null;
|
||||
this.touchPresence();
|
||||
this.log(p.name + ' (slot ' + p.slot + ') disconnected; holding the slot for ' + this.manager.graceMs + ' ms');
|
||||
p.graceTimer = setTimeout(() => { p.graceTimer = null; this.removePlayer(p, 'grace expired'); }, this.manager.graceMs);
|
||||
this.broadcastPlayers();
|
||||
}
|
||||
|
||||
// Frees the slot for good, migrates the host, deletes the room when nobody is left.
|
||||
removePlayer(p, why) {
|
||||
if (this.destroyed || this.players[p.slot] !== p) return;
|
||||
if (p.graceTimer) { clearTimeout(p.graceTimer); p.graceTimer = null; }
|
||||
this.players[p.slot] = null;
|
||||
p.conn = null;
|
||||
p.cursor = null;
|
||||
this.log(p.name + ' (slot ' + p.slot + ') removed: ' + why);
|
||||
if (!this.anyPlayers()) { this.manager.deleteRoom(this, 'empty'); return; }
|
||||
if (p.host) {
|
||||
const next = this.players.find(Boolean);
|
||||
next.host = true;
|
||||
this.log('host is now ' + next.name + ' (slot ' + next.slot + ')');
|
||||
}
|
||||
this.touchPresence();
|
||||
this.broadcastPlayers();
|
||||
}
|
||||
|
||||
leave(conn) {
|
||||
const p = conn.player;
|
||||
if (!p || p.conn !== conn) return;
|
||||
conn.player = null; conn.room = null;
|
||||
this.removePlayer(p, 'left');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- messages after join
|
||||
// Returns false when the message is malformed (the caller counts those).
|
||||
handleMessage(p, msg) {
|
||||
switch (msg.t) {
|
||||
case 'cmd': return this.handleCmd(p, msg);
|
||||
case 'ctl': return this.handleCtl(msg);
|
||||
case 'cursor': return this.handleCursor(p, msg);
|
||||
case 'mark': return this.handleMark(p, msg);
|
||||
case 'rtt':
|
||||
if (!finite(msg.ts) && !(typeof msg.ts === 'string' && msg.ts.length <= 32)) return false;
|
||||
this.send(p, { t: 'rtt', ts: msg.ts });
|
||||
return true;
|
||||
case 'sync': this.send(p, this.stateMsg()); return true;
|
||||
case 'newgame': return this.handleNewgame(p, msg);
|
||||
default: return false;
|
||||
}
|
||||
}
|
||||
|
||||
reject(p, c, reason, msg) {
|
||||
const out = { t: 'reject', c, reason };
|
||||
if (msg) {
|
||||
if (finite(msg.x)) out.x = msg.x;
|
||||
if (finite(msg.y)) out.y = msg.y;
|
||||
if (finite(msg.id)) out.id = msg.id;
|
||||
}
|
||||
this.send(p, out);
|
||||
}
|
||||
|
||||
handleCmd(p, msg) {
|
||||
const c = msg.c;
|
||||
if (typeof c !== 'string' || !CMDS.has(c)) return false;
|
||||
const sim = this.sim;
|
||||
if (c === 'wave' && sim.monsters.length + sim.spawnQ.length > MAX_MONSTER_LOAD) {
|
||||
this.reject(p, c, 'busy', msg);
|
||||
return true;
|
||||
}
|
||||
// Whitelisted fields only; `by` always comes from the socket's slot, never from the client.
|
||||
const cmd = { c, type: msg.type, x: msg.x, y: msg.y, id: msg.id, mode: msg.mode, v: msg.v, by: p.slot };
|
||||
let r;
|
||||
try { r = sim.cmd(cmd); } catch (e) { this.log('sim.cmd threw: ' + (e && e.stack || e)); r = { ok: false, reason: 'error' }; }
|
||||
if (!r || !r.ok) this.reject(p, c, (r && r.reason) || 'error', msg);
|
||||
return true;
|
||||
}
|
||||
|
||||
handleCtl(msg) {
|
||||
if (msg.c === 'pause' && typeof msg.v === 'boolean') { this.paused = msg.v; return true; }
|
||||
if (msg.c === 'speed' && (msg.v === 1 || msg.v === 2 || msg.v === 3)) { this.speed = msg.v; return true; }
|
||||
return false;
|
||||
}
|
||||
|
||||
boardPoint(msg) {
|
||||
const b = this.sim.board;
|
||||
return [round2(clamp(msg.x, 0, b.cols)), round2(clamp(msg.y, 0, b.rows))];
|
||||
}
|
||||
|
||||
handleCursor(p, msg) {
|
||||
if (msg.x === null) { p.cursor = null; return true; }
|
||||
if (!finite(msg.x) || !finite(msg.y)) return false;
|
||||
p.cursor = this.boardPoint(msg);
|
||||
return true;
|
||||
}
|
||||
|
||||
handleMark(p, msg) {
|
||||
if (!finite(msg.x) || !finite(msg.y)) return false;
|
||||
const now = nowMs(); // monotonic: immune to wall-clock steps
|
||||
if (now - p.lastMarkAt < MARK_GAP_MS) return true; // rate limited: dropped silently
|
||||
p.lastMarkAt = now;
|
||||
const pt = this.boardPoint(msg);
|
||||
this.broadcast({ t: 'mark', slot: p.slot, x: pt[0], y: pt[1] });
|
||||
return true;
|
||||
}
|
||||
|
||||
handleNewgame(p, msg) {
|
||||
if (!p.host) { this.reject(p, 'newgame', 'not_host'); return true; }
|
||||
const map = msg.map === undefined || msg.map === null ? this.sim.mapId : msg.map;
|
||||
if (typeof map !== 'string' || !hasOwn(TD.MAPS, map)) { this.reject(p, 'newgame', 'bad_map'); return true; }
|
||||
this.sim = new TD.Sim({ map });
|
||||
this.speed = 1; this.paused = false; this.acc = 0;
|
||||
this.lastSentRev = this.sim.rev; // the 'state' below carries the tower list
|
||||
this.log('new game on map ' + map + ' started by ' + p.name);
|
||||
this.broadcast(this.stateMsg({ newgame: true }));
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- loop
|
||||
// Called every LOOP_MS by the manager with process.hrtime.bigint().
|
||||
step(now) {
|
||||
const last = this.lastNs;
|
||||
this.lastNs = now;
|
||||
const online = this.onlinePlayers().length > 0;
|
||||
const sim = this.sim;
|
||||
|
||||
if (!online || this.paused || sim.state !== 'playing' || last === null) {
|
||||
this.acc = 0; // no catch-up after a pause / an empty room
|
||||
} else {
|
||||
let dt = Number(now - last) / 1e9;
|
||||
if (dt > MAX_CATCHUP_S) dt = MAX_CATCHUP_S;
|
||||
this.acc += dt * this.speed;
|
||||
let n = 0;
|
||||
const t0 = process.hrtime.bigint();
|
||||
while (this.acc >= TD.STEP) {
|
||||
sim.tick(TD.STEP);
|
||||
this.acc -= TD.STEP;
|
||||
if ((++n & 7) === 0 && process.hrtime.bigint() - t0 > STEP_BUDGET_NS) { // overloaded: run slower, do not freeze the server
|
||||
this.acc = Math.min(this.acc, TD.STEP);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!online) { this.nextSnapNs = now; return; }
|
||||
if (now >= this.nextSnapNs) {
|
||||
this.broadcastSnap();
|
||||
this.nextSnapNs += this.manager.snapPeriodNs;
|
||||
if (this.nextSnapNs <= now) this.nextSnapNs = now + this.manager.snapPeriodNs;
|
||||
}
|
||||
}
|
||||
|
||||
// Serialised once, the same string goes to every online player.
|
||||
broadcastSnap() {
|
||||
const sim = this.sim;
|
||||
const cur = [];
|
||||
for (const p of this.players) if (p && p.conn && p.cursor) cur.push([p.slot, p.cursor[0], p.cursor[1]]);
|
||||
const msg = Object.assign({ t: 'snap', seq: ++this.seq }, sim.snapshot(), {
|
||||
ev: sim.drainEvents(), cur, pa: this.paused ? 1 : 0, sp: this.speed,
|
||||
});
|
||||
if (sim.rev !== this.lastSentRev) { msg.tw = sim.towerList(); this.lastSentRev = sim.rev; }
|
||||
const str = JSON.stringify(msg);
|
||||
for (const p of this.players) {
|
||||
if (!p || !p.conn) continue;
|
||||
const ws = p.conn.ws;
|
||||
if (ws.bufferedAmount > MAX_BUFFERED) { // hopelessly behind: dropping a snap could lose 'tw'/'ev'
|
||||
this.log(p.name + ' is too slow (' + ws.bufferedAmount + ' bytes queued); dropping the connection');
|
||||
try { ws.terminate(); } catch (e) { /* gone */ }
|
||||
continue;
|
||||
}
|
||||
sendRaw(p.conn, str);
|
||||
}
|
||||
}
|
||||
|
||||
// Something threw inside the loop: tell everyone and drop the room rather than the whole process.
|
||||
crash(err) {
|
||||
this.log('room crashed: ' + (err && err.stack || err));
|
||||
for (const p of this.players) {
|
||||
if (!p || !p.conn) continue;
|
||||
sendRaw(p.conn, JSON.stringify({ t: 'error', code: 'server_error', msg: 'internal error' }));
|
||||
try { p.conn.ws.close(1011, 'internal error'); } catch (e) { /* gone */ }
|
||||
}
|
||||
this.manager.deleteRoom(this, 'crashed');
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this.destroyed = true;
|
||||
for (const p of this.players) {
|
||||
if (p && p.graceTimer) { clearTimeout(p.graceTimer); p.graceTimer = null; }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class RoomManager {
|
||||
constructor(opts) {
|
||||
this.rooms = new Map();
|
||||
this.maxRooms = opts.maxRooms;
|
||||
this.graceMs = opts.graceMs;
|
||||
this.snapPeriodNs = BigInt(Math.max(1, Math.round(1e9 / opts.snapshotHz)));
|
||||
this.log = opts.log;
|
||||
this.timer = null;
|
||||
this.closed = false;
|
||||
}
|
||||
|
||||
newCode() {
|
||||
for (let tries = 0; tries < 200; tries++) {
|
||||
let c = '';
|
||||
for (let i = 0; i < 4; i++) c += CODE_ALPHABET[crypto.randomInt(CODE_ALPHABET.length)];
|
||||
if (!this.rooms.has(c)) return c;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
get(code) { return this.rooms.get(code); }
|
||||
|
||||
// The room nobody has been online in for the longest time, or null.
|
||||
abandonedRoom() {
|
||||
let oldest = null;
|
||||
for (const r of this.rooms.values()) if (r.emptySince !== null && (oldest === null || r.emptySince < oldest.emptySince)) oldest = r;
|
||||
return oldest;
|
||||
}
|
||||
|
||||
// null when the room limit is reached. A full table first drops a room that nobody is online in (it is only
|
||||
// being held for its grace period): otherwise one client could fill all slots for a minute at a time by
|
||||
// creating rooms and closing the sockets, which costs nothing and is not limited by any per-IP socket cap.
|
||||
create(mapId) {
|
||||
if (this.closed) return null;
|
||||
if (this.rooms.size >= this.maxRooms) {
|
||||
const victim = this.abandonedRoom();
|
||||
if (!victim) return null;
|
||||
this.deleteRoom(victim, 'evicted: the server is full and nobody is online in it');
|
||||
}
|
||||
const code = this.newCode();
|
||||
if (!code) return null;
|
||||
const room = new Room(this, code, mapId);
|
||||
this.rooms.set(code, room);
|
||||
room.log('created (map ' + mapId + '); ' + this.rooms.size + ' room(s)');
|
||||
this.startLoop();
|
||||
return room;
|
||||
}
|
||||
|
||||
deleteRoom(room, why) {
|
||||
if (this.rooms.get(room.code) !== room) return;
|
||||
room.destroy();
|
||||
this.rooms.delete(room.code);
|
||||
room.log('deleted (' + why + '); ' + this.rooms.size + ' room(s) left');
|
||||
if (!this.rooms.size) this.stopLoop();
|
||||
}
|
||||
|
||||
startLoop() {
|
||||
if (this.timer || this.closed) return;
|
||||
this.timer = setInterval(() => this.tick(), LOOP_MS);
|
||||
}
|
||||
|
||||
stopLoop() {
|
||||
if (this.timer) { clearInterval(this.timer); this.timer = null; }
|
||||
}
|
||||
|
||||
tick() {
|
||||
const now = process.hrtime.bigint();
|
||||
for (const room of Array.from(this.rooms.values())) {
|
||||
try { room.step(now); } catch (err) { room.crash(err); }
|
||||
}
|
||||
}
|
||||
|
||||
close() {
|
||||
this.closed = true;
|
||||
this.stopLoop();
|
||||
for (const room of Array.from(this.rooms.values())) room.destroy();
|
||||
this.rooms.clear();
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { Room, RoomManager, CODE_ALPHABET, CMDS, MAX_MONSTER_LOAD, MAX_BUFFERED };
|
||||
181
server/static.js
Normal file
|
|
@ -0,0 +1,181 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Minimal, safe static file server for public/.
|
||||
* - GET / HEAD only (405 otherwise), never serves anything outside the root (also not via symlinks)
|
||||
* - rejects "..", %2e%2e, %2f, %5c, backslashes, NUL and control characters (400), dotfiles (404)
|
||||
* - ETag / If-None-Match / Last-Modified (304) with Cache-Control: no-cache
|
||||
* - single-range requests (206): iOS Safari will not play <audio>/<video> without them
|
||||
*/
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { pipeline } = require('stream');
|
||||
|
||||
const MIME = {
|
||||
'.html': 'text/html; charset=utf-8',
|
||||
'.htm': 'text/html; charset=utf-8',
|
||||
'.js': 'text/javascript; charset=utf-8',
|
||||
'.mjs': 'text/javascript; charset=utf-8',
|
||||
'.css': 'text/css; charset=utf-8',
|
||||
'.json': 'application/json; charset=utf-8',
|
||||
'.webmanifest': 'application/manifest+json; charset=utf-8',
|
||||
'.svg': 'image/svg+xml',
|
||||
'.png': 'image/png',
|
||||
'.jpg': 'image/jpeg',
|
||||
'.jpeg': 'image/jpeg',
|
||||
'.gif': 'image/gif',
|
||||
'.webp': 'image/webp',
|
||||
'.ico': 'image/x-icon',
|
||||
'.woff2': 'font/woff2',
|
||||
'.woff': 'font/woff',
|
||||
'.mp3': 'audio/mpeg',
|
||||
'.ogg': 'audio/ogg',
|
||||
'.wav': 'audio/wav',
|
||||
'.txt': 'text/plain; charset=utf-8',
|
||||
};
|
||||
|
||||
const CSP = "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'";
|
||||
|
||||
// Headers every response carries (static files, /healthz, errors).
|
||||
function applySecurityHeaders(res) {
|
||||
res.setHeader('X-Content-Type-Options', 'nosniff');
|
||||
res.setHeader('Referrer-Policy', 'no-referrer');
|
||||
res.setHeader('Content-Security-Policy', CSP);
|
||||
}
|
||||
|
||||
function sendText(req, res, status, text, extra) {
|
||||
const body = Buffer.from(text, 'utf8');
|
||||
res.writeHead(status, Object.assign({
|
||||
'Content-Type': 'text/plain; charset=utf-8',
|
||||
'Content-Length': body.length,
|
||||
'Cache-Control': 'no-cache',
|
||||
}, extra));
|
||||
res.end(req.method === 'HEAD' ? undefined : body);
|
||||
}
|
||||
|
||||
// Turns a raw request target into path segments, or an HTTP status to answer with.
|
||||
function parseTarget(rawUrl) {
|
||||
if (typeof rawUrl !== 'string' || rawUrl[0] !== '/') return { status: 400 };
|
||||
const cut = rawUrl.search(/[?#]/);
|
||||
const raw = cut < 0 ? rawUrl : rawUrl.slice(0, cut);
|
||||
if (/%(2f|5c)/i.test(raw) || raw.includes('\\')) return { status: 400 };
|
||||
let dec;
|
||||
try { dec = decodeURIComponent(raw); } catch (e) { return { status: 400 }; }
|
||||
if (/[\x00-\x1f\x7f\\]/.test(dec)) return { status: 400 };
|
||||
const segs = dec.split('/').filter((s) => s !== ''); // '//' collapses
|
||||
for (const s of segs) {
|
||||
if (s === '.' || s === '..') return { status: 400 };
|
||||
if (s[0] === '.') return { status: 404 }; // dotfiles and dot-directories
|
||||
}
|
||||
return { segs, trailingSlash: dec.endsWith('/') };
|
||||
}
|
||||
|
||||
function etagOf(st) { return 'W/"' + st.size.toString(16) + '-' + Math.floor(st.mtimeMs).toString(16) + '"'; }
|
||||
|
||||
function etagMatches(header, etag) {
|
||||
if (!header) return false;
|
||||
if (header.trim() === '*') return true;
|
||||
const weak = (s) => s.trim().replace(/^W\//, '');
|
||||
const mine = weak(etag);
|
||||
return header.split(',').some((t) => weak(t) === mine);
|
||||
}
|
||||
|
||||
// Parses "bytes=a-b" for a file of `size` bytes.
|
||||
// -> null (ignore the header, serve everything) | 'unsatisfiable' | { start, end }
|
||||
function parseRange(header, size) {
|
||||
if (!header) return null;
|
||||
const m = /^bytes=(\d*)-(\d*)$/.exec(header.trim()); // multiple ranges: ignore, serve all
|
||||
if (!m || (m[1] === '' && m[2] === '')) return null;
|
||||
let start, end;
|
||||
if (m[1] === '') { // suffix: last N bytes
|
||||
const n = parseInt(m[2], 10);
|
||||
if (n === 0) return 'unsatisfiable';
|
||||
start = Math.max(0, size - n); end = size - 1;
|
||||
} else {
|
||||
start = parseInt(m[1], 10);
|
||||
end = m[2] === '' ? size - 1 : Math.min(parseInt(m[2], 10), size - 1);
|
||||
if (m[2] !== '' && parseInt(m[2], 10) < start) return null; // malformed spec: ignore
|
||||
}
|
||||
if (start >= size) return 'unsatisfiable';
|
||||
return { start, end };
|
||||
}
|
||||
|
||||
function createStaticHandler(publicDir) {
|
||||
const root = path.resolve(publicDir);
|
||||
|
||||
async function resolveFile(segs, trailingSlash) {
|
||||
let file = path.join(root, ...segs);
|
||||
if (file !== root && !file.startsWith(root + path.sep)) return { status: 404 };
|
||||
let st;
|
||||
try { st = await fs.promises.stat(file); } catch (e) { return { status: 404 }; }
|
||||
if (st.isDirectory()) {
|
||||
if (!trailingSlash && segs.length) return { redirect: encodeURIComponent(segs[segs.length - 1]) + '/' };
|
||||
file = path.join(file, 'index.html');
|
||||
try { st = await fs.promises.stat(file); } catch (e) { return { status: 404 }; }
|
||||
}
|
||||
if (!st.isFile()) return { status: 404 };
|
||||
let real, realRoot;
|
||||
try {
|
||||
real = await fs.promises.realpath(file);
|
||||
realRoot = await fs.promises.realpath(root);
|
||||
} catch (e) { return { status: 404 }; }
|
||||
if (real !== realRoot && !real.startsWith(realRoot + path.sep)) return { status: 404 }; // symlink escape
|
||||
return { file: real, st };
|
||||
}
|
||||
|
||||
return async function handle(req, res) {
|
||||
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
||||
return sendText(req, res, 405, 'Method Not Allowed', { Allow: 'GET, HEAD' });
|
||||
}
|
||||
const target = parseTarget(req.url);
|
||||
if (target.status) return sendText(req, res, target.status, target.status === 400 ? 'Bad Request' : 'Not Found');
|
||||
let r;
|
||||
try { r = await resolveFile(target.segs, target.trailingSlash); } catch (e) { r = { status: 404 }; }
|
||||
if (r.redirect) {
|
||||
// Relative on purpose: it keeps working when a proxy serves us under a path prefix.
|
||||
return sendText(req, res, 301, 'Moved Permanently', { Location: r.redirect });
|
||||
}
|
||||
if (r.status) return sendText(req, res, r.status, 'Not Found');
|
||||
|
||||
const { file, st } = r;
|
||||
const ext = path.extname(file).toLowerCase();
|
||||
const etag = etagOf(st);
|
||||
const lastModified = st.mtime.toUTCString();
|
||||
const base = {
|
||||
'Content-Type': MIME[ext] || 'application/octet-stream',
|
||||
'Cache-Control': 'no-cache',
|
||||
'ETag': etag,
|
||||
'Last-Modified': lastModified,
|
||||
'Accept-Ranges': 'bytes',
|
||||
};
|
||||
|
||||
const inm = req.headers['if-none-match'];
|
||||
const ims = req.headers['if-modified-since'];
|
||||
const fresh = inm ? etagMatches(inm, etag)
|
||||
: (ims && Math.floor(st.mtimeMs / 1000) <= Math.floor(Date.parse(ims) / 1000));
|
||||
if (fresh) {
|
||||
res.writeHead(304, { 'Cache-Control': base['Cache-Control'], 'ETag': etag, 'Last-Modified': lastModified });
|
||||
return res.end();
|
||||
}
|
||||
|
||||
let range = parseRange(req.headers.range, st.size);
|
||||
const ifRange = req.headers['if-range'];
|
||||
if (range && ifRange && ifRange.trim() !== etag && ifRange.trim() !== lastModified) range = null;
|
||||
if (range === 'unsatisfiable') {
|
||||
res.writeHead(416, { 'Content-Range': 'bytes */' + st.size, 'Content-Length': 0, 'Cache-Control': 'no-cache' });
|
||||
return res.end();
|
||||
}
|
||||
|
||||
let status = 200, start = 0, end = st.size - 1;
|
||||
if (range) {
|
||||
status = 206; start = range.start; end = range.end;
|
||||
base['Content-Range'] = 'bytes ' + start + '-' + end + '/' + st.size;
|
||||
}
|
||||
base['Content-Length'] = st.size === 0 ? 0 : end - start + 1;
|
||||
res.writeHead(status, base);
|
||||
if (req.method === 'HEAD' || st.size === 0) return res.end();
|
||||
pipeline(fs.createReadStream(file, { start, end }), res, () => { /* client went away: nothing to do */ });
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { createStaticHandler, applySecurityHeaders, parseTarget, parseRange, MIME, CSP };
|
||||