Multiplayer for self-hosted copies: sessions, server-side saves, a leaderboard

Off unless the page is built with MP_API set (MP_API=/api/mp npm run
build): a plain build has no door, no chip and makes no requests. The
session server is scripts/mp-server.js (npm run mp), plain node:http,
which can also serve the built site so one process sits behind the
reverse proxy; docs/MULTIPLAYER.md has the nginx and Caddy setups.

A session has a six-character code, one seed and one rules preset, so
every player starts in the same world, and up to twelve players with
their own AS numbers. Saves go to the server on a new game day at most
every 15 s and when the page hides, ordered by a sequence number (409 on
a stale push, and the player picks which one to keep). Tokens live in
localStorage, never in the save; the server keeps only their hash. A
#mp= link moves a network to another device. The session panel shows
the leaderboard, the feed and a short chat; each player's public card
(tier, POPs, links, exchanges, transit, peak, customers, score) carries
what in-game peering between players will need next.

Server limits: body sizes, one upload per player, uploads per address
and in total, sessions per hour, wrong-code lockout; addresses counted
per IPv6 /64, X-Forwarded-For only with --trust-proxy.
This commit is contained in:
jvanvik 2026-11-07 00:42:39 +01:00
parent 2b48a6ad65
commit 95aa9b6532
39 changed files with 2757 additions and 24 deletions

1
.gitignore vendored
View file

@ -1,3 +1,4 @@
node_modules/ node_modules/
_site/ _site/
.DS_Store .DS_Store
mp-data/

View file

@ -7,6 +7,7 @@ All notable changes to this project are documented here. The project follows
## [Unreleased] ## [Unreleased]
- Your intern can upgrade optical transport: a new standing order moves full, busy fiber to a bigger line system, or trades its smallest channels for bigger optics. Pick a line system, and every fiber on a smaller one is moved up to it. A line system swap takes the fiber down for a day, so the intern only does it where the traffic gets around it and no customer rides it, one a night. - Your intern can upgrade optical transport: a new standing order moves full, busy fiber to a bigger line system, or trades its smallest channels for bigger optics. Pick a line system, and every fiber on a smaller one is moved up to it. A line system swap takes the fiber down for a day, so the intern only does it where the traffic gets around it and no customer rides it, one a night.
- Copies of the game you host yourself can now have multiplayer: friends join your session with a six-character code and build their networks next to yours in the same world, with a leaderboard, a feed with chat, saves kept on your server and a link to carry a network to another device. It needs the small session server that comes with the source code, so the game at seriesoftub.es stays single-player.
- Your intern can standardize your routers on a model you choose: pick it in Keep routers ahead, and every POP on a smaller model is swapped to it, the busiest first, within the monthly budget. Every setting in the Standing orders sheet is now a list to pick from instead of a button to tap through. - Your intern can standardize your routers on a model you choose: pick it in Keep routers ahead, and every POP on a smaller model is swapped to it, the busiest first, within the monthly budget. Every setting in the Standing orders sheet is now a list to pick from instead of a button to tap through.
- Set a build standard for your whole network: routers, a second building and a generator at every POP, LAGs, exchange ports and PNIs, line systems, optics and wave sizes, all in one sheet. New POPs get the POP part the day they open, the sheet shows what is below the standard and what fixing it costs, one tap brings everything up, and the new "Keep to the build standard" order has your intern do it a few jobs a day with money to spare. Find it in the menu, the Standing orders sheet and every POP's router section. - Set a build standard for your whole network: routers, a second building and a generator at every POP, LAGs, exchange ports and PNIs, line systems, optics and wave sizes, all in one sheet. New POPs get the POP part the day they open, the sheet shows what is below the standard and what fixing it costs, one tap brings everything up, and the new "Keep to the build standard" order has your intern do it a few jobs a day with money to spare. Find it in the menu, the Standing orders sheet and every POP's router section.

211
docs/MULTIPLAYER.md Normal file
View file

@ -0,0 +1,211 @@
# Multiplayer (self-hosted copies)
The game at [seriesoftub.es](https://seriesoftub.es) is hosted on GitHub Pages and nowhere else
([ADR 0001](adr/0001-github-pages-only.md)), so it has no server and no multiplayer. This page is for a copy you host
yourself: there, a small session server that ships with the source (`scripts/mp-server.js`) lets players build their
networks side by side.
A plain `npm run build` is unchanged: the page has no multiplayer door, no chip and makes no request for it. Multiplayer
is switched on only when the build is told where the session server lives.
## What it does (phase 1)
- **Sessions by code.** One player starts a session from the title screen (Multiplayer: their network's name, home city
and rules preset, optionally a session name) and gets a six-character code such as `K7Q-2XD`. Friends join with that
code. Codes use Crockford's base32 (no I, L, O or U); they are case-insensitive, and the dash is optional.
- **One world.** Everyone in a session plays a Normal game with the creator's rules preset (Best Effort, Change Freeze,
On-call or BGP at 3 a.m.) and the session's random seed, so day 0 is the same world for all. The session hands each
player an AS number from 200000–214999 that nobody else in the session and no network on the map uses. Each network
is still simulated in its own player's browser; from the first different click on, the worlds drift apart.
- **Saves on the server.** Each network's save goes to the server on a new game day, at most every 15 seconds (gzipped
when it is big), and when the page is hidden or closed if anything changed since the last push (a paused game's
building too). Opening the network on any device fetches the server's save first and loads it if another device
played on.
- **Seeing each other.** Every push carries a small public *card*: day, tier, POPs, links between them (with capacity),
exchanges, transit providers, peering policy, reach, peak and served traffic, customers, revenue per month, cash as an
order of magnitude, and a score. The session panel (the 🌐 chip in the top bar, or the menu) shows the leaderboard
(Tier 1 first, then Tier 2, then traffic served), a feed (joins, leaves, Tier 2, Tier 1 and who got there first) and a
chat. While the panel is open it refreshes every 5 seconds; otherwise the roster rides along with each push.
- **Moving to another device.** The panel's "Move to another device" holds a link `https://your.host/#mp=CODE.pid.token`.
The part after `#` never reaches any server. Opening it (or copying the link) first sends this device's latest save,
and opening the link loads the network into that browser. Treat it like a password: anyone with it can play as you.
A browser keeps the link's token only once the server has accepted it, so a wrong or mistyped link never replaces the
one it already has; when the server cannot be reached, the link stays in the address bar for a reload to try again.
- **Offline.** The game never waits for the server. When it cannot be reached, the game says so once, keeps playing and
tries again later (30 s, then 1, 2, 4, at most 5 minutes apart; the open session panel keeps looking every 5 seconds
without stretching that wait).
Not yet (phase 2): peering, transit and competition between players inside the simulation. The card already carries
what that will need (POPs, links, exchanges, transit, peering policy, reach).
## Build
```bash
MP_API=/api/mp npm run build # _site/ with multiplayer on; the page talks to /api/mp on its own origin
```
`MP_API` must be a path on the same origin (letters, digits, `/`, `_`, `-`; no trailing slash, and not starting with
`//`, which a browser reads as another host). Anything else fails the build. Without it, or empty, the build is the
plain one.
## Run the server
```bash
node scripts/mp-server.js --site _site --data /var/lib/tubes-mp --port 8090
# or: npm run mp -- --site _site --data /var/lib/tubes-mp
```
One process serves the API under `/api/mp` and, with `--site`, the built game too (like GitHub Pages would: `/` is
`index.html`, a missing file gets `404.html`, nothing outside the folder is ever served). It binds `127.0.0.1` by default:
put a reverse proxy with HTTPS in front. Plain `node:http`, no dependencies beyond Node 20 or newer.
| Option | Default | |
|---|---|---|
| `--port N` | 8090 (or `$PORT`) | port to listen on |
| `--host H` | 127.0.0.1 | address to bind |
| `--data DIR` | `./mp-data` | sessions and saves; created if missing |
| `--site DIR` | none | also serve the built game from DIR |
| `--base PATH` | `/api/mp` | the API's path; must match `MP_API` |
| `--prune-days N` | 60 | sessions nobody touched for N days are deleted, at startup and daily |
| `--max-sessions N` | 1000 | sessions on this server |
| `--max-players N` | 12 | players per session (at most 12) |
| `--create-per-hour N` | 10 | new sessions one address may start per hour |
| `--sessions-per-hour N` | 100 | new sessions per hour on the whole server, from all addresses together |
| `--trust-proxy` | off | take the client's address from `X-Forwarded-For` (only behind your own proxy) |
| `--verbose` | off | one log line per API request (never tokens) |
Behind a reverse proxy every request comes from the proxy's address, so the per-address limits only mean something with
`--trust-proxy` (the server then uses the last address in `X-Forwarded-For`, the one your proxy added); without it, all
players share one address's limits, such as 4 save uploads at once. An IPv6 address counts as its /64, since one phone
or home usually has a whole /64 to itself.
To try it locally without a build: `npm run dev -- --mp` runs the API inside the dev server (sessions in `mp-data/`) and
turns multiplayer on in the dev page. Open a second window (a private one counts as another browser) to be the second
player.
### nginx
```nginx
server {
listen 443 ssl http2;
server_name tubes.example.org;
ssl_certificate /etc/letsencrypt/live/tubes.example.org/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/tubes.example.org/privkey.pem;
client_max_body_size 5m; # a save is at most 4 MB
location / {
proxy_pass http://127.0.0.1:8090; # the game and /api/mp, from the one process
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
```
Run the server with `--site /srv/tubes/_site --data /var/lib/tubes-mp --trust-proxy`.
### Caddy
```caddy
tubes.example.org {
request_body {
max_size 5MB
}
reverse_proxy 127.0.0.1:8090
}
```
Caddy sets `X-Forwarded-For` itself and gets the certificate on its own; run the server with `--trust-proxy` as above.
### systemd
```ini
[Unit]
Description=Series of Tubes multiplayer
After=network.target
[Service]
ExecStart=/usr/bin/node /srv/tubes/scripts/mp-server.js --site /srv/tubes/_site --data /var/lib/tubes-mp --trust-proxy
User=tubes
Restart=on-failure
StateDirectory=tubes-mp
[Install]
WantedBy=multi-user.target
```
## Backups
Everything is in the data folder: `<CODE>.json` per session (settings, players, cards, feed, and each save's number) and
`<CODE>.<pid>.save` per player's save (its text exactly as the game sent it). Every write goes to a temporary file that is then renamed over the old one, so a
copy of the folder (`rsync`, a snapshot, `tar`) taken while the server runs holds whole files. Restore by stopping the
server, putting the files back and starting it again. A player's token is stored only as its SHA-256, so a backup cannot
be used to play as anyone.
## Limits
- 12 players per session, 1000 sessions per server (configurable).
- A save is at most 4 MB of text (the game gzips anything over 32 kB: the big test network, 236 kB of JSON, goes as about 50 kB). Other
requests are at most 16 kB.
- Chat lines: at most 200 characters, one a second and six per 30 seconds per player. The feed keeps the last 100 lines.
- Per address and hour (an IPv6 address counts as its /64): 10 new sessions, 60 joins, 120 wrong codes (after that,
every code is refused for a while from there, so guessing codes gets nowhere; a player who sends their own session's
code with its token is never refused for it). At most 100 new sessions an hour on the whole server.
- Saves and cards: one save upload at a time per player (another one meanwhile gets 429), at most 4 at once from one
address and 16 on the whole server (503 with `busy: true` beyond that; the game then tries again a little later,
quietly), and per player at most 20 saves and 60 cards a minute (the game sends one every 15 seconds at most). A
save's body must arrive within two minutes. A card alone is written to disk within two seconds, together with any
others that came in meanwhile.
- Network names: at most 32 characters; control characters, `<`, `>`, `&`, quotes and backticks are removed. The page
escapes everything other players wrote anyway.
- A page that is being hidden or closed can only send 64 KiB (the browser's limit for such requests, counted in bytes),
so a network whose save does not fit sends its card alone then; its save goes with the next push from that device.
## How saves stay in order
Each network in a session carries a save number (`S.mp.seq`). When a save is due to go to the server, the game picks
the next number before it writes the save, so the save kept in the browser and the one sent carry the same number;
reopening the network then finds nothing newer on the server unless another device pushed one. The server refuses a
number that is not newer than its own (HTTP 409, with its number), and only counts a save once it is on disk. Then the
player is told once that the network moved on elsewhere and chooses: load the newer save from the server (only one at
least as new as the server said it had: never an older one), or keep this one (at the end of the current game day it
goes with `force` and a number past the server's).
The token is never part of the save: it lives in the browser's storage under `sot-mp:<code>:<pid>`. An exported or
imported save keeps its session but cannot talk to the server without the token (the game says it is no longer in its
session and plays on alone).
## API
JSON in and out, same origin, no cookies, no CORS headers. Every call but starting and joining needs
`Authorization: Bearer <pid>.<token>`. Errors are `{"error": "…"}` with a fitting status (400, 401, 404, 405, 409, 413,
415, 429, 503).
| Call | Body | Answer |
|---|---|---|
| `POST /api/mp/sessions` | `{net:{name,home}, preset, title?, avoid?}` | `201 {code, pid, token, seed, asn, preset, color, title}` |
| `POST /api/mp/sessions/:code/join` | `{net:{name,home}, avoid?}` | the same, for the joiner (`409 {full:true}` when full) |
| `GET /api/mp/sessions/:code` | | `{code, title, preset, seed, created, players:[{pid, name, asn, color, card, seen, joined}], feed}` |
| `PUT /api/mp/sessions/:code/card` | `{card}` | the roster |
| `PUT /api/mp/sessions/:code/save` | `{seq, at, data, card?, force?}` | `{ok, seq, at, roster}`, or `409 {seq, at}`; `429` while another one is on its way, `503` when the server is busy |
| `GET /api/mp/sessions/:code/save` | | `{seq, at, data}` (your own save only) |
| `POST /api/mp/sessions/:code/feed` | `{text}` | the roster |
| `DELETE /api/mp/sessions/:code/me` | | `{ok}`; the session goes when its last player leaves |
`avoid` lists AS numbers the server must not hand out (the game sends the map's own networks in that range). `preset` is
one of `soft`, `freeze`, `oncall`, `bgp`. `data` is the save as the game writes it: JSON text, or `gz:` and base64.
The card, as the server keeps it (unknown fields are dropped, numbers clamped, ids checked for shape; the page checks
the ids against its own catalogs again): `day`, `tier` (`t1`, `t2`, `t3`), `t1`, `lvl`, `pops` (city ids), `links`
(`[a, b, Gbps]`, up to 300), `ix`, `transit` (network ids), `ppol` (`open`, `selective`, `closed`), `reach` (0–1),
`peak`, `served` (Gbps), `cust`, `rev` (per month), `cashB` (−1 in debt, else the power of ten of the cash), `score`.
Cards are what each player's browser says: nothing on the server checks that a network really is that big.
## Code
- Server: `scripts/lib/mp.js` (the API and storage), `scripts/mp-server.js` (the command line and the static site).
- Game: `src/game/60-features/89-multiplayer.js` (state, sync, the card, the `#mp=` link),
`src/game/95-modals/48-multiplayer.js` (door, sheets, panel, chip), `src/game/90-actions/92-multiplayer.js`
(actions), `src/styles/41-multiplayer.css`. The build stamps `MP_API` into `src/game/00-core/20-analytics.js`.
- Tests: `tests/mp-server.test.js`, `tests/multiplayer.test.js`.

View file

@ -21,7 +21,8 @@
"perf": "node scripts/perf-bench.js", "perf": "node scripts/perf-bench.js",
"bench:gpu": "node scripts/gpu-bench.js", "bench:gpu": "node scripts/gpu-bench.js",
"mcp": "node scripts/mcp.js", "mcp": "node scripts/mcp.js",
"mcp:browser": "node scripts/mcp.js --browser" "mcp:browser": "node scripts/mcp.js --browser",
"mp": "node scripts/mp-server.js"
}, },
"engines": { "engines": {
"node": ">=20" "node": ">=20"

View file

@ -6,6 +6,8 @@
// //
// npm run build VERSION, BUILD_DATE and OUT can be set in the environment // npm run build VERSION, BUILD_DATE and OUT can be set in the environment
// REQUIRE_NOTES=1 npm run build fail when CHANGELOG.md has no bullets for this version // REQUIRE_NOTES=1 npm run build fail when CHANGELOG.md has no bullets for this version
// MP_API=/api/mp npm run build a self-hosted copy with multiplayer (docs/MULTIPLAYER.md): the
// page talks to scripts/mp-server.js at that path, same origin
const fs = require('node:fs'); const fs = require('node:fs');
const path = require('node:path'); const path = require('node:path');
const { execFileSync } = require('node:child_process'); const { execFileSync } = require('node:child_process');
@ -19,6 +21,10 @@ const die = (msg) => { console.error(`error: ${msg}`); process.exit(1); };
if (!/^[0-9]+\.[0-9]+\.[0-9]+([-.+][0-9A-Za-z.-]+)?$/.test(VERSION)) die(`VERSION '${VERSION}' is not a semantic version`); if (!/^[0-9]+\.[0-9]+\.[0-9]+([-.+][0-9A-Za-z.-]+)?$/.test(VERSION)) die(`VERSION '${VERSION}' is not a semantic version`);
if (!/^\d{4}-\d{2}-\d{2}$/.test(BUILD_DATE)) die(`BUILD_DATE '${BUILD_DATE}' is not YYYY-MM-DD`); if (!/^\d{4}-\d{2}-\d{2}$/.test(BUILD_DATE)) die(`BUILD_DATE '${BUILD_DATE}' is not YYYY-MM-DD`);
if (OUT === ROOT || OUT === path.join(ROOT, 'site') || OUT === path.join(ROOT, 'src')) die(`refusing to build into ${OUT}`); if (OUT === ROOT || OUT === path.join(ROOT, 'site') || OUT === path.join(ROOT, 'src')) die(`refusing to build into ${OUT}`);
// Multiplayer is off unless MP_API names the session server's path on the page's own origin ("//host/x" would be
// another host, and the player's token would go there).
const MP_API = process.env.MP_API || '';
if (MP_API && !/^\/(?!\/)[A-Za-z0-9/_-]*[A-Za-z0-9_-]$/.test(MP_API)) die(`MP_API '${MP_API}' must be a path on the same origin, like /api/mp`);
fs.rmSync(OUT, { recursive: true, force: true }); fs.rmSync(OUT, { recursive: true, force: true });
fs.cpSync(path.join(ROOT, 'site'), OUT, { recursive: true }); fs.cpSync(path.join(ROOT, 'site'), OUT, { recursive: true });
@ -44,7 +50,9 @@ if (!html.includes(PH)) die('release-notes placeholder missing from the page');
// A release can also open with a story (prose before its first bullet), shown in full in "What's new". // A release can also open with a story (prose before its first bullet), shown in full in "What's new".
const story = execFileSync(process.execPath, [path.join(__dirname, 'release-notes.js'), VERSION, '--story'], { encoding: 'utf8' }), PS = '/*__RELEASE_STORY__*/[]'; const story = execFileSync(process.execPath, [path.join(__dirname, 'release-notes.js'), VERSION, '--story'], { encoding: 'utf8' }), PS = '/*__RELEASE_STORY__*/[]';
if (!html.includes(PS)) die('release-story placeholder missing from the page'); if (!html.includes(PS)) die('release-story placeholder missing from the page');
fs.writeFileSync(page, html.replace(PH, () => notes.replace(/</g, '\\u003c')).replace(PS, () => story.replace(/</g, '\\u003c'))); const PM = "/*__MP_API__*/''";
if (!html.includes(PM)) die('multiplayer placeholder missing from the page');
fs.writeFileSync(page, html.replace(PH, () => notes.replace(/</g, '\\u003c')).replace(PS, () => story.replace(/</g, '\\u003c')).replace(PM, () => `'${MP_API}'`));
fs.writeFileSync(path.join(OUT, 'version.json'), JSON.stringify({ version: VERSION, date: BUILD_DATE, notes: JSON.parse(notes), story: JSON.parse(story) }, null, 2) + '\n'); fs.writeFileSync(path.join(OUT, 'version.json'), JSON.stringify({ version: VERSION, date: BUILD_DATE, notes: JSON.parse(notes), story: JSON.parse(story) }, null, 2) + '\n');
// Nothing may ship half-stamped. // Nothing may ship half-stamped.

View file

@ -7,6 +7,8 @@
// tools (node scripts/mcp.js --browser) drive the page this server serves. // tools (node scripts/mcp.js --browser) drive the page this server serves.
// Binds loopback by default; --host binds wherever the operator chooses, the relay with it. Plain node:http and the // Binds loopback by default; --host binds wherever the operator chooses, the relay with it. Plain node:http and the
// relay's ws. For the production build as GitHub Pages will serve it: npm run serve. // relay's ws. For the production build as GitHub Pages will serve it: npm run serve.
// --mp also runs the multiplayer API (docs/MULTIPLAYER.md) at /api/mp, sessions kept in mp-data/, and turns multiplayer
// on in the page: two browser windows (or a private one) can then play one session locally.
const fs = require('node:fs'); const fs = require('node:fs');
const http = require('node:http'); const http = require('node:http');
const path = require('node:path'); const path = require('node:path');
@ -23,17 +25,19 @@ const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; ch
'.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml', '.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml',
'.webmanifest': 'application/manifest+json' }; '.webmanifest': 'application/manifest+json' };
const RELOAD = '<script>new EventSource("/__dev").onmessage=()=>location.reload()</script>'; const RELOAD = '<script>new EventSource("/__dev").onmessage=()=>location.reload()</script>';
const MP = process.argv.includes('--mp') ? require('./lib/mp').createMp({ dir: path.join(ROOT, 'mp-data'), createPerHour: 1000, joinPerHour: 1000, log: (s) => console.error(s) }) : null;
const clients = new Set(); const clients = new Set();
function page() { function page() {
const { html, map } = assemble({ dev: true }); const { html, map } = assemble({ dev: true });
// Errors report a line of the assembled page; the console also says which file under src/ that is. // Errors report a line of the assembled page; the console also says which file under src/ that is.
const hint = `<script>addEventListener('error',e=>{const n=e.lineno,m=n&&(${lit(map)}).find(m=>n>=m.from&&n<=m.to);if(m)console.warn('↑ src/'+m.file+':'+(n-m.from+1))});</script>`; const hint = `<script>addEventListener('error',e=>{const n=e.lineno,m=n&&(${lit(map)}).find(m=>n>=m.from&&n<=m.to);if(m)console.warn('↑ src/'+m.file+':'+(n-m.from+1))});</script>`;
return html.replace('</body>', `${hint}${RELOAD}</body>`); return (MP ? html.replace("/*__MP_API__*/''", () => "'/api/mp'") : html).replace('</body>', `${hint}${RELOAD}</body>`);
} }
const server = http.createServer((req, res) => { const server = http.createServer((req, res) => {
const url = new URL(req.url, 'http://localhost'); const url = new URL(req.url, 'http://localhost');
if (MP && MP.handle(req, res)) return;
if (url.pathname === '/__dev') { if (url.pathname === '/__dev') {
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store' }); res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store' });
res.write(': hi\n\n'); res.write(': hi\n\n');
@ -69,6 +73,7 @@ server.listen(PORT, HOST, () => {
console.log(`Series of Tubes (dev): http://${at}/ — edits in src/ and site/ reload the page`); console.log(`Series of Tubes (dev): http://${at}/ — edits in src/ and site/ reload the page`);
console.error(`[series-of-tubes] agent relay on ws://${at}${relay.path} (no token)${local ? '' : `: bound to ${ad.address}, so anything that can reach this address can drive a game whose player turned agent mode on`}`); console.error(`[series-of-tubes] agent relay on ws://${at}${relay.path} (no token)${local ? '' : `: bound to ${ad.address}, so anything that can reach this address can drive a game whose player turned agent mode on`}`);
console.error('[series-of-tubes] to let an agent play: Settings → Agent API in the game, then node scripts/mcp.js --browser'); console.error('[series-of-tubes] to let an agent play: Settings → Agent API in the game, then node scripts/mcp.js --browser');
if (MP) console.error(`[series-of-tubes] multiplayer on: API at http://${at}/api/mp, sessions in ${path.relative(ROOT, MP.dir) || MP.dir}/`);
}); });
const shutdown = () => { relay.close(); process.exit(0); }; const shutdown = () => { relay.close(); process.exit(0); };
process.on('SIGINT', shutdown); process.on('SIGINT', shutdown);

448
scripts/lib/mp.js Normal file
View file

@ -0,0 +1,448 @@
// The multiplayer API (docs/MULTIPLAYER.md): sessions players share by a short code, each player's save kept on the
// server, and a small public card per player for the session's leaderboard and feed. Plain node:http, no dependencies.
// scripts/mp-server.js runs it on its own (optionally serving the built site too); npm run dev -- --mp mounts it in the
// dev server. It is never part of the page or of site/: the page only talks to it when the build stamped MP_API.
//
// Storage: one JSON file per session (DIR/<CODE>.json: settings, players, cards, feed) and one file per player's save
// (DIR/<CODE>.<pid>.save), kept apart so a card push never rewrites a dozen saves. Writes go to a temporary file and are
// renamed into place, one session at a time, in order. A session code is checked against CODE_RE before it ever becomes
// part of a file name, and so is a player id.
const fs = require('node:fs');
const path = require('node:path');
const net = require('node:net');
const crypto = require('node:crypto');
// Crockford's base32 (no I, L, O or U): codes read aloud or typed from a phone do not get mixed up.
const ALPHA = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
const CODE_RE = /^[0-9A-HJKMNP-TV-Z]{6}$/;
const PID_RE = /^[a-z0-9]{8}$/;
const TOKEN_RE = /^[0-9a-f]{64}$/;
const PRESETS = ['soft', 'freeze', 'oncall', 'bgp'];
const PPOL = ['open', 'selective', 'closed'];
const TIERS = ['t1', 't2', 't3'];
const ASN_LO = 200000, ASN_HI = 214999;
const COLORS = ['#ff4f9a', '#3a86ff', '#ffbe0b', '#2ec4b6', '#8338ec', '#fb5607', '#06d6a0', '#e63946', '#118ab2', '#8ac926', '#b5179e', '#6c757d'];
const MAX_SAVE = 4 * 1024 * 1024; // characters of save text ('gz:'+base64 or JSON)
const LIMIT = { small: 16 * 1024, save: MAX_SAVE + 64 * 1024 };
const SAVE_MS = 120000; // a save's body must arrive within this, or the upload is cut (it holds one of few places)
const FEED_MAX = 100, CHAT_MAX = 200;
const DAY = 86400000;
// "k7q-2xd", "K7Q 2XD", even "k7q2xo": the code itself, or null. I, L and O are read as 1, 1 and 0, as Crockford meant.
function normCode(s) {
if (typeof s !== 'string' || s.length > 20) return null;
const c = s.toUpperCase().replace(/[\s-]/g, '').replace(/[IL]/g, '1').replace(/O/g, '0');
return CODE_RE.test(c) ? c : null;
}
const showCode = (c) => c.slice(0, 3) + '-' + c.slice(3);
const randCode = () => { const b = crypto.randomBytes(6); let s = ''; for (const x of b) s += ALPHA[x & 31]; return s; };
const randPid = () => crypto.randomBytes(4).toString('hex');
const sha = (t) => crypto.createHash('sha256').update(t).digest();
// Text from players: no control or bidi-override characters, none of <>&"'` (the page escapes everything anyway), one
// space between words, at most max characters (whole characters, never half an emoji).
function cleanText(v, max) {
if (typeof v !== 'string') return '';
const s = v.replace(/[\u0000-\u001f\u007f-\u009f‎‏‪-‮⁦-⁩<>&"'`]/g, '').replace(/\s+/g, ' ').trim();
return Array.from(s).slice(0, max).join('').trim();
}
const cleanChat = (v) => {
if (typeof v !== 'string') return '';
const s = v.replace(/[\u0000-\u001f\u007f-\u009f‎‏‪-‮⁦-⁩]/g, ' ').replace(/\s+/g, ' ').trim();
return Array.from(s).slice(0, CHAT_MAX).join('').trim();
};
const num = (v, lo, hi, d = 0) => { v = +v; if (!Number.isFinite(v)) return d; return Math.min(hi, Math.max(lo, v)); };
const int = (v, lo, hi, d = 0) => Math.round(num(v, lo, hi, d));
// Only the first few times max entries are even looked at: a card padded with copies costs no more than an honest one.
const ids = (v, re, max) => {
if (!Array.isArray(v)) return [];
const out = new Set();
for (const x of v.slice(0, max * 4)) { if (typeof x === 'string' && re.test(x)) out.add(x); if (out.size >= max) break; }
return [...out];
};
const CITY_RE = /^[a-z0-9]{2,8}$/, IX_RE = /^[a-z0-9~_-]{1,16}$/, NET_RE = /^[a-z0-9]{1,12}$/;
/* A player's public card: only these fields, numbers clamped, ids only in their shape (the page checks them against its
catalogs again: this is other players' data there). Name and AS number come from the server, never from the card. */
function cleanCard(c) {
if (!c || typeof c !== 'object' || Array.isArray(c)) return null;
const links = [];
if (Array.isArray(c.links)) for (const l of c.links.slice(0, 1200)) {
if (!Array.isArray(l) || typeof l[0] !== 'string' || typeof l[1] !== 'string' || !CITY_RE.test(l[0]) || !CITY_RE.test(l[1]) || l[0] === l[1]) continue;
links.push([l[0], l[1], num(l[2], 0, 1e7)]);
if (links.length >= 300) break;
}
return {
day: int(c.day, 0, 1e7), tier: TIERS.includes(c.tier) ? c.tier : 't3', t1: c.t1 === true, lvl: int(c.lvl, 0, 99),
pops: ids(c.pops, CITY_RE, 500), links, ix: ids(c.ix, IX_RE, 500), transit: ids(c.transit, NET_RE, 64),
ppol: PPOL.includes(c.ppol) ? c.ppol : 'open', reach: num(c.reach, 0, 1), peak: num(c.peak, 0, 1e9), served: num(c.served, 0, 1e9),
cust: int(c.cust, 0, 1e7), rev: num(c.rev, -1e13, 1e13), cashB: int(c.cashB, -1, 20), score: num(c.score, 0, 1e15),
};
}
/* Small in-memory rate limits: at most n events per window for one key (an address, a player). Keys are kept in the
order they were last seen, so the ones nobody used for a whole window go from the front, a few at a time, and above
cap keys the oldest go too: memory stays bounded and no call ever walks the whole map. */
function limiter(n, ms, cap = 20000) {
const m = new Map();
const live = (k, now) => { const a = m.get(k); return a ? a.filter((t) => now - t < ms) : []; };
return {
// Counts one more, unless the key is already at its limit.
ok(k, now) {
const a = live(k, now), ok = a.length < n;
if (ok) a.push(now);
m.delete(k); m.set(k, a);
for (const [x, v] of m) { if (m.size > cap || !v.length || now - v[v.length - 1] >= ms) m.delete(x); else break; }
return ok;
},
full: (k, now) => live(k, now).length >= n,
size: () => m.size,
};
}
/* The address a limit counts against. One IPv6 customer (a phone, a home, a server) usually holds a whole /64, so an
IPv6 address counts as its /64; an IPv4 address mapped into IPv6 counts as itself. null: not an address. */
function addrKey(a) {
a = String(a || '').trim();
if (a.startsWith('[')) a = a.slice(1, a.indexOf(']') >>> 0);
const z = a.indexOf('%'); if (z >= 0) a = a.slice(0, z);
const m4 = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i.exec(a); if (m4) a = m4[1];
const v = net.isIP(a);
if (v === 4) return a;
if (v !== 6) return null;
const [h, t] = a.toLowerCase().split('::'), head = h ? h.split(':') : [], tail = t ? t.split(':') : [];
// The groups :: stands for (a dotted IPv4 at the end is two of them).
const n = head.length + tail.length + (tail.length && tail[tail.length - 1].includes('.') ? 1 : 0);
const g = t === undefined ? head : [...head, ...Array(8 - n).fill('0'), ...tail];
return g.slice(0, 4).map((x) => parseInt(x, 16).toString(16)).join(':') + '::/64';
}
class HttpError extends Error { constructor(status, msg, extra) { super(msg); this.status = status; this.extra = extra; } }
const fail = (status, msg, extra) => { throw new HttpError(status, msg, extra); };
// The request body as JSON, refusing it as soon as it is longer than max bytes (never buffered beyond that). A body that
// has not arrived within ms is cut off: it would hold its place (and its memory) for as long as the sender likes.
function readJson(req, max, ms = 30000) {
return new Promise((resolve, reject) => {
const ct = String(req.headers['content-type'] || '');
if (!/^application\/json\b/i.test(ct)) { req.resume(); return reject(new HttpError(415, 'send JSON (content-type: application/json)')); }
const len = +req.headers['content-length'];
if (len > max) { req.resume(); return reject(new HttpError(413, 'too large')); }
let parts = [], n = 0, done = false;
const stop = (e) => { if (done) return; done = true; clearTimeout(tm); parts = null; reject(e); };
const tm = setTimeout(() => { stop(new HttpError(408, 'too slow')); req.destroy(); }, ms);
req.on('data', (b) => {
if (done) return;
n += b.length;
if (n > max) { stop(new HttpError(413, 'too large')); req.resume(); return; }
parts.push(b);
});
req.on('end', () => {
if (done) return; done = true; clearTimeout(tm);
let j;
try { const t = Buffer.concat(parts).toString('utf8'); parts = null; j = JSON.parse(t); } catch (e) { return reject(new HttpError(400, 'bad JSON')); }
if (!j || typeof j !== 'object' || Array.isArray(j)) return reject(new HttpError(400, 'expected a JSON object'));
resolve(j);
});
req.on('error', () => stop(new HttpError(400, 'request failed')));
req.on('close', () => { if (!req.complete) stop(new HttpError(400, 'request failed')); });
});
}
function send(res, status, body) {
if (res.headersSent) { try { res.end(); } catch (e) { /* gone */ } return; }
const txt = JSON.stringify(body);
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', 'content-length': Buffer.byteLength(txt) });
res.end(txt);
}
/* createMp({dir, base, maxSessions, maxPlayers, pruneDays, trustProxy, verbose, log, now, ...limits}): the API.
handle(req, res) answers anything under base (default /api/mp) and returns true, or returns false for everything else. */
function createMp(o = {}) {
const dir = path.resolve(o.dir || 'mp-data');
const base = (o.base || '/api/mp').replace(/\/+$/, '');
const maxSessions = o.maxSessions || 1000, maxPlayers = o.maxPlayers || 12, pruneDays = o.pruneDays || 60;
const now = o.now || Date.now, log = o.log || ((s) => console.log(s));
fs.mkdirSync(dir, { recursive: true });
const file = (code) => path.join(dir, code + '.json');
const saveFile = (code, pid) => path.join(dir, `${code}.${pid}.save`);
const cache = new Map(), chains = new Map(), soon = new Map();
let codes = new Set(), tmpN = 0;
const HOUR = 3600000, MIN = 60000;
const createRate = limiter(o.createPerHour || 10, HOUR), joinRate = limiter(o.joinPerHour || 60, HOUR);
// However many addresses ask, the server fills up slowly: a full server takes days, not minutes.
const createAll = limiter(o.sessionsPerHour || 100, HOUR);
const chatRate = limiter(6, 30000), chatGap = limiter(1, 1000);
// Wrong codes, counted per address: guessing codes runs out long before it finds one.
const missRate = limiter(o.missesPerHour || 120, HOUR);
// A player's pushes. The game sends a save at most every 15 seconds and a card with it, so these never touch it; they
// stop one player from keeping the disk busy rewriting their session.
const saveRate = limiter(o.savesPerMinute || 20, MIN), cardRate = limiter(o.cardsPerMinute || 60, MIN);
// Saves being uploaded: one per player, a few per address, a few more on the whole server. Each can hold megabytes.
const up = new Set(), upAddr = new Map(), maxUploads = o.maxUploads || 16, maxUploadsAddr = o.maxUploadsPerAddress || 4;
// Atomic: write a temporary file next to it, then rename over the old one.
const writeAtomic = async (f, txt) => {
const tmp = `${f}.${process.pid}.${++tmpN}.tmp`;
await fs.promises.writeFile(tmp, txt);
await fs.promises.rename(tmp, f);
};
// One session's writes happen one after another, in the order they were asked for.
const queue = (code, job) => {
const p = (chains.get(code) || Promise.resolve()).then(job, job);
const q = p.catch((e) => { log(`[mp] writing ${code} failed: ${e.message}`); });
chains.set(code, q);
q.then(() => { if (chains.get(code) === q) chains.delete(code); });
return p;
};
// A session that is gone (its last player left) is never written again, whatever was still on its way.
const persist = (s) => {
const tm = soon.get(s.code); if (tm) { clearTimeout(tm); soon.delete(s.code); }
s.touched = now();
if (s.dead) return Promise.resolve();
return queue(s.code, () => s.dead ? null : writeAtomic(file(s.code), JSON.stringify(s)));
};
// Cards change often and matter little: their session is written a moment later, once for all of that moment's.
const persistSoon = (s) => {
s.touched = now();
if (s.dead || soon.has(s.code)) return;
const tm = setTimeout(() => { soon.delete(s.code); persist(s); }, o.persistMs ?? 2000);
if (tm.unref) tm.unref();
soon.set(s.code, tm);
};
function scan() { codes = new Set(); for (const f of fs.readdirSync(dir)) { const m = /^([0-9A-Z]{6})\.json$/.exec(f); if (m && CODE_RE.test(m[1])) codes.add(m[1]); } }
// Sessions nobody touched for pruneDays go, with their saves; so do leftovers of interrupted writes.
function prune() {
const cut = now() - pruneDays * DAY; let n = 0;
for (const f of fs.readdirSync(dir)) {
const p = path.join(dir, f);
let st; try { st = fs.statSync(p); } catch (e) { continue; }
if (!st.isFile()) continue;
if (f.endsWith('.tmp') && st.mtimeMs < now() - 3600000) { fs.rmSync(p, { force: true }); continue; }
const m = /^([0-9A-Z]{6})\.json$/.exec(f);
const live = m && cache.get(m[1]);
if (m && CODE_RE.test(m[1]) && st.mtimeMs < cut && !(live && live.touched >= cut)) { drop(m[1]); n++; }
}
for (const f of fs.readdirSync(dir)) { const m = /^([0-9A-Z]{6})\.[a-z0-9]{8}\.save$/.exec(f); if (m && !fs.existsSync(file(m[1]))) fs.rmSync(path.join(dir, f), { force: true }); }
scan();
return n;
}
function drop(code) {
const s = cache.get(code); if (s) s.dead = true;
const tm = soon.get(code); if (tm) { clearTimeout(tm); soon.delete(code); }
for (const f of fs.readdirSync(dir)) if (f === code + '.json' || (f.startsWith(code + '.') && f.endsWith('.save'))) fs.rmSync(path.join(dir, f), { force: true });
cache.delete(code); codes.delete(code);
}
function load(code) {
if (!CODE_RE.test(code)) return null;
if (cache.has(code)) return cache.get(code);
if (!codes.has(code)) return null;
let s = null;
try { s = JSON.parse(fs.readFileSync(file(code), 'utf8')); } catch (e) { return null; }
if (!s || s.code !== code || !Array.isArray(s.players)) return null;
// A hand-edited or damaged file: players without an id or a token hash cannot be anyone.
s.players = s.players.filter((p) => p && typeof p === 'object' && PID_RE.test(p.pid) && typeof p.th === 'string');
for (const p of s.players) if (!p.hit || typeof p.hit !== 'object') p.hit = { t1: !!(p.card && p.card.t1), t2: !!(p.card && (p.card.t1 || p.card.tier !== 't3')) };
if (!Array.isArray(s.feed)) s.feed = [];
cache.set(code, s);
return s;
}
prune();
// The client's address, as the limits count it (see addrKey); behind your own proxy, the one it added last.
const ipOf = (req) => {
if (o.trustProxy) { const x = String(req.headers['x-forwarded-for'] || '').split(',').map((v) => v.trim()).filter(Boolean); const k = x.length && addrKey(x[x.length - 1]); if (k) return k; }
return addrKey(req.socket.remoteAddress) || '?';
};
// The player this request's token belongs to, or null. Compares hashes of the same length, in constant time, even for
// a player who is not there.
function player(req, s) {
const m = /^Bearer ([a-z0-9]{8})\.([0-9a-f]{64})$/.exec(String(req.headers.authorization || ''));
if (!m) return null;
const p = s.players.find((x) => x.pid === m[1]);
const want = p && /^[0-9a-f]{64}$/.test(p.th) ? Buffer.from(p.th, 'hex') : Buffer.alloc(32), got = sha(m[2]);
return crypto.timingSafeEqual(want, got) && p ? p : null;
}
const authed = (p) => { if (!p) fail(401, 'unauthorized'); p.seen = now(); return p; };
// Still there after waiting for a body or a write: the player may have left meanwhile, or the session gone with them.
const still = (s, p) => !s.dead && cache.get(s.code) === s && (!p || s.players.includes(p));
const event = (s, k, p, extra) => { s.feed.push({ k, pid: p.pid, name: p.name, at: now(), ...extra }); if (s.feed.length > FEED_MAX) s.feed.splice(0, s.feed.length - FEED_MAX); };
const roster = (s) => ({
code: s.code, title: s.title, preset: s.preset, seed: s.seed, created: s.created,
players: s.players.map((p) => ({ pid: p.pid, name: p.name, asn: p.asn, color: p.color, card: p.card, seen: p.seen, joined: p.joined })),
feed: s.feed,
});
// A card can tell the feed something, once per player: reaching Tier 2, and Tier 1 (the first one in the session gets
// the headline). A network that drops out and comes back is not news again.
function applyCard(s, p, c) {
const hit = p.hit || (p.hit = {});
if (c.t1 && !hit.t1) { hit.t1 = hit.t2 = true; if (!s.first) { s.first = p.pid; event(s, 't1first', p); } else event(s, 't1', p); }
else if (c.tier === 't2' && !hit.t2) { hit.t2 = true; event(s, 't2', p); }
p.card = c;
}
function newPlayer(s, body, ip) {
const net = body.net && typeof body.net === 'object' ? body.net : {};
const name = cleanText(net.name, 32);
if (!name) fail(400, 'name your network');
const home = typeof net.home === 'string' && CITY_RE.test(net.home) ? net.home : null;
if (!home) fail(400, 'pick a home city');
let pid; do pid = randPid(); while (s.players.some((p) => p.pid === pid));
const token = crypto.randomBytes(32).toString('hex');
const avoid = new Set((Array.isArray(body.avoid) ? body.avoid.slice(0, 64) : []).filter((a) => Number.isInteger(a)));
for (const p of s.players) avoid.add(p.asn);
let asn; do asn = ASN_LO + crypto.randomInt(ASN_HI - ASN_LO + 1); while (avoid.has(asn));
const color = COLORS.find((c) => !s.players.some((p) => p.color === c)) || COLORS[s.players.length % COLORS.length];
const p = { pid, name, home, asn, color, th: sha(token).toString('hex'), joined: now(), seen: now(), card: null, sv: null, hit: {} };
s.players.push(p);
event(s, 'join', p);
return { code: s.code, pid, token, seed: s.seed, asn, preset: s.preset, color, title: s.title };
}
// The save as stored: its text alone (the number and time are in the session). Files from before that were wrapped.
const readSave = async (code, pid) => {
const t = await fs.promises.readFile(saveFile(code, pid), 'utf8');
if (t.startsWith('{"seq":')) { try { const j = JSON.parse(t); if (typeof j.data === 'string') return j.data; } catch (e) { /* a save after all */ } }
return t;
};
// A save upload holds a place until it is done: one per player, a few per address and on the whole server.
function upTake(key, ip) {
if (up.has(key)) fail(429, 'a save of yours is still on its way');
if (up.size >= maxUploads || (upAddr.get(ip) || 0) >= maxUploadsAddr) fail(503, 'busy: try again in a moment', { busy: true });
up.add(key); upAddr.set(ip, (upAddr.get(ip) || 0) + 1);
return () => { up.delete(key); const n = (upAddr.get(ip) || 1) - 1; if (n > 0) upAddr.set(ip, n); else upAddr.delete(ip); };
}
async function route(req, res, url) {
const rest = url.pathname.slice(base.length);
const t = now(), ip = ipOf(req), M = req.method;
if (rest === '/sessions') {
if (M !== 'POST') fail(405, 'method not allowed');
const body = await readJson(req, LIMIT.small);
if (codes.size >= maxSessions) fail(503, 'the server is full: no new sessions for now');
if (!createRate.ok(ip, t)) fail(429, 'too many new sessions from here: try again later');
if (!createAll.ok('*', t)) fail(503, 'the server is full: no new sessions for now');
const preset = PRESETS.includes(body.preset) ? body.preset : null;
if (!preset) fail(400, 'unknown rules preset');
let code; do code = randCode(); while (codes.has(code));
const s = { v: 1, code, title: cleanText(body.title, 40), preset, seed: crypto.randomBytes(4).readInt32LE(0), created: t, touched: t, first: null, players: [], feed: [] };
const out = newPlayer(s, body, ip);
codes.add(code); cache.set(code, s);
await persist(s);
return send(res, 201, out);
}
const m = /^\/sessions\/([^/]{1,32})(\/[a-z]+)?$/.exec(rest);
if (!m) fail(404, 'not found');
const sub = m[2] || '';
let raw = ''; try { raw = decodeURIComponent(m[1]); } catch (e) { /* not a code */ }
const code = normCode(raw), s = code && load(code);
// A player of this very session, with their token, is never held up by somebody else's wrong codes from the same
// address. Everyone else is: a wrong code and a wrong token get the same answer then, so it says nothing either.
const me = s ? player(req, s) : null;
if (!me && missRate.full(ip, t)) fail(429, 'too many wrong codes from here: try again later');
if (sub === '/join' && M === 'POST' && !joinRate.ok(ip, t)) fail(429, 'too many joins from here: try again later');
if (!s) { missRate.ok(ip, t); fail(404, 'no such session'); }
if (sub === '/join') {
if (M !== 'POST') fail(405, 'method not allowed');
const body = await readJson(req, LIMIT.small);
if (!still(s)) fail(404, 'no such session');
if (s.players.length >= maxPlayers) fail(409, 'this session is full', { full: true });
const out = newPlayer(s, body, ip);
await persist(s);
return send(res, 200, out);
}
if (sub === '') {
if (M !== 'GET') fail(405, 'method not allowed');
authed(me);
return send(res, 200, roster(s));
}
if (sub === '/card') {
if (M !== 'PUT') fail(405, 'method not allowed');
const p = authed(me);
if (!cardRate.ok(code + '.' + p.pid, t)) fail(429, 'too many cards: slow down');
const body = await readJson(req, LIMIT.small);
if (!still(s, p)) fail(401, 'unauthorized');
const c = cleanCard(body.card);
if (!c) fail(400, 'bad card');
applyCard(s, p, c);
persistSoon(s);
return send(res, 200, roster(s));
}
if (sub === '/save') {
if (M === 'GET') {
const p = authed(me);
if (!p.sv) fail(404, 'no save yet');
let data; try { data = await readSave(code, p.pid); } catch (e) { fail(404, 'no save yet'); }
return send(res, 200, { seq: p.sv.seq, at: p.sv.at, data });
}
if (M !== 'PUT') fail(405, 'method not allowed');
const p = authed(me), key = code + '.' + p.pid;
const free = upTake(key, ip);
try {
if (!saveRate.ok(key, t)) fail(429, 'too many saves: slow down');
const body = await readJson(req, LIMIT.save, o.saveMs || SAVE_MS);
if (!still(s, p)) fail(401, 'unauthorized');
const seq = body.seq, data = body.data;
if (!Number.isSafeInteger(seq) || seq < 1) fail(400, 'seq must be a positive integer');
if (typeof data !== 'string' || !data.length) fail(400, 'no save data');
if (data.length > MAX_SAVE) fail(413, 'save too large');
if (!(data.startsWith('gz:') || data.startsWith('{'))) fail(400, 'not a save');
const card = body.card === undefined ? undefined : cleanCard(body.card);
if (card === null) fail(400, 'bad card');
const old = p.sv;
// Another device of the same player saved a newer game: never overwrite it unless the player says so.
if (old && seq <= old.seq && body.force !== true) fail(409, 'a newer save is on the server', { seq: old.seq, at: old.at });
const at = num(body.at, 0, 1e15, t), sq = old && seq <= old.seq ? old.seq + 1 : seq;
// The session says it has this save only once the save is on disk.
await queue(code, () => writeAtomic(saveFile(code, p.pid), data));
if (!still(s, p)) fail(401, 'unauthorized');
p.sv = { seq: sq, at, size: data.length };
if (card) applyCard(s, p, card);
await persist(s);
return send(res, 200, { ok: true, seq: sq, at, roster: roster(s) });
} finally { free(); }
}
if (sub === '/feed') {
if (M !== 'POST') fail(405, 'method not allowed');
const p = authed(me), body = await readJson(req, LIMIT.small);
if (!still(s, p)) fail(401, 'unauthorized');
const text = cleanChat(body.text);
if (!text) fail(400, 'say something');
if (!chatGap.ok(code + p.pid, t) || !chatRate.ok(code + p.pid, t)) fail(429, 'slow down a little');
event(s, 'chat', p, { text });
await persist(s);
return send(res, 200, roster(s));
}
if (sub === '/me') {
if (M !== 'DELETE') fail(405, 'method not allowed');
const p = authed(me);
s.players = s.players.filter((x) => x !== p);
await queue(code, () => fs.promises.rm(saveFile(code, p.pid), { force: true }));
if (!s.players.length) { s.dead = true; await queue(code, async () => drop(code)); return send(res, 200, { ok: true }); }
event(s, 'leave', p);
await persist(s);
return send(res, 200, { ok: true });
}
fail(404, 'not found');
}
function handle(req, res) {
let url;
try { url = new URL(req.url, 'http://x'); } catch (e) { return false; }
if (url.pathname !== base && !url.pathname.startsWith(base + '/')) return false;
const t0 = Date.now();
res.on('finish', () => { if (o.verbose) log(`${new Date().toISOString()} ${ipOf(req)} ${req.method} ${url.pathname} ${res.statusCode} ${Date.now() - t0}ms`); });
route(req, res, url).catch((e) => {
// A body nobody read (refused before it was needed) is drained, so the client still gets its answer.
if (!req.complete && !req.destroyed) req.resume();
if (e instanceof HttpError) return send(res, e.status, { error: e.message, ...(e.extra || {}) });
log(`[mp] ${req.method} ${url.pathname}: ${e && e.stack || e}`);
send(res, 500, { error: 'server error' });
});
return true;
}
// Everything written before the process goes, sessions waiting for their moment too.
const flush = () => { for (const code of [...soon.keys()]) { const s = cache.get(code); if (s) persist(s); else { clearTimeout(soon.get(code)); soon.delete(code); } } return Promise.all([...chains.values()]); };
return { handle, prune, flush, dir, base, sessions: () => codes.size, uploads: () => up.size };
}
module.exports = { createMp, cleanCard, cleanText, normCode, showCode, addrKey, limiter, CODE_RE, PRESETS, MAX_SAVE };

117
scripts/mp-server.js Normal file
View file

@ -0,0 +1,117 @@
#!/usr/bin/env node
// The multiplayer server for a self-hosted Series of Tubes (docs/MULTIPLAYER.md). The public game at seriesoftub.es
// is GitHub Pages only and has no multiplayer: this is for your own copy, built with MP_API=/api/mp npm run build.
// Plain node:http, no dependencies. It answers the API under /api/mp and, with --site, serves the built game too, so
// one process can sit behind a reverse proxy.
const fs = require('node:fs');
const http = require('node:http');
const path = require('node:path');
const { createMp } = require('./lib/mp');
const HELP = `Series of Tubes multiplayer server
node scripts/mp-server.js [options] (npm run mp -- [options])
--port N port to listen on (default 8090, or $PORT)
--host H address to bind (default 127.0.0.1: put a reverse proxy in front)
--data DIR where sessions and saves are kept (default ./mp-data, created if missing)
--site DIR also serve the built game from DIR (e.g. _site from MP_API=/api/mp npm run build)
--base PATH the API's path (default /api/mp; the page's MP_API must match)
--prune-days N sessions nobody touched for N days are deleted at startup and daily (default 60)
--max-sessions N at most N sessions on this server (default 1000)
--max-players N at most N players per session (default 12, at most 12)
--create-per-hour N new sessions one address may start per hour (default 10; an IPv6 address counts as its /64)
--sessions-per-hour N new sessions on the whole server per hour (default 100)
--trust-proxy take the client's address from X-Forwarded-For (only behind your own reverse proxy)
--verbose log one line per API request (never tokens)
--help this text
Storage: DIR/<CODE>.json per session and DIR/<CODE>.<pid>.save per player's save. Back up DIR.
API (JSON; every call but create and join needs Authorization: Bearer <pid>.<token>):
POST /api/mp/sessions {net:{name,home},preset,title?} start a session
POST /api/mp/sessions/:code/join {net:{name,home}} join one
GET /api/mp/sessions/:code roster, cards and feed
PUT /api/mp/sessions/:code/card {card} your public card
PUT /api/mp/sessions/:code/save {seq,at,data,card?,force?} your save (409 when the server has a newer one)
GET /api/mp/sessions/:code/save your save
POST /api/mp/sessions/:code/feed {text} a chat line
DELETE /api/mp/sessions/:code/me leave
`;
const argv = process.argv.slice(2);
if (argv.includes('--help') || argv.includes('-h')) { process.stdout.write(HELP); process.exit(0); }
const die = (m) => { console.error(`error: ${m}`); process.exit(2); };
const KNOWN = new Set(['--port', '--host', '--data', '--site', '--base', '--prune-days', '--max-sessions', '--max-players', '--create-per-hour', '--sessions-per-hour', '--trust-proxy', '--verbose', '--help', '-h']);
for (const a of argv) if (a.startsWith('-') && !KNOWN.has(a)) die(`unknown option ${a} (see --help)`);
const opt = (k) => { const i = argv.indexOf(k); if (i < 0) return null; const v = argv[i + 1]; if (v === undefined || v.startsWith('--')) die(`${k} needs a value`); return v; };
const pos = (k, d, max = 1e9) => { const v = opt(k); if (v === null) return d; const n = +v; if (!Number.isInteger(n) || n < 1 || n > max) die(`${k} wants a whole number from 1 to ${max}`); return n; };
const PORT = pos('--port', +process.env.PORT || 8090, 65535);
const HOST = opt('--host') || '127.0.0.1';
const DATA = path.resolve(opt('--data') || 'mp-data');
const SITE = opt('--site') ? path.resolve(opt('--site')) : null;
const BASE = opt('--base') || '/api/mp';
// A path, never "//host/..." (which a browser reads as another host).
if (!/^\/(?!\/)[A-Za-z0-9/_-]*[A-Za-z0-9_-]$/.test(BASE)) die('--base must be a path like /api/mp');
if (SITE && !fs.statSync(SITE, { throwIfNoEntry: false })?.isDirectory()) die(`--site ${SITE} is not a directory`);
if (SITE && !fs.existsSync(path.join(SITE, 'index.html'))) die(`--site ${SITE} has no index.html (run npm run build first)`);
const mp = createMp({
dir: DATA, base: BASE, pruneDays: pos('--prune-days', 60), maxSessions: pos('--max-sessions', 1000),
maxPlayers: pos('--max-players', 12, 12), createPerHour: pos('--create-per-hour', 10), sessionsPerHour: pos('--sessions-per-hour', 100),
trustProxy: argv.includes('--trust-proxy'), verbose: argv.includes('--verbose'),
});
const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json',
'.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml',
'.webmanifest': 'application/manifest+json', '.woff2': 'font/woff2', '.jpg': 'image/jpeg', '.webp': 'image/webp' };
// The page, the service worker and the files that change between releases are always checked; the rest may be cached.
const FRESH = /(^|\/)(index\.html|404\.html|sw\.js|version\.json)$|\/weekly\//;
// What is at p, or null: a path the file system cannot even look at (too long, a loop of links...) is not there either.
const stat = (p) => { try { return fs.statSync(p, { throwIfNoEntry: false }) || null; } catch (e) { return null; } };
const isFile = (p) => { const st = stat(p); return !!(st && st.isFile()); };
// The built site, like GitHub Pages serves it: / is index.html, a missing file is 404.html, nothing outside SITE.
function serveSite(req, res) {
if (req.method !== 'GET' && req.method !== 'HEAD') { res.writeHead(405, { allow: 'GET, HEAD' }); return res.end(); }
let rel;
try { rel = decodeURIComponent(new URL(req.url, 'http://x').pathname); } catch (e) { rel = null; }
let file = null;
if (rel !== null && !rel.includes('\0')) {
if (rel.endsWith('/')) rel += 'index.html';
const p = path.resolve(SITE, '.' + path.posix.normalize('/' + rel));
if (p.startsWith(SITE + path.sep)) { const st = stat(p); if (st && st.isFile()) file = p; else if (st && st.isDirectory() && isFile(path.join(p, 'index.html'))) file = path.join(p, 'index.html'); }
}
const status = file ? 200 : 404;
if (!file) file = path.join(SITE, '404.html');
if (!isFile(file)) { res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }); return res.end('Not found'); }
const r = path.relative(SITE, file).split(path.sep).join('/');
res.writeHead(status, { 'content-type': TYPES[path.extname(file)] || 'application/octet-stream', 'cache-control': FRESH.test('/' + r) ? 'no-cache' : 'public, max-age=3600', 'x-content-type-options': 'nosniff' });
if (req.method === 'HEAD') return res.end();
fs.createReadStream(file).on('error', () => res.destroy()).pipe(res);
}
const server = http.createServer((req, res) => {
try {
if (mp.handle(req, res)) return;
if (SITE) return serveSite(req, res);
res.writeHead(404, { 'content-type': 'application/json; charset=utf-8' });
res.end('{"error":"not found"}');
} catch (e) {
// One line, never a stack: whatever went wrong, a request should not be able to fill the log.
console.error(`[mp] ${req.method} ${String(req.url).slice(0, 200)}: ${e && e.message}`);
if (!res.headersSent) res.writeHead(500, { 'content-type': 'application/json; charset=utf-8' });
res.end('{"error":"server error"}');
}
});
server.on('clientError', (e, socket) => { try { socket.end('HTTP/1.1 400 Bad Request\r\n\r\n'); } catch (_) { /* gone */ } });
server.on('error', (e) => { console.error(`error: could not listen on ${HOST}:${PORT}: ${e.message}`); process.exit(1); });
server.listen(PORT, HOST, () => {
const ad = server.address(), at = `${ad.family === 'IPv6' ? `[${ad.address}]` : ad.address}:${ad.port}`;
console.log(`Series of Tubes multiplayer: http://${at}${BASE} (data in ${DATA}, ${mp.sessions()} sessions${SITE ? `, serving ${SITE}` : ''})`);
});
setInterval(() => { try { mp.prune(); } catch (e) { console.error(`[mp] pruning failed: ${e.message}`); } }, 86400000).unref();
const shutdown = () => { server.close(); mp.flush().finally(() => process.exit(0)); setTimeout(() => process.exit(0), 3000).unref(); };
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);

View file

@ -3085,6 +3085,65 @@
"modal_and_names.the_real_thing_follow_a_packet":"Das Original: Folge einem Paket vom WLAN bis zur Unterseeglasfaser.", "modal_and_names.the_real_thing_follow_a_packet":"Das Original: Folge einem Paket vom WLAN bis zur Unterseeglasfaser.",
"modals.lay_your_own_subsea_cable":"Eigenes Seekabel verlegen…", "modals.lay_your_own_subsea_cable":"Eigenes Seekabel verlegen…",
"modals.your_own_subsea_cable_level_n":"Eigenes Seekabel <small>Level {n} oder Tier 1</small>", "modals.your_own_subsea_cable_level_n":"Eigenes Seekabel <small>Level {n} oder Tier 1</small>",
"mp.code":"Session-Code",
"mp.copy_link":"Link kopieren",
"mp.door_d":"Eine Welt, die Netze deiner Freunde neben deinem: Code teilen und um Tier 1 wetteifern.",
"mp.err_code":"Ein Session-Code hat sechs Buchstaben und Ziffern, etwa K7Q-2XD.",
"mp.err_full":"Diese Session ist voll: Alle Plätze darin sind vergeben.",
"mp.err_no_session":"Mit diesem Code gibt es keine Session.",
"mp.err_offline":"Der Multiplayer-Server ist gerade nicht erreichbar. Versuch es gleich noch mal.",
"mp.err_refused":"Das hat der Server nicht angenommen. Versuch einen anderen Netznamen.",
"mp.err_server_full":"Der Server nimmt gerade keine neuen Sessions an.",
"mp.err_slow":"Zu viele Versuche von hier. Warte kurz und versuch es noch mal.",
"mp.feed":"Feed",
"mp.feed_empty":"Noch nichts. Sag hallo!",
"mp.feed_join":"{name} ist der Session beigetreten.",
"mp.feed_leave":"{name} hat die Session verlassen.",
"mp.feed_t1":"{name} ist jetzt auch Tier 1.",
"mp.feed_t1first":"{name} ist das erste Tier 1 in dieser Session!",
"mp.feed_t2":"{name} ist jetzt Tier 2.",
"mp.intro":"Alle bauen ihr eigenes Netz in derselben Welt, ab demselben Tag 0, mit denselben Regeln. Rangliste und Feed zeigen, wer vorne liegt.",
"mp.join":"Beitreten",
"mp.join_a_session":"Einer Session beitreten",
"mp.join_note":"Welt und Regeln kommen von dem, der die Session gestartet hat, und deine AS-Nummer bekommst du von der Session.",
"mp.joined":"<b>Du bist Session {code} beigetreten.</b> Öffne die Session, um zu sehen, wer vorne liegt.",
"mp.keep_mine":"Diesen behalten",
"mp.leaderboard":"Rangliste",
"mp.leave":"Session verlassen",
"mp.leave_d":"{name} bleibt auf diesem Gerät als eigenes Spiel. Die Session vergisst es, und sein Spielstand auf dem Server wird gelöscht.",
"mp.leave_q":"Session {code} verlassen?",
"mp.left":"Du hast die Session verlassen. {name} spielt hier allein weiter.",
"mp.link_bad":"Dieser Multiplayer-Link hat nicht funktioniert: Er ist alt, oder dieses Netz hat nie in der Session gespeichert.",
"mp.link_copied":"Link kopiert. Öffne ihn auf deinem anderen Gerät.",
"mp.load_newer":"Neueren Spielstand laden",
"mp.loaded_newer":"Den neueren Spielstand von {name} aus der Session geladen ({date}).",
"mp.loading":"Frage den Server…",
"mp.move_device":"Auf ein anderes Gerät umziehen",
"mp.move_note":"Öffne diesen Link auf deinem anderen Handy oder Computer, um dort mit diesem Netz weiterzumachen. Es zählt, welches Gerät zuletzt speichert.",
"mp.move_warn":"Wer diesen Link hat, kann als du spielen. Behalte ihn für dich.",
"mp.moved_on_elsewhere":"<b>Die Session ist woanders weitergelaufen.</b> Dein Netz wurde seitdem auf einem anderen Gerät gespielt. Lade jenen Spielstand, oder behalte deinen hier und überschreib den auf dem Server.",
"mp.multiplayer":"Multiplayer",
"mp.n_customers":{"one":"{n} Kunde","other":"{n} Kunden"},
"mp.n_pops":{"one":"{n} POP","other":"{n} POPs"},
"mp.no_card":"hat noch keinen Tag beendet",
"mp.no_newer":"Die Session hat keinen neueren Spielstand von {name}. Dieser bleibt und geht beim nächsten Speichern an den Server.",
"mp.not_in_session":"Dieses Netz ist nicht mehr in seiner Session. Es spielt hier allein weiter.",
"mp.play_with_friends":"Mit Freunden spielen",
"mp.save_unreadable":"Der Spielstand dieses Netzes in der Session war nicht lesbar. Es geht mit dem hier weiter.",
"mp.say":"Sag was",
"mp.send":"Senden",
"mp.server_away":"Der Multiplayer-Server ist weg. Dein Netz spielt hier weiter und holt auf, sobald er zurück ist.",
"mp.session":"Multiplayer-Session",
"mp.session_code":"Session {code}",
"mp.session_live":"<b>Session {code} läuft.</b> Teil den Code: Wer beitritt, baut in derselben Welt.",
"mp.session_title":"Name der Session (optional)",
"mp.share_line":"Komm in meine Series-of-Tubes-Session {code}: {url}",
"mp.share_note":"Freunde treten vom Startbildschirm aus bei: Multiplayer, dann dieser Code.",
"mp.slow_down":"Mach mal langsam: eine Zeile pro Sekunde.",
"mp.start_a_session":"Session starten",
"mp.talking":"Spreche mit dem Server…",
"mp.welcome_device":"<b>{name}</b> ist auf dieses Gerät umgezogen. Willkommen zurück in Session {code}.",
"mp.you":"du",
"networks.a_mobile_network_named_after_the":"Ein Mobilfunknetz, benannt nach dem Klang anstoßender Gläser. Prost auf jeden 5G-Mast.", "networks.a_mobile_network_named_after_the":"Ein Mobilfunknetz, benannt nach dem Klang anstoßender Gläser. Prost auf jeden 5G-Mast.",
"networks.a_spanish_carrier_starring_in_every":"Ein spanischer Carrier mit Hauptrolle in jedem lateinamerikanischen Markt, zumindest bis er den nächsten verkauft.", "networks.a_spanish_carrier_starring_in_every":"Ein spanischer Carrier mit Hauptrolle in jedem lateinamerikanischen Markt, zumindest bis er den nächsten verkauft.",
"networks.a_tiny_telco_in_a_country":"Eine winzige Telco in einem Land, in dem die Kabel der Welt an Land gehen. Die Preise passen dazu.", "networks.a_tiny_telco_in_a_country":"Eine winzige Telco in einem Land, in dem die Kabel der Welt an Land gehen. Die Preise passen dazu.",

View file

@ -3083,6 +3083,65 @@
"modal_and_names.the_real_thing_follow_a_packet":"Lo de verdad: sigue un paquete del Wi-Fi a la fibra submarina.", "modal_and_names.the_real_thing_follow_a_packet":"Lo de verdad: sigue un paquete del Wi-Fi a la fibra submarina.",
"modals.lay_your_own_subsea_cable":"Tender tu propio cable submarino…", "modals.lay_your_own_subsea_cable":"Tender tu propio cable submarino…",
"modals.your_own_subsea_cable_level_n":"Tu propio cable submarino <small>nivel {n} o Tier 1</small>", "modals.your_own_subsea_cable_level_n":"Tu propio cable submarino <small>nivel {n} o Tier 1</small>",
"mp.code":"Código de la sesión",
"mp.copy_link":"Copiar el enlace",
"mp.door_d":"Un mundo, las redes de tus amigos junto a la tuya: comparte un código y compite por llegar a Tier 1.",
"mp.err_code":"Un código de sesión tiene seis letras y cifras, como K7Q-2XD.",
"mp.err_full":"Esa sesión está llena: no queda ningún hueco libre.",
"mp.err_no_session":"No hay ninguna sesión con ese código.",
"mp.err_offline":"Ahora mismo no se puede contactar con el servidor multijugador. Inténtalo de nuevo en un momento.",
"mp.err_refused":"El servidor no lo aceptó. Prueba con otro nombre de red.",
"mp.err_server_full":"El servidor no acepta sesiones nuevas ahora mismo.",
"mp.err_slow":"Demasiados intentos desde aquí. Espera un poco y vuelve a intentarlo.",
"mp.feed":"Actividad",
"mp.feed_empty":"Nada todavía. ¡Saluda!",
"mp.feed_join":"{name} se unió a la sesión.",
"mp.feed_leave":"{name} dejó la sesión.",
"mp.feed_t1":"{name} también es Tier 1.",
"mp.feed_t1first":"¡{name} es el primer Tier 1 de esta sesión!",
"mp.feed_t2":"{name} llegó a Tier 2.",
"mp.intro":"Cada uno construye su propia red en el mismo mundo, desde el mismo día 0 y con las mismas reglas. La clasificación y la actividad muestran quién va delante.",
"mp.join":"Unirse",
"mp.join_a_session":"Unirse a una sesión",
"mp.join_note":"El mundo y las reglas los pone quien empezó la sesión, y la sesión te da tu número de AS.",
"mp.joined":"<b>Te uniste a la sesión {code}.</b> Abre la sesión para ver quién va delante.",
"mp.keep_mine":"Quedarme con esta",
"mp.leaderboard":"Clasificación",
"mp.leave":"Dejar la sesión",
"mp.leave_d":"{name} se queda en este dispositivo como una partida propia. La sesión se olvida de ella y su partida guardada en el servidor se borra.",
"mp.leave_q":"¿Dejar la sesión {code}?",
"mp.left":"Dejaste la sesión. {name} sigue jugando aquí por su cuenta.",
"mp.link_bad":"Ese enlace multijugador no funcionó: es antiguo, o esa red nunca guardó en la sesión.",
"mp.link_copied":"Enlace copiado. Ábrelo en tu otro dispositivo.",
"mp.load_newer":"Cargar la más reciente",
"mp.loaded_newer":"Se cargó desde la sesión la partida más reciente de {name} ({date}).",
"mp.loading":"Preguntando al servidor…",
"mp.move_device":"Pasar a otro dispositivo",
"mp.move_note":"Abre este enlace en tu otro móvil u ordenador para seguir allí con esta red. Gana el dispositivo que guarde el último.",
"mp.move_warn":"Cualquiera con este enlace puede jugar como tú. Guárdalo para ti.",
"mp.moved_on_elsewhere":"<b>Esta sesión siguió en otro sitio.</b> Desde entonces tu red se jugó en otro dispositivo. Carga esa partida, o quédate con esta y sobrescríbela.",
"mp.multiplayer":"Multijugador",
"mp.n_customers":{"one":"{n} cliente","other":"{n} clientes"},
"mp.n_pops":{"one":"{n} POP","other":"{n} POPs"},
"mp.no_card":"aún no ha terminado ningún día",
"mp.no_newer":"La sesión no tiene una partida más reciente de {name}. Se queda esta, que irá al servidor con el próximo guardado.",
"mp.not_in_session":"Esta red ya no está en su sesión. Sigue jugando aquí por su cuenta.",
"mp.play_with_friends":"Jugar con amigos",
"mp.save_unreadable":"No se pudo leer la partida de esta red en la sesión. Se sigue con la de aquí.",
"mp.say":"Di algo",
"mp.send":"Enviar",
"mp.server_away":"El servidor multijugador no está. Tu red sigue jugando aquí y se pone al día cuando vuelva.",
"mp.session":"Sesión multijugador",
"mp.session_code":"Sesión {code}",
"mp.session_live":"<b>La sesión {code} está en marcha.</b> Comparte el código: quien se una construye en el mismo mundo.",
"mp.session_title":"Nombre de la sesión (opcional)",
"mp.share_line":"Únete a mi sesión de Series of Tubes {code}: {url}",
"mp.share_note":"Tus amigos se unen desde la pantalla de inicio: Multijugador y luego este código.",
"mp.slow_down":"Más despacio: una línea por segundo.",
"mp.start_a_session":"Empezar una sesión",
"mp.talking":"Hablando con el servidor…",
"mp.welcome_device":"<b>{name}</b> se pasó a este dispositivo. Bienvenido de nuevo a la sesión {code}.",
"mp.you":"tú",
"networks.a_mobile_network_named_after_the":"Una red móvil con el nombre del sonido de un brindis. Salud por cada torre 5G.", "networks.a_mobile_network_named_after_the":"Una red móvil con el nombre del sonido de un brindis. Salud por cada torre 5G.",
"networks.a_spanish_carrier_starring_in_every":"Un operador español protagonista en todos los mercados latinoamericanos, al menos hasta que vende el siguiente.", "networks.a_spanish_carrier_starring_in_every":"Un operador español protagonista en todos los mercados latinoamericanos, al menos hasta que vende el siguiente.",
"networks.a_tiny_telco_in_a_country":"Una telco diminuta en un país donde llegan a tierra los cables del mundo. Precios a juego.", "networks.a_tiny_telco_in_a_country":"Una telco diminuta en un país donde llegan a tierra los cables del mundo. Precios a juego.",

View file

@ -3083,6 +3083,65 @@
"modal_and_names.the_real_thing_follow_a_packet":"La version réelle : suis un paquet du Wi-Fi à la fibre sous-marine.", "modal_and_names.the_real_thing_follow_a_packet":"La version réelle : suis un paquet du Wi-Fi à la fibre sous-marine.",
"modals.lay_your_own_subsea_cable":"Pose ton propre câble sous-marin…", "modals.lay_your_own_subsea_cable":"Pose ton propre câble sous-marin…",
"modals.your_own_subsea_cable_level_n":"Ton propre câble sous-marin <small>niveau {n} ou Tier 1</small>", "modals.your_own_subsea_cable_level_n":"Ton propre câble sous-marin <small>niveau {n} ou Tier 1</small>",
"mp.code":"Code de la session",
"mp.copy_link":"Copier le lien",
"mp.door_d":"Un seul monde, les réseaux de tes amis à côté du tien : partage un code et fonce vers le Tier 1.",
"mp.err_code":"Un code de session a six lettres et chiffres, comme K7Q-2XD.",
"mp.err_full":"Cette session est pleine : toutes les places sont prises.",
"mp.err_no_session":"Aucune session n'a ce code.",
"mp.err_offline":"Le serveur multijoueur est injoignable pour l'instant. Réessaie dans un moment.",
"mp.err_refused":"Le serveur n'a pas accepté. Essaie un autre nom de réseau.",
"mp.err_server_full":"Le serveur n'accepte pas de nouvelles sessions pour l'instant.",
"mp.err_slow":"Trop d'essais depuis ici. Attends un peu et réessaie.",
"mp.feed":"Fil",
"mp.feed_empty":"Rien pour l'instant. Dis bonjour !",
"mp.feed_join":"{name} a rejoint la session.",
"mp.feed_leave":"{name} a quitté la session.",
"mp.feed_t1":"{name} est Tier 1 aussi.",
"mp.feed_t1first":"{name} est le premier Tier 1 de cette session !",
"mp.feed_t2":"{name} est passé Tier 2.",
"mp.intro":"Chacun construit son propre réseau dans le même monde, depuis le même jour 0, avec les mêmes règles. Le classement et le fil montrent qui mène.",
"mp.join":"Rejoindre",
"mp.join_a_session":"Rejoindre une session",
"mp.join_note":"Le monde et les règles viennent de qui a lancé la session, et la session te donne ton numéro d'AS.",
"mp.joined":"<b>Tu as rejoint la session {code}.</b> Ouvre la session pour voir qui mène.",
"mp.keep_mine":"Garder celle-ci",
"mp.leaderboard":"Classement",
"mp.leave":"Quitter la session",
"mp.leave_d":"{name} reste sur cet appareil comme une partie à part entière. La session l'oublie, et sa sauvegarde sur le serveur est supprimée.",
"mp.leave_q":"Quitter la session {code} ?",
"mp.left":"Tu as quitté la session. {name} continue ici en solo.",
"mp.link_bad":"Ce lien multijoueur n'a pas marché : il est trop vieux, ou ce réseau n'a jamais sauvegardé dans la session.",
"mp.link_copied":"Lien copié. Ouvre-le sur ton autre appareil.",
"mp.load_newer":"Charger la plus récente",
"mp.loaded_newer":"Sauvegarde plus récente de {name} chargée depuis la session ({date}).",
"mp.loading":"Je demande au serveur…",
"mp.move_device":"Passer sur un autre appareil",
"mp.move_note":"Ouvre ce lien sur ton autre téléphone ou ordinateur pour continuer ce réseau là-bas. C'est l'appareil qui sauvegarde en dernier qui gagne.",
"mp.move_warn":"Quiconque a ce lien peut jouer à ta place. Garde-le pour toi.",
"mp.moved_on_elsewhere":"<b>Cette session a avancé ailleurs.</b> Ton réseau a été joué sur un autre appareil depuis. Charge cette sauvegarde, ou garde celle-ci et écrase l'autre.",
"mp.multiplayer":"Multijoueur",
"mp.n_customers":{"one":"{n} client","other":"{n} clients"},
"mp.n_pops":{"one":"{n} POP","other":"{n} POP"},
"mp.no_card":"n'a pas encore fini de journée",
"mp.no_newer":"La session n'a pas de sauvegarde plus récente de {name}. Celle-ci reste, et part au serveur à la prochaine sauvegarde.",
"mp.not_in_session":"Ce réseau n'est plus dans sa session. Il continue ici en solo.",
"mp.play_with_friends":"Jouer avec des amis",
"mp.save_unreadable":"La sauvegarde de ce réseau dans la session est illisible. On continue avec celle d'ici.",
"mp.say":"Dis quelque chose",
"mp.send":"Envoyer",
"mp.server_away":"Le serveur multijoueur est absent. Ton réseau continue ici et se met à jour à son retour.",
"mp.session":"Session multijoueur",
"mp.session_code":"Session {code}",
"mp.session_live":"<b>La session {code} est lancée.</b> Partage le code : qui la rejoint construit dans le même monde.",
"mp.session_title":"Nom de la session (facultatif)",
"mp.share_line":"Rejoins ma session Series of Tubes {code} : {url}",
"mp.share_note":"Tes amis rejoignent depuis l'écran d'accueil : Multijoueur, puis ce code.",
"mp.slow_down":"Doucement : une ligne par seconde.",
"mp.start_a_session":"Lancer une session",
"mp.talking":"Je parle au serveur…",
"mp.welcome_device":"<b>{name}</b> est passé sur cet appareil. Bon retour dans la session {code}.",
"mp.you":"toi",
"networks.a_mobile_network_named_after_the":"Un réseau mobile qui porte le nom du bruit d’un toast. Tchin-tchin à chaque antenne 5G.", "networks.a_mobile_network_named_after_the":"Un réseau mobile qui porte le nom du bruit d’un toast. Tchin-tchin à chaque antenne 5G.",
"networks.a_spanish_carrier_starring_in_every":"Un opérateur espagnol en vedette sur chaque marché d’Amérique latine, au moins jusqu’à ce qu’il revende le suivant.", "networks.a_spanish_carrier_starring_in_every":"Un opérateur espagnol en vedette sur chaque marché d’Amérique latine, au moins jusqu’à ce qu’il revende le suivant.",
"networks.a_tiny_telco_in_a_country":"Un tout petit opérateur dans un pays où les câbles du monde entier touchent terre. Tarifs à l’avenant.", "networks.a_tiny_telco_in_a_country":"Un tout petit opérateur dans un pays où les câbles du monde entier touchent terre. Tarifs à l’avenant.",

View file

@ -3083,6 +3083,65 @@
"modal_and_names.the_real_thing_follow_a_packet":"La versione vera: segui un pacchetto dal Wi-Fi alla fibra sottomarina.", "modal_and_names.the_real_thing_follow_a_packet":"La versione vera: segui un pacchetto dal Wi-Fi alla fibra sottomarina.",
"modals.lay_your_own_subsea_cable":"Posa il tuo cavo sottomarino…", "modals.lay_your_own_subsea_cable":"Posa il tuo cavo sottomarino…",
"modals.your_own_subsea_cable_level_n":"Il tuo cavo sottomarino <small>livello {n} o Tier 1</small>", "modals.your_own_subsea_cable_level_n":"Il tuo cavo sottomarino <small>livello {n} o Tier 1</small>",
"mp.code":"Codice della sessione",
"mp.copy_link":"Copia il link",
"mp.door_d":"Un solo mondo, le reti dei tuoi amici accanto alla tua: condividi un codice e corri verso il Tier 1.",
"mp.err_code":"Un codice di sessione ha sei lettere e cifre, tipo K7Q-2XD.",
"mp.err_full":"Quella sessione è piena: tutti i posti sono occupati.",
"mp.err_no_session":"Non c'è nessuna sessione con quel codice.",
"mp.err_offline":"Il server multigiocatore non è raggiungibile adesso. Riprova tra un attimo.",
"mp.err_refused":"Il server non l'ha accettato. Prova un altro nome per la rete.",
"mp.err_server_full":"Il server non accetta nuove sessioni in questo momento.",
"mp.err_slow":"Troppi tentativi da qui. Aspetta un po' e riprova.",
"mp.feed":"Bacheca",
"mp.feed_empty":"Ancora niente. Saluta!",
"mp.feed_join":"{name} è entrato nella sessione.",
"mp.feed_leave":"{name} ha lasciato la sessione.",
"mp.feed_t1":"Anche {name} è Tier 1.",
"mp.feed_t1first":"{name} è il primo Tier 1 di questa sessione!",
"mp.feed_t2":"{name} è arrivato a Tier 2.",
"mp.intro":"Ognuno costruisce la propria rete nello stesso mondo, dallo stesso giorno 0 e con le stesse regole. Classifica e bacheca mostrano chi è in testa.",
"mp.join":"Entra",
"mp.join_a_session":"Entra in una sessione",
"mp.join_note":"Il mondo e le regole li sceglie chi ha avviato la sessione, e il numero di AS te lo dà la sessione.",
"mp.joined":"<b>Sei entrato nella sessione {code}.</b> Apri la sessione per vedere chi è in testa.",
"mp.keep_mine":"Tieni questa",
"mp.leaderboard":"Classifica",
"mp.leave":"Lascia la sessione",
"mp.leave_d":"{name} resta su questo dispositivo come partita a sé. La sessione se ne dimentica e il suo salvataggio sul server viene cancellato.",
"mp.leave_q":"Lasciare la sessione {code}?",
"mp.left":"Hai lasciato la sessione. {name} continua qui per conto suo.",
"mp.link_bad":"Quel link multigiocatore non ha funzionato: è vecchio, oppure quella rete non ha mai salvato nella sessione.",
"mp.link_copied":"Link copiato. Aprilo sull'altro dispositivo.",
"mp.load_newer":"Carica quello più recente",
"mp.loaded_newer":"Caricato dalla sessione il salvataggio più recente di {name} ({date}).",
"mp.loading":"Chiedo al server…",
"mp.move_device":"Passa a un altro dispositivo",
"mp.move_note":"Apri questo link sull'altro telefono o computer per continuare lì con questa rete. Vince il dispositivo che salva per ultimo.",
"mp.move_warn":"Chiunque abbia questo link può giocare al posto tuo. Tienilo per te.",
"mp.moved_on_elsewhere":"<b>Questa sessione è andata avanti altrove.</b> Da allora la tua rete è stata giocata su un altro dispositivo. Carica quel salvataggio, oppure tieni questo e sovrascrivilo.",
"mp.multiplayer":"Multigiocatore",
"mp.n_customers":{"one":"{n} cliente","other":"{n} clienti"},
"mp.n_pops":{"one":"{n} POP","other":"{n} POP"},
"mp.no_card":"non ha ancora finito un giorno",
"mp.no_newer":"La sessione non ha un salvataggio più recente di {name}. Resta questo, che andrà al server al prossimo salvataggio.",
"mp.not_in_session":"Questa rete non è più nella sua sessione. Continua qui per conto suo.",
"mp.play_with_friends":"Gioca con gli amici",
"mp.save_unreadable":"Non si riesce a leggere il salvataggio di questa rete nella sessione. Si continua con quello qui.",
"mp.say":"Scrivi qualcosa",
"mp.send":"Invia",
"mp.server_away":"Il server multigiocatore non risponde. La tua rete continua a giocare qui e si rimette in pari quando torna.",
"mp.session":"Sessione multigiocatore",
"mp.session_code":"Sessione {code}",
"mp.session_live":"<b>La sessione {code} è partita.</b> Condividi il codice: chi entra costruisce nello stesso mondo.",
"mp.session_title":"Nome della sessione (facoltativo)",
"mp.share_line":"Entra nella mia sessione di Series of Tubes {code}: {url}",
"mp.share_note":"Gli amici entrano dalla schermata iniziale: Multigiocatore, poi questo codice.",
"mp.slow_down":"Piano: una riga al secondo.",
"mp.start_a_session":"Avvia una sessione",
"mp.talking":"Parlo con il server…",
"mp.welcome_device":"<b>{name}</b> è passata su questo dispositivo. Bentornato nella sessione {code}.",
"mp.you":"tu",
"networks.a_mobile_network_named_after_the":"Una rete mobile che porta il nome del suono di un brindisi. Cin cin a ogni antenna 5G.", "networks.a_mobile_network_named_after_the":"Una rete mobile che porta il nome del suono di un brindisi. Cin cin a ogni antenna 5G.",
"networks.a_spanish_carrier_starring_in_every":"Un carrier spagnolo protagonista in ogni mercato latinoamericano, almeno finché non vende il prossimo.", "networks.a_spanish_carrier_starring_in_every":"Un carrier spagnolo protagonista in ogni mercato latinoamericano, almeno finché non vende il prossimo.",
"networks.a_tiny_telco_in_a_country":"Una piccola telco in un paese dove approdano i cavi di mezzo mondo. Prezzi in proporzione.", "networks.a_tiny_telco_in_a_country":"Una piccola telco in un paese dove approdano i cavi di mezzo mondo. Prezzi in proporzione.",

View file

@ -3083,6 +3083,65 @@
"modal_and_names.the_real_thing_follow_a_packet":"A coisa de verdade: siga um pacote do Wi-Fi até a fibra submarina.", "modal_and_names.the_real_thing_follow_a_packet":"A coisa de verdade: siga um pacote do Wi-Fi até a fibra submarina.",
"modals.lay_your_own_subsea_cable":"Lançar seu próprio cabo submarino…", "modals.lay_your_own_subsea_cable":"Lançar seu próprio cabo submarino…",
"modals.your_own_subsea_cable_level_n":"Seu próprio cabo submarino <small>nível {n} ou Tier 1</small>", "modals.your_own_subsea_cable_level_n":"Seu próprio cabo submarino <small>nível {n} ou Tier 1</small>",
"mp.code":"Código da sessão",
"mp.copy_link":"Copiar o link",
"mp.door_d":"Um só mundo, as redes dos seus amigos ao lado da sua: compartilhe um código e corra para o Tier 1.",
"mp.err_code":"Um código de sessão tem seis letras e números, como K7Q-2XD.",
"mp.err_full":"Essa sessão está cheia: todas as vagas já estão ocupadas.",
"mp.err_no_session":"Não existe sessão com esse código.",
"mp.err_offline":"Não dá para falar com o servidor multijogador agora. Tente de novo daqui a pouco.",
"mp.err_refused":"O servidor não aceitou. Tente outro nome de rede.",
"mp.err_server_full":"O servidor não está aceitando sessões novas agora.",
"mp.err_slow":"Tentativas demais daqui. Espere um pouco e tente de novo.",
"mp.feed":"Mural",
"mp.feed_empty":"Nada ainda. Diga oi!",
"mp.feed_join":"{name} entrou na sessão.",
"mp.feed_leave":"{name} saiu da sessão.",
"mp.feed_t1":"{name} também é Tier 1.",
"mp.feed_t1first":"{name} é o primeiro Tier 1 desta sessão!",
"mp.feed_t2":"{name} chegou a Tier 2.",
"mp.intro":"Cada um constrói a própria rede no mesmo mundo, a partir do mesmo dia 0 e com as mesmas regras. O ranking e o mural mostram quem está na frente.",
"mp.join":"Entrar",
"mp.join_a_session":"Entrar numa sessão",
"mp.join_note":"O mundo e as regras vêm de quem começou a sessão, e a sessão te dá o seu número de AS.",
"mp.joined":"<b>Você entrou na sessão {code}.</b> Abra a sessão para ver quem está na frente.",
"mp.keep_mine":"Ficar com esta",
"mp.leaderboard":"Ranking",
"mp.leave":"Sair da sessão",
"mp.leave_d":"{name} fica neste dispositivo como um jogo próprio. A sessão se esquece dela, e o jogo salvo dela no servidor é apagado.",
"mp.leave_q":"Sair da sessão {code}?",
"mp.left":"Você saiu da sessão. {name} continua aqui por conta própria.",
"mp.link_bad":"Esse link multijogador não funcionou: é antigo, ou essa rede nunca salvou na sessão.",
"mp.link_copied":"Link copiado. Abra no seu outro dispositivo.",
"mp.load_newer":"Carregar o mais recente",
"mp.loaded_newer":"Carregado da sessão o jogo salvo mais recente de {name} ({date}).",
"mp.loading":"Perguntando ao servidor…",
"mp.move_device":"Passar para outro dispositivo",
"mp.move_note":"Abra este link no seu outro celular ou computador para continuar com esta rede lá. Vale o dispositivo que salvar por último.",
"mp.move_warn":"Qualquer um com este link pode jogar como você. Guarde só para você.",
"mp.moved_on_elsewhere":"<b>Esta sessão seguiu em outro lugar.</b> Desde então sua rede foi jogada em outro dispositivo. Carregue aquele jogo salvo, ou fique com este e sobrescreva o outro.",
"mp.multiplayer":"Multijogador",
"mp.n_customers":{"one":"{n} cliente","other":"{n} clientes"},
"mp.n_pops":{"one":"{n} POP","other":"{n} POPs"},
"mp.no_card":"ainda não terminou nenhum dia",
"mp.no_newer":"A sessão não tem um jogo salvo mais recente de {name}. Este fica e vai para o servidor no próximo salvamento.",
"mp.not_in_session":"Esta rede não está mais na sua sessão. Ela continua jogando aqui por conta própria.",
"mp.play_with_friends":"Jogar com amigos",
"mp.save_unreadable":"Não deu para ler o jogo salvo desta rede na sessão. Seguimos com o daqui.",
"mp.say":"Diga algo",
"mp.send":"Enviar",
"mp.server_away":"O servidor multijogador sumiu. Sua rede continua jogando aqui e se atualiza quando ele voltar.",
"mp.session":"Sessão multijogador",
"mp.session_code":"Sessão {code}",
"mp.session_live":"<b>A sessão {code} está no ar.</b> Compartilhe o código: quem entrar constrói no mesmo mundo.",
"mp.session_title":"Nome da sessão (opcional)",
"mp.share_line":"Entre na minha sessão de Series of Tubes {code}: {url}",
"mp.share_note":"Os amigos entram pela tela inicial: Multijogador, depois este código.",
"mp.slow_down":"Calma: uma linha por segundo.",
"mp.start_a_session":"Começar uma sessão",
"mp.talking":"Falando com o servidor…",
"mp.welcome_device":"<b>{name}</b> passou para este dispositivo. Bem-vindo de volta à sessão {code}.",
"mp.you":"você",
"networks.a_mobile_network_named_after_the":"Uma rede móvel com nome de brinde. Tim-tim para cada torre 5G.", "networks.a_mobile_network_named_after_the":"Uma rede móvel com nome de brinde. Tim-tim para cada torre 5G.",
"networks.a_spanish_carrier_starring_in_every":"Uma operadora espanhola estrelando em todo mercado latino-americano, pelo menos até vender o próximo.", "networks.a_spanish_carrier_starring_in_every":"Uma operadora espanhola estrelando em todo mercado latino-americano, pelo menos até vender o próximo.",
"networks.a_tiny_telco_in_a_country":"Uma operadora minúscula num país onde os cabos do mundo chegam à terra. Os preços acompanham.", "networks.a_tiny_telco_in_a_country":"Uma operadora minúscula num país onde os cabos do mundo chegam à terra. Os preços acompanham.",

View file

@ -15,6 +15,8 @@ self.addEventListener('activate', (e) => {
self.addEventListener('fetch', (e) => { self.addEventListener('fetch', (e) => {
const req = e.request; const req = e.request;
if (req.method !== 'GET') return; if (req.method !== 'GET') return;
// Calls with a player's credentials, or that ask not to be cached (a self-hosted copy's multiplayer server), are never cached.
if (req.cache === 'no-store' || req.headers.has('authorization')) return;
const url = new URL(req.url); const url = new URL(req.url);
// The update check must always ask the network. // The update check must always ask the network.
if (url.origin === location.origin && url.pathname === '/version.json') return; if (url.origin === location.origin && url.pathname === '/version.json') return;

View file

@ -600,6 +600,7 @@ const API_WHY={
time:'use advance to move time, or wait when the clock runs on its own',start:'use new_game',files:'use load_save or export_save', time:'use advance to move time, or wait when the clock runs on its own',start:'use new_game',files:'use load_save or export_save',
slots:'saved networks in browser storage are not part of this game',prefs:'device and player settings are not part of the game', slots:'saved networks in browser storage are not part of this game',prefs:'device and player settings are not part of the game',
browser:'it needs the browser itself (a share sheet, the clipboard, an install prompt or a reload)', browser:'it needs the browser itself (a share sheet, the clipboard, an install prompt or a reload)',
mp:'multiplayer talks to a session server for the player: only the player starts, joins, chats in or leaves a session',
}; };
const API_DENY={ const API_DENY={
speed:'time',phonePlay:'time',phoneSpeed:'time', speed:'time',phonePlay:'time',phoneSpeed:'time',
@ -607,5 +608,6 @@ const API_DENY={
exportSave:'files',importGo:'files',importPick:'files',slotExport:'files', exportSave:'files',importGo:'files',importPick:'files',slotExport:'files',
slotBack:'slots',slotDel:'slots',slotDelGo:'slots',slotMenu:'slots',slotRetry:'slots',slotSpace:'slots',slotSwitch:'slots',slotTake:'slots', slotBack:'slots',slotDel:'slots',slotDelGo:'slots',slotMenu:'slots',slotRetry:'slots',slotSpace:'slots',slotSwitch:'slots',slotTake:'slots',
animSet:'prefs',langSet:'prefs',mapSet:'prefs',menu:'prefs',mute:'prefs',prefSet:'prefs',settings:'prefs',settingsClose:'prefs',soundSet:'prefs',vpSet:'prefs', animSet:'prefs',langSet:'prefs',mapSet:'prefs',menu:'prefs',mute:'prefs',prefSet:'prefs',settings:'prefs',settingsClose:'prefs',soundSet:'prefs',vpSet:'prefs',
mpDoor:'mp',mpBack:'mp',mpStart:'mp',mpJoin:'mp',mpOpen:'mp',mpShare:'mp',mpCopyLink:'mp',mpChat:'mp',mpLeaveAsk:'mp',mpLeave:'mp',mpNewer:'mp',mpKeep:'mp',
install:'browser',share:'browser',shareDl:'browser',shareGo:'browser',traceCopy:'browser',updateLater:'browser',updateNow:'browser',wsShare:'browser',pzShare:'browser', install:'browser',share:'browser',shareDl:'browser',shareGo:'browser',traceCopy:'browser',updateLater:'browser',updateNow:'browser',wsShare:'browser',pzShare:'browser',
}; };

View file

@ -62,6 +62,7 @@ const API_STATE_DOC={
core:{type:'map',doc:'Your backbone technology: lv bought, the level it runs at, the interop lab.'}, core:{type:'map',doc:'Your backbone technology: lv bought, the level it runs at, the interop lab.'},
ddosAuto:{type:'map',doc:'The NOC\'s auto-mitigation switches: rtbh and scrub.'}, ddosAuto:{type:'map',doc:'The NOC\'s auto-mitigation switches: rtbh and scrub.'},
popStd:{type:'map',doc:'The build standard, or null for none. g router model (an RG index), rt routers, then only the targets that are set: site2, gen (true), lag (2 or 4 members), split, ix (true), pni (2 or 3 cities per network), sys (roadm, cl), opt (fast), wv (an LT index). New POPs get g, rt, site2 and gen at once; the std standing order and bstdApply bring the rest up.'}, popStd:{type:'map',doc:'The build standard, or null for none. g router model (an RG index), rt routers, then only the targets that are set: site2, gen (true), lag (2 or 4 members), split, ix (true), pni (2 or 3 cities per network), sys (roadm, cl), opt (fast), wv (an LT index). New POPs get g, rt, site2 and gen at once; the std standing order and bstdApply bring the rest up.'},
mp:{type:'map',doc:'Multiplayer, only in a self-hosted copy with a session server: the session code, your player id, the AS number and seed the session gave you, its rules preset, your colour, its title and the last save number the server holds; null in every other game.'},
demo:{type:'map',doc:'Vendor demo units on order, by "kind:id" → ready day.'}, demo:{type:'map',doc:'Vendor demo units on order, by "kind:id" → ready day.'},
seatOff:{type:'map',doc:'The pending consortium-cable seat offer: landings, km, name, expiry day.'}, seatOff:{type:'map',doc:'The pending consortium-cable seat offer: landings, km, name, expiry day.'},
monkey:{type:'map',doc:'The chaos monkey: next visit day, whether it is in your network now, days left, whether anyone noticed.'}, monkey:{type:'map',doc:'The chaos monkey: next visit day, whether it is in your network now, days left, whether anyone noticed.'},

View file

@ -7,6 +7,9 @@ const RELEASE_NOTES=/*__RELEASE_NOTES__*/[];
// A big release's story, shown in full in "What's new" (paragraphs; **bold** allowed). Empty for most releases. // A big release's story, shown in full in "What's new" (paragraphs; **bold** allowed). Empty for most releases.
const RELEASE_STORY=/*__RELEASE_STORY__*/[]; const RELEASE_STORY=/*__RELEASE_STORY__*/[];
const IS_DEV=APP_VERSION.startsWith('__'); const IS_DEV=APP_VERSION.startsWith('__');
// Multiplayer (docs/MULTIPLAYER.md): the path of a self-hosted copy's session server, stamped by MP_API=/api/mp npm run build.
// Empty, as in every plain build (and on seriesoftub.es), multiplayer stays off: no door, no requests.
const MP_API=/*__MP_API__*/'';
// Only report from the real site; previews, localhost and the Claude viewer stay silent. // Only report from the real site; previews, localhost and the Claude viewer stay silent.
const ANALYTICS={host:/(^|\.)seriesoftub\.es$/.test(location.hostname)&&!/[?&]noc=/.test(location.search)?'https://stats.seriesoftub.es':'',site:'seriesoftub.es'}; const ANALYTICS={host:/(^|\.)seriesoftub\.es$/.test(location.hostname)&&!/[?&]noc=/.test(location.search)?'https://stats.seriesoftub.es':'',site:'seriesoftub.es'};
(function(){ (function(){

View file

@ -44,6 +44,8 @@ function weekly(){const [y,w]=pzWeekKey(new Date()).split('-W').map(Number);let
const scnRule=k=>!!(S&&S.scn&&S.scn.rules&&S.scn.rules[k]); const scnRule=k=>!!(S&&S.scn&&S.scn.rules&&S.scn.rules[k]);
function scnHof(){try{return JSON.parse(localStorage.getItem('sot-scn')||'{}')||{};}catch(e){return {};}} function scnHof(){try{return JSON.parse(localStorage.getItem('sot-scn')||'{}')||{};}catch(e){return {};}}
function beginGame(nm,city,o={}){if(needPitch()&&!UI.pitched){UI.pendGame=[nm,city,o];openModal(pitchHtml(true));return;}if(pzOn())pzLeave();slotLeave();slotNew();newGame(nm,city);{const a=+(UI.asnTxt||UI.asnSug||0);if(asnOk(a))S.asn=a;UI.asnSug=null;}S.mode=o.mode||'normal'; function beginGame(nm,city,o={}){if(needPitch()&&!UI.pitched){UI.pendGame=[nm,city,o];openModal(pitchHtml(true));return;}if(pzOn())pzLeave();slotLeave();slotNew();newGame(nm,city);{const a=+(UI.asnTxt||UI.asnSug||0);if(asnOk(a))S.asn=a;UI.asnSug=null;}S.mode=o.mode||'normal';
// A multiplayer session (89-multiplayer.js): the server's AS number, and its seed, so every player starts in the same world.
if(o.mp&&S.mode==='normal'){const m=o.mp;S.mp={code:m.code,pid:m.pid,asn:m.asn,seed:m.seed,preset:m.preset,color:m.color,title:m.title,seq:0};S.asn=m.asn;S.rng=m.seed|0;}
// The rules are picked here and locked for the life of the network. Scenarios run on On-call plus their own rules. // The rules are picked here and locked for the life of the network. Scenarios run on On-call plus their own rules.
{const pr=o.scn?'oncall':S.mode==='sandbox'?'sandbox':S.mode==='puzzle'?'puzzle':own(PRESETS,o.preset)&&o.preset!=='sandbox'&&o.preset!=='puzzle'?o.preset:'oncall';S.rules=makeRules(pr,o.scn?{}:o.rules);} {const pr=o.scn?'oncall':S.mode==='sandbox'?'sandbox':S.mode==='puzzle'?'puzzle':own(PRESETS,o.preset)&&o.preset!=='sandbox'&&o.preset!=='puzzle'?o.preset:'oncall';S.rules=makeRules(pr,o.scn?{}:o.rules);}
if(S.mode==='sandbox'){S.cash=1e9;S.lvl=LEVELS.length;if(!chaosMul()){S.nextFail=1e9;S.nextEvent=1e9;}} if(S.mode==='sandbox'){S.cash=1e9;S.lvl=LEVELS.length;if(!chaosMul()){S.nextFail=1e9;S.nextEvent=1e9;}}
@ -55,4 +57,5 @@ function beginGame(nm,city,o={}){if(needPitch()&&!UI.pitched){UI.pendGame=[nm,ci
track('game_new');UI.started=true;closeModal();compute();cam.x=CITY[city].x;cam.y=CITY[city].y;cam.z=innerWidth<760?1.1:1.4;selectCity(city); track('game_new');UI.started=true;closeModal();compute();cam.x=CITY[city].x;cam.y=CITY[city].y;cam.z=innerWidth<760?1.1:1.4;selectCity(city);
toast(S.scn?`<b>${esc(S.scn.name)}</b><br>${o.scn.goal?esc(o.scn.goal)+'.':tr('common.serve_as_much_traffic_as_you')} ${tr('scenarios.you_have_n_days',{n:S.scn.days})}`:S.mode==='sandbox'?(chaosMul()?tr('scenarios.sandbox_mode_a_billion_dollars_chaos',{chaos:CHAOS[rule('chaos')].n}):tr('scenarios.sandbox_mode_a_billion_dollars_every')):tr('scenarios.welcome_name_the_ripe_ncc_assigned',{name:esc(nm),asn:S.asn,city:CITY[city].name}),'goal'); toast(S.scn?`<b>${esc(S.scn.name)}</b><br>${o.scn.goal?esc(o.scn.goal)+'.':tr('common.serve_as_much_traffic_as_you')} ${tr('scenarios.you_have_n_days',{n:S.scn.days})}`:S.mode==='sandbox'?(chaosMul()?tr('scenarios.sandbox_mode_a_billion_dollars_chaos',{chaos:CHAOS[rule('chaos')].n}):tr('scenarios.sandbox_mode_a_billion_dollars_every')):tr('scenarios.welcome_name_the_ripe_ncc_assigned',{name:esc(nm),asn:S.asn,city:CITY[city].name}),'goal');
// A Normal game asks for its charter first; the tutorial starts once it is signed. // A Normal game asks for its charter first; the tutorial starts once it is signed.
renderAll();save();if(!S.scn&&S.mode!=='sandbox'&&S.mode!=='puzzle'){charterAsk();if(!$('modal').hidden&&$('modal').className==='charter')UI.tutLater=true;else tutorialStart();}} renderAll();if(S.mp)mpStarted(o.mp);save();if(!S.scn&&S.mode!=='sandbox'&&S.mode!=='puzzle'){charterAsk();if(!$('modal').hidden&&$('modal').className==='charter')UI.tutLater=true;else tutorialStart();}
if(S.mp)mpStartTell();}

View file

@ -1,6 +1,6 @@
function newGame(name,home){ function newGame(name,home){
S={v:1,name,asn:200000+Math.floor(_rand()*15000),home,day:0,cash:START_CASH, S={v:1,name,asn:200000+Math.floor(_rand()*15000),home,day:0,cash:START_CASH,
ltv:2,t1v:4,auV:1,calV:1,pieV:1,pie:null,ops:opsNew(),slAuto:slAutoNew(),achP:{},seen:NETS.map(n=>n.id),spares:{},pops:{[home]:{day:0,bb:null,boost:0,down:0,routers:1,gen:false}},links:[],nni:[],transit:[],ixp:{},rs:{},peers:{},pni:[],caches:[],biz:[],offers:[],myIx:{},pairMet:{}, ltv:2,t1v:4,auV:1,calV:1,pieV:1,pie:null,ops:opsNew(),slAuto:slAutoNew(),achP:{},seen:NETS.map(n=>n.id),spares:{},pops:{[home]:{day:0,bb:null,boost:0,down:0,routers:1,gen:false}},links:[],nni:[],transit:[],ixp:{},rs:{},peers:{},pni:[],caches:[],biz:[],offers:[],myIx:{},pairMet:{},
done:{},inc:[],fleet:{},ev:{ddosMore:[]},ddosStarts:[],priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},cnLic:{state:'none'},scrubs:[],scrubMode:'always',ddosAuto:{rtbh:false,scrub:true},capDeal:null,core:{lv:0,run:0},popStd:null,won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,ppol:'open',pdesk:null,pdeskRep:null,hw:{},rules:makeRules('oncall'),charter:'global',chartSet:false,demo:{},seatOff:null,solWon:0,monkey:{next:null,on:0}}; done:{},inc:[],fleet:{},ev:{ddosMore:[]},ddosStarts:[],priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},cnLic:{state:'none'},scrubs:[],scrubMode:'always',ddosAuto:{rtbh:false,scrub:true},capDeal:null,core:{lv:0,run:0},popStd:null,won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,ppol:'open',pdesk:null,pdeskRep:null,hw:{},rules:makeRules('oncall'),charter:'global',chartSet:false,demo:{},seatOff:null,solWon:0,monkey:{next:null,on:0},mp:null};
} }

View file

@ -0,0 +1,180 @@
/* ================= MULTIPLAYER (docs/MULTIPLAYER.md) =================
Only in a self-hosted copy built with MP_API (scripts/mp-server.js on the same origin); with MP_API empty nothing here
runs. Players share a session by a six-character code: each builds their own network in the same world (one seed,
one rules preset), each network's save is also kept on the server (so it can move to another device), and a small
public card per player feeds the session's leaderboard and feed. The game itself stays local and keeps playing
when the server is away. S.mp = null | {code, pid, asn, seed, preset, color, title, seq}; the secret token is never in
S (saves get exported and shared): it lives in this browser's storage, sot-mp:<code>:<pid>. */
const MP_CODE=/^[0-9A-HJKMNP-TV-Z]{6}$/,MP_PID=/^[a-z0-9]{8}$/,MP_TOK=/^[0-9a-f]{64}$/,MP_COL=/^#[0-9a-f]{6}$/i;
// Pushes: a new game day, at most every 15 s; the roster every 5 s only while the session panel is open. A keepalive
// request (the page is going away) carries at most 64 KiB, so only a small save goes with it (MP_KEEP bytes of request,
// with room to spare), else the card alone.
const MP_GAP=15000,MP_POLL=5000,MP_KEEP=63000,MP_GZ=32768,MP_FEED=['join','leave','t2','t1','t1first','chat'];
/* cur: the push on its way ({cut, ac}); staleSeq: the server's number when it said it has a newer save; sig: what the
last push that landed looked like (mpSig); force: the player chose to keep this save; now: push at the next save. */
const MP={roster:null,day:-1,last:-1e9,busy:false,cur:null,stale:false,staleSeq:0,gone:false,leaving:false,wait:0,fails:0,told:false,poll:null,sig:'',force:false,now:false};
const mpIs=()=>!!(MP_API&&S&&S.mp&&!pzOn());
const mpShow=c=>c.slice(0,3)+'-'+c.slice(3);
// "k7q-2xd", "K7Q 2XD", even "k7q2xo": the code, or null. I, L and O read as 1, 1 and 0 (Crockford's base32).
function mpNorm(s){if(typeof s!=='string'||s.length>20)return null;const c=s.toUpperCase().replace(/[\s-]/g,'').replace(/[IL]/g,'1').replace(/O/g,'0');return MP_CODE.test(c)?c:null;}
const mpPath=(m,p)=>'/sessions/'+m.code+(p||'');
const mpTokK=(c,p)=>'sot-mp:'+c+':'+p;
function mpTok(m){if(!m||!MP_CODE.test(m.code)||!MP_PID.test(m.pid))return null;const t=lsGet(mpTokK(m.code,m.pid));return typeof t==='string'&&MP_TOK.test(t)?t:null;}
function mpTokSet(c,p,t){try{if(t==null)localStorage.removeItem(mpTokK(c,p));else localStorage.setItem(mpTokK(c,p),t);}catch(e){}}
// The catalog's own AS numbers in the server's range: the server hands out one nobody on the map uses.
const mpAvoid=()=>NETS.filter(n=>n.asn>=200000&&n.asn<=214999).map(n=>n.asn).slice(0,64);
function mpSanitize(s){const m=s.mp;
if(!m||typeof m!=='object'||Array.isArray(m)||!MP_CODE.test(m.code)||!MP_PID.test(m.pid)||s.mode!=='normal'){s.mp=null;return;}
s.mp={code:m.code,pid:m.pid,asn:int(m.asn,200000,214999,200000),seed:int(m.seed,-2147483648,2147483647,0),preset:NORMAL_PRESETS.includes(m.preset)?m.preset:'oncall',
color:typeof m.color==='string'&&MP_COL.test(m.color)?m.color:'#ff4f9a',title:typeof m.title==='string'?m.title.slice(0,40):'',seq:int(m.seq,0,1e15,0)};}
// What the server said when a session started or someone joined: checked before it becomes S.mp.
function mpJoinOk(j){if(!j||typeof j!=='object'||!MP_CODE.test(j.code)||!MP_PID.test(j.pid)||typeof j.token!=='string'||!MP_TOK.test(j.token)||!Number.isInteger(j.seed)||!Number.isInteger(j.asn)||j.asn<200000||j.asn>214999)return null;
return {code:j.code,pid:j.pid,token:j.token,asn:j.asn,seed:j.seed|0,preset:NORMAL_PRESETS.includes(j.preset)?j.preset:'oncall',color:typeof j.color==='string'&&MP_COL.test(j.color)?j.color:'#ff4f9a',title:typeof j.title==='string'?j.title.slice(0,40):''};}
/* One call to the session server. Same origin, never cached; a call that takes over 15 s gives up. Rejects with
{status, j} on an HTTP error, so callers can tell "no such session" from "server away". */
function mpReq(method,p,body,o={}){
if(!MP_API||typeof fetch!=='function')return Promise.reject(Object.assign(new Error('off'),{status:0}));
const h={};if(body!==undefined)h['content-type']='application/json';
// o.tok: a token not stored yet (a #mp= link's, until the server takes it).
if(o.auth){const t=o.tok||mpTok(o.auth);if(!t)return Promise.reject(Object.assign(new Error('no token'),{status:401}));h.authorization='Bearer '+o.auth.pid+'.'+t;}
const ac=o.keep?null:o.ac||(typeof AbortController==='function'?new AbortController():null),tm=ac?setTimeout(()=>ac.abort(),15000):0;
let f;try{f=fetch(MP_API+p,{method,headers:h,body:body===undefined?undefined:typeof body==='string'?body:JSON.stringify(body),cache:'no-store',credentials:'same-origin',...(o.keep?{keepalive:true}:{}),...(ac?{signal:ac.signal}:{})});}
catch(e){clearTimeout(tm);return Promise.reject(Object.assign(e,{status:0}));}
return Promise.resolve(f).then(r=>Promise.resolve(r.json?r.json():null).catch(()=>null).then(j=>{clearTimeout(tm);if(!r.ok)throw Object.assign(new Error(j&&j.error||'HTTP '+r.status),{status:r.status,j});return j;}),
e=>{clearTimeout(tm);throw Object.assign(e||new Error('failed'),{status:e&&e.status||0});});}
/* The public card: what the leaderboard shows (and what peering between players will need later). */
function mpCard(){let t1=false,tl='Tier 3';try{t1=isTier1();tl=tierLabel();}catch(e){}
const tier=tl==='Tier 1'?'t1':tl==='Tier 2'?'t2':'t3',pairs=new Map();
for(const l of S.links){if(l.ready>S.day)continue;const k=l.a<l.b?l.a+'|'+l.b:l.b+'|'+l.a;let g=0;try{g=hopG(l)||0;}catch(e){}pairs.set(k,(pairs.get(k)||0)+g);}
const links=[...pairs].sort((a,b)=>b[1]-a[1]).slice(0,300).map(([k,g])=>{const [a,b]=k.split('|');return [a,b,Math.round(g)];});
const served=R.served||0;
return {day:S.day,name:S.name,asn:S.asn,tier,t1,lvl:S.lvl||1,pops:Object.keys(S.pops).slice(0,500),links,ix:Object.keys(S.ixp).slice(0,500),transit:[...new Set(S.transit.map(t=>t.net))].slice(0,64),
ppol:ppol(),reach:Math.round((R.reach||0)*1e4)/1e4,peak:Math.round((S.stats.peak||0)*10)/10,served:Math.round(served*10)/10,cust:S.biz.length,rev:Math.round(R.revMo||0),
cashB:S.cash<0?-1:Math.min(20,Math.floor(Math.log10(Math.max(1,S.cash)))),score:(t1?2e9:tier==='t2'?1e9:0)+Math.round(served)};}
/* Other players' data, as it comes back: the same whitelist the server keeps, and every id checked against our own
catalogs. Names and chat stay text: everything that shows them escapes them. */
function mpCardOk(c){if(!c||typeof c!=='object'||Array.isArray(c))return null;
const n=(v,lo,hi)=>{v=+v;return Number.isFinite(v)?Math.min(hi,Math.max(lo,v)):0;},L=(v,ok,max)=>Array.isArray(v)?[...new Set(v.filter(ok))].slice(0,max):[];
return {day:Math.round(n(c.day,0,1e7)),tier:['t1','t2','t3'].includes(c.tier)?c.tier:'t3',t1:c.t1===true,lvl:Math.round(n(c.lvl,0,99)),pops:L(c.pops,isCity,500),
links:(Array.isArray(c.links)?c.links:[]).filter(l=>Array.isArray(l)&&isCity(l[0])&&isCity(l[1])&&l[0]!==l[1]).slice(0,300).map(l=>[l[0],l[1],n(l[2],0,1e7)]),
ix:L(c.ix,isIx,500),transit:L(c.transit,isNet,64),ppol:PPOL.includes(c.ppol)?c.ppol:'open',reach:n(c.reach,0,1),peak:n(c.peak,0,1e9),served:n(c.served,0,1e9),
cust:Math.round(n(c.cust,0,1e7)),rev:n(c.rev,-1e13,1e13),cashB:Math.round(n(c.cashB,-1,20)),score:n(c.score,0,1e15)};}
function mpRosterOk(j){if(!j||typeof j!=='object'||Array.isArray(j)||!Array.isArray(j.players))return null;
const txt=(v,max)=>typeof v==='string'?v.slice(0,max):'';
const players=j.players.filter(p=>p&&typeof p==='object'&&MP_PID.test(p.pid)).slice(0,12).map(p=>({pid:p.pid,name:txt(p.name,32),asn:int(p.asn,0,4294967294,0),
color:typeof p.color==='string'&&MP_COL.test(p.color)?p.color:'#888888',card:mpCardOk(p.card),seen:num(p.seen,0),joined:num(p.joined,0)}));
const feed=(Array.isArray(j.feed)?j.feed:[]).filter(f=>f&&typeof f==='object'&&MP_FEED.includes(f.k)).slice(-100).map(f=>({k:f.k,pid:MP_PID.test(f.pid)?f.pid:'',name:txt(f.name,32),at:num(f.at,0),text:f.k==='chat'?txt(f.text,200):''}));
return {code:MP_CODE.test(j.code)?j.code:'',title:txt(j.title,40),preset:NORMAL_PRESETS.includes(j.preset)?j.preset:'oncall',players,feed};}
// Tier 1 first, then Tier 2, then whoever serves the most traffic; players who never pushed a card last.
const mpTierN=c=>c?(c.t1?3:c.tier==='t2'?2:1):0;
function mpRank(ps){return ps.slice().sort((a,b)=>mpTierN(b.card)-mpTierN(a.card)||(b.card?b.card.served:0)-(a.card?a.card.served:0)||(b.card?b.card.peak:0)-(a.card?a.card.peak:0)||a.joined-b.joined);}
/* ---------- staying in step with the server ---------- */
function mpOk(roster){MP.fails=0;MP.wait=0;if(MP.told)MP.told=false;const r=mpRosterOk(roster);if(r)MP.roster=r;if(MP_API)mpHud();mpPanelUpdate();}
/* The server is away: back off (30 s, 1, 2, 4 min, at most 5), say so once, and keep playing. Too many pushes at once
(429: another one still on its way, or too often; 503 busy: too many uploads on the server right now) is not "away":
wait a little, quietly. The session panel's own refresh (poll) runs every few seconds while it is open: it may say
the server is away, but never stretches the wait. */
function mpFail(e,poll){const st=e&&e.status;
if((st===401||st===404)&&S&&S.mp){MP.gone=true;toast(tr('mp.not_in_session'),'bad',[{l:tr('mp.session'),act:'mpOpen',args:{}}]);return;}
if(st===429||st===503&&e.j&&e.j.busy===true){MP.wait=performance.now()+MP_GAP*2;return;}
if(!poll||!MP.fails){MP.fails++;MP.wait=performance.now()+Math.min(300000,MP_GAP*2**MP.fails);}
if(!MP.told){MP.told=true;toast(tr('mp.server_away'),'bad');}}
const mpHid=()=>MP.leaving||document.visibilityState==='hidden';
// What a save looks like, in a few characters (FNV-1a and the length): a page hidden on the same game day pushes only
// when something changed since the last push.
function mpSig(t){let h=0x811c9dc5;for(let i=0;i<t.length;i++){h^=t.charCodeAt(i);h=Math.imul(h,16777619);}return (h>>>0).toString(36)+'.'+t.length;}
// The request's size in bytes (UTF-8), which is what the keepalive limit counts.
function mpBytes(t){let n=t.length;for(let i=0;i<t.length;i++){const c=t.charCodeAt(i);if(c>127)n+=c>2047&&(c<0xd800||c>0xdfff)?2:1;}return n;}
/* Does this save go to the server too? 1: yes; 2: if it changed since the last push (the page is being hidden, or the
player asked, on the same game day); 0: no. A push goes on a new game day at most every MP_GAP; at once when the page
is hidden or closed, when the player chose to keep this save (MP.force) or asked for it (MP.now). Never mid-day or in
a puzzle: save() returns before then. */
function mpDue(){if(!mpIs()||MP.stale||MP.gone||S.lost)return 0;
const hid=mpHid(),now=performance.now();
// One push at a time, except when the page goes away: that one cuts the one on its way short (mpPush).
if(MP.busy&&!hid)return 0;
const ask=MP.now;MP.now=false;
if(MP.force&&(hid||now>=MP.wait))return 1;
if(S.day===MP.day)return hid||ask?2:0;
return hid||ask||(now-MP.last>=MP_GAP&&now>=MP.wait)?1:0;}
/* save()'s text for a network in a session, and its push when one is due. The number the server will keep it under is
picked before the text is made, so the save here and the one on the server carry the same: reopening this device
then knows the server has nothing newer. A push that fails leaves this one ahead, which the server accepts. */
function mpSave(st){let d=mpDue();if(d===1)S.mp.seq=(S.mp.seq||0)+1;let txt=JSON.stringify(packSave(st));
if(d===2){if(mpSig(txt)===MP.sig)d=0;else{S.mp.seq=(S.mp.seq||0)+1;txt=JSON.stringify(packSave(st));}}
if(d)mpPush(txt);return txt;}
/* Sends that save (it carries S.mp.seq), gzipped when big, with the card. When the page is being hidden or closed it
goes at once, as a keepalive request: the save when the request fits in one, else the card alone. */
function mpPush(txt){if(!mpIs()||MP.stale||MP.gone||S.lost)return;
const m=S.mp,day=S.day,seq=m.seq||0,hid=mpHid(),force=MP.force,me={cut:false,ac:null};let card;try{card=mpCard();}catch(e){card=undefined;}
// A push still on its way while the page goes away with a newer save: that one is cut short, this one goes.
if(MP.cur){MP.cur.cut=true;try{if(MP.cur.ac)MP.cur.ac.abort();}catch(e){}}
MP.cur=me;MP.busy=true;MP.last=performance.now();
const sig=mpSig(txt),body=data=>({seq,at:Date.now(),data,card,...(force?{force:true}:{})});
// Only a save that went counts as this day's push; a card alone does not.
const done=j=>{if(me.cut)return;if(j&&j.seq!==undefined&&S&&S.mp===m){m.seq=Math.max(m.seq||0,int(j.seq,0,1e15,seq));MP.day=day;MP.sig=sig;if(force)MP.force=false;}mpOk(j&&(j.roster||j));};
const bad=e=>{if(me.cut)return;if(e&&e.status===409&&S&&S.mp===m){MP.stale=true;MP.staleSeq=int(e.j&&e.j.seq,0,1e15,seq);mpStaleTell();}else mpFail(e);};
const fin=()=>{if(MP.cur===me){MP.cur=null;MP.busy=false;}};
const send=(p,b,keep)=>{if(me.cut)return;if(!keep&&typeof AbortController==='function')me.ac=new AbortController();
mpReq('PUT',mpPath(m,p),b,{auth:m,keep,ac:me.ac}).then(done,bad).finally(fin);};
if(hid){const b=txt.length<MP_KEEP?JSON.stringify(body(txt)):'';
if(b&&mpBytes(b)<MP_KEEP)send('/save',b,true);
else if(card&&mpBytes(JSON.stringify({card}))<MP_KEEP)send('/card',{card},true);else fin();
return;}
const go=data=>send('/save',body(data),false);
if(txt.length>=MP_GZ&&gzOk())gzip(txt).then(go,()=>go(txt));else go(txt);}
// The page is going away (pagehide comes before save()'s own handler, which then pushes as a keepalive request).
if(MP_API){addEventListener('pagehide',()=>{MP.leaving=true;});addEventListener('pageshow',()=>{MP.leaving=false;});}
function mpStaleTell(){toast(tr('mp.moved_on_elsewhere'),'bad',[{l:tr('mp.load_newer'),act:'mpNewer',args:{}},{l:tr('mp.keep_mine'),act:'mpKeep',args:{}}]);}
// Pushes this network's save now if it changed since the last push (before a link to another device is handed out).
function mpSyncNow(){if(!mpIs())return;MP.now=true;save(true);}
// The server's save text as a game state: unzipped, parsed, and only if it is this very network.
function mpUnpack(data){if(typeof data!=='string')return Promise.reject(new Error('no save'));
return (data.startsWith(GZ)?gunzip(data):Promise.resolve(data)).then(t=>JSON.parse(t));}
function mpSaveOk(s,m){if(!s||typeof s!=='object'||s.v!==1||typeof s.day!=='number'||typeof s.cash!=='number'||!s.pops||typeof s.pops!=='object'||!Array.isArray(s.links)||s.lost)return false;
if(!Object.keys(s.pops).every(isCity))return false;return !!(s.mp&&s.mp.code===m.code&&s.mp.pid===m.pid);}
/* Opening a network of a session: if another device played on and pushed a newer save, that one is loaded instead.
Nothing is pushed until the answer is in. */
function mpResume(){if(!mpIs())return;const m=S.mp;mpReset({day:S.day,last:performance.now(),busy:true});mpHud();
// A push of the page going away meanwhile is its own: only an answer to this question frees the next one.
const free=()=>{if(!MP.cur)MP.busy=false;};
mpReq('GET',mpPath(m,'/save'),undefined,{auth:m}).then(j=>{free();if(S&&S.mp===m&&j&&int(j.seq,0,1e15,0)>(m.seq||0))mpAdopt(j,m);else mpRefresh();},
e=>{free();if(e&&e.status===404&&S&&S.mp===m)mpRefresh();else mpFail(e);});}
// A network of a session opened or started: nothing from another one carries over (a push still on its way is forgotten).
function mpReset(o){if(MP.cur)MP.cur.cut=true;Object.assign(MP,{roster:null,cur:null,busy:false,stale:false,staleSeq:0,gone:false,fails:0,wait:0,told:false,sig:'',force:false,now:false},o);}
function mpAdopt(j,m,n=0){if(!S||S.mp!==m)return;
// A day still routing in the worker finishes first.
if(RW.job){if(n<50)setTimeout(()=>mpAdopt(j,m,n+1),100);return;}
mpUnpack(j.data).then(s=>{if(!S||S.mp!==m||!mpSaveOk(s,m))throw new Error('not this network');delete s.sv;const nx=migrate(s);nx.mp.seq=int(j.seq,0,1e15,0);
S=nx;compute();UI.sel=null;if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);Object.assign(MP,{stale:false,staleSeq:0,force:false,day:S.day,last:performance.now()});
renderAll();save(true);toast(tr('mp.loaded_newer',{name:esc(S.name),date:dateStr(S.day)}),'good');mpRefresh();})
.catch(e=>{console.error('[tubes] loading the session save failed',e);toast(tr('mp.save_unreadable'),'bad');});}
function mpRefresh(poll){if(!mpIs()||MP.gone)return Promise.resolve();const m=S.mp;return mpReq('GET',mpPath(m),undefined,{auth:m}).then(mpOk,e=>mpFail(e,poll));}
/* ---------- a link to the same network on another device ----------
<origin>/#mp=<CODE>.<pid>.<token>: the fragment never reaches a server. At boot (before the slots are picked) the save
is fetched into a new slot, or the one this browser already has for that network is opened (one open in another tab
too: slotBoot then offers to take it over), and the fragment is cleared. The link's token is stored only once the
server took it: a wrong or old link never replaces nor deletes the one this browser already has. */
const mpLink=m=>{const t=mpTok(m);return t?location.origin+location.pathname+'#mp='+m.code+'.'+m.pid+'.'+t:'';};
function mpBoot(go){const hash=String(location.hash||''),h=MP_API?/^#mp=([0-9A-Za-z-]{6,8})\.([a-z0-9]{8})\.([0-9a-f]{64})$/.exec(hash):null;
if(!h){go();return;}
try{history.replaceState(null,'',location.pathname+location.search);}catch(e){}
const code=mpNorm(h[1]),m={code,pid:h[2]},tok=h[3],fin=b=>{UI.mpBoot=b;go();};
if(!code){fin({bad:1});return;}
const had=mpTok(m),keep=()=>{if(had!==tok)mpTokSet(code,m.pid,tok);};
// The server is away (or busy): the link may be fine, so it stays in the address bar for a reload to try again.
const no=e=>{console.error('[tubes] moving the network here failed',e);const st=e&&e.status,away=st===0||st===429||st>=500;
if(away)try{history.replaceState(null,'',location.pathname+location.search+hash);}catch(x){}fin(away?{away:1}:{bad:1});};
const ex=slotIdx(true).find(e=>e.mp===code+'.'+m.pid&&!e.broken);
if(ex){const open=()=>{ssSet(SLOT_SS,ex.id);fin({code});};
// Opening it fetches the server's save when that one is newer. A link with another token is asked about first.
if(had===tok)open();else mpReq('GET',mpPath(m),undefined,{auth:m,tok}).then(()=>{keep();open();},no);return;}
mpReq('GET',mpPath(m,'/save'),undefined,{auth:m,tok}).then(j=>mpUnpack(j&&j.data).then(s=>{if(!mpSaveOk(s,m))throw new Error('not this network');
delete s.sv;s.mp.seq=int(j.seq,0,1e15,0);const txt=JSON.stringify(s);return (txt.length>=GZ_MIN&&gzOk()?gzip(txt):Promise.resolve(txt)).then(data=>{
const id=slotRid();localStorage.setItem(SLOT_K+id,data);keep();
slotIdxPut(slotIdx(true).filter(x=>x.id!==id).concat([slotClean({id,...slotMeta(s,null),seq:1,at:Date.now(),size:data.length,gz:data.startsWith(GZ),broken:false})]));ssSet(SLOT_SS,id);});}))
.then(()=>fin({code}),no);}
// Said once the game is on screen (or the title is).
function mpBootTell(){const b=UI.mpBoot;if(!b)return;UI.mpBoot=null;
if(b.bad)toast(tr('mp.link_bad'),'bad');else if(b.away)toast(tr('mp.err_offline'),'bad');
else if(S&&S.mp&&S.mp.code===b.code)toast(tr('mp.welcome_device',{name:esc(S.name),code:mpShow(b.code)}),'goal');}

View file

@ -110,7 +110,7 @@ function sanitize(s){
three Normal presets, unchanged (its validated mods kept). So an edited or imported save cannot stop the clock or print money. */ three Normal presets, unchanged (its validated mods kept). So an edited or imported save cannot stop the clock or print money. */
{const r=s.rules&&typeof s.rules==='object'&&!Array.isArray(s.rules)?s.rules:{}; {const r=s.rules&&typeof s.rules==='object'&&!Array.isArray(s.rules)?s.rules:{};
const m={mods:r.mods};s.rules=s.scn&&typeof s.scn==='object'?makeRules('oncall',m):s.mode==='sandbox'?makeRules('sandbox',{...m,chaos:r.chaos}):makeRules(NORMAL_PRESETS.includes(r.preset)?r.preset:'oncall',m);} const m={mods:r.mods};s.rules=s.scn&&typeof s.scn==='object'?makeRules('oncall',m):s.mode==='sandbox'?makeRules('sandbox',{...m,chaos:r.chaos}):makeRules(NORMAL_PRESETS.includes(r.preset)?r.preset:'oncall',m);}
specSanitize(s); specSanitize(s);mpSanitize(s);
pieSanitize(s);pieIncFix(s); pieSanitize(s);pieIncFix(s);
if(s.te){if(typeof s.te!=='object')s.te=null;else{s.te.on=!!s.te.on;s.te.script=typeof s.te.script==='string'?s.te.script.slice(0,4000):'';}} if(s.te){if(typeof s.te!=='object')s.te=null;else{s.te.on=!!s.te.on;s.te.script=typeof s.te.script==='string'?s.te.script.slice(0,4000):'';}}
return s;} return s;}

View file

@ -8,5 +8,7 @@ Object.assign(ACT,{
toast(tr('specialist.you_own_n_fiber_pairs_on',{n,name:esc(o.name),a:CITY[o.a].name,b:CITY[o.b].name,d:days}),'goal');sfx('build');after();}, toast(tr('specialist.you_own_n_fiber_pairs_on',{n,name:esc(o.name),a:CITY[o.a].name,b:CITY[o.b].name,d:days}),'goal');sfx('build');after();},
seatNo:()=>{S.seatOff=null;after();}, seatNo:()=>{S.seatOff=null;after();},
charter:({k})=>{if(!own(CHARTERS,k)||S.chartSet||S.scn||S.mode!=='normal')return;S.charter=k;S.chartSet=true;if($('modal').className==='charter')closeModal(); charter:({k})=>{if(!own(CHARTERS,k)||S.chartSet||S.scn||S.mode!=='normal')return;S.charter=k;S.chartSet=true;if($('modal').className==='charter')closeModal();
toast(tr('specialist.charter_signed_name',{name:tr(CHARTERS[k].n)}),'good');if(UI.tutLater){UI.tutLater=false;tutorialStart();}after();}, toast(tr('specialist.charter_signed_name',{name:tr(CHARTERS[k].n)}),'good');if(UI.tutLater){UI.tutLater=false;tutorialStart();}
// A new multiplayer session's code to share waited for the charter (95-modals/48-multiplayer.js).
if(UI.mpLater)mpStartTell();after();},
}); });

View file

@ -23,13 +23,13 @@ Object.assign(ACT,{
importPick:()=>{let f=$('importIn');if(!f){f=document.createElement('input');f.type='file';f.accept='.json,application/json';f.id='importIn';f.hidden=true;document.body.appendChild(f);f.addEventListener('change',()=>{importFile(f.files[0]);f.value='';});}f.click();}, importPick:()=>{let f=$('importIn');if(!f){f=document.createElement('input');f.type='file';f.accept='.json,application/json';f.id='importIn';f.hidden=true;document.body.appendChild(f);f.addEventListener('change',()=>{importFile(f.files[0]);f.value='';});}f.click();},
importGo:()=>{const s0=UI.importing;if(!s0)return;UI.importing=null;const prev=S;let nx;try{nx=migrate(JSON.parse(JSON.stringify(s0)));}catch(e){nx=null;}if(nx&&pzOn())pzLeave();const was=S; importGo:()=>{const s0=UI.importing;if(!s0)return;UI.importing=null;const prev=S;let nx;try{nx=migrate(JSON.parse(JSON.stringify(s0)));}catch(e){nx=null;}if(nx&&pzOn())pzLeave();const was=S;
// An import is a new network next to the others: the one playing here is saved and kept. // An import is a new network next to the others: the one playing here is saved and kept.
try{if(!nx)throw 0;S=nx;compute();checkGoals();}catch(e){S=was;if(S)compute();renderAll();toast(tr('game_and_settings.import_failed_that_save_is_damaged'),'bad');sfx('err');return;}UI.confirm=null;$('bankBox').hidden=true;$('dash').hidden=true;UI.started=true;UI.sel=null;setSpeed(S.uiSpeed===undefined?1:S.uiSpeed);if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;}}closeModal();$('modal').hidden=true;{const im=S;S=was;slotLeave();S=im;}slotNew();delete S.sv;compute();renderAll();save(true);toast(tr('game_and_settings.welcome_back_name_imported_and_saved',{name:esc(S.name)}),'good');sfx('coin');track('game_import');}, try{if(!nx)throw 0;S=nx;compute();checkGoals();}catch(e){S=was;if(S)compute();renderAll();toast(tr('game_and_settings.import_failed_that_save_is_damaged'),'bad');sfx('err');return;}UI.confirm=null;$('bankBox').hidden=true;$('dash').hidden=true;UI.started=true;UI.sel=null;setSpeed(S.uiSpeed===undefined?1:S.uiSpeed);if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;}}closeModal();$('modal').hidden=true;{const im=S;S=was;slotLeave();S=im;}slotNew();delete S.sv;compute();renderAll();save(true);toast(tr('game_and_settings.welcome_back_name_imported_and_saved',{name:esc(S.name)}),'good');sfx('coin');track('game_import');if(MP_API)mpResume();},
menu:()=>{if(!S||!UI.started){showTitle();return;}if(pzOn()){pzMenu();return;}openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">AS${S.asn} · ${esc(dateStr(S.day))} · ${tierLabel()}</div><h2 style="font-size:28px">${esc(S.name)} <button class="thb rn" data-act="rename" aria-label="${tr('slots.rename_your_network')}">✏️</button></h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div> menu:()=>{if(!S||!UI.started){showTitle();return;}if(pzOn()){pzMenu();return;}openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">AS${S.asn} · ${esc(dateStr(S.day))} · ${tierLabel()}</div><h2 style="font-size:28px">${esc(S.name)} <button class="thb rn" data-act="rename" aria-label="${tr('slots.rename_your_network')}">✏️</button></h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div>
${saveFailing()?`<p class="why">${saveFailMsg()}</p>`:`<p class="tagline">${tr('game_and_settings.your_game_saves_itself_every_few')}</p>`} ${saveFailing()?`<p class="why">${saveFailMsg()}</p>`:`<p class="tagline">${tr('game_and_settings.your_game_saves_itself_every_few')}</p>`}
<div class="menu-list"> <div class="menu-list">
${btn(tr('common.back_to_the_map'),'closeModal',{},'pink big')}${saveFailing()?btn(tr('common.export_save'),'exportSave',{},'pink'):''}${saveFailing()&&UI.saveFail.full&&slotOthers().length?btn(tr('slots.free_up_space'),'slotSpace',{},'pink'):''} ${btn(tr('common.back_to_the_map'),'closeModal',{},'pink big')}${saveFailing()?btn(tr('common.export_save'),'exportSave',{},'pink'):''}${saveFailing()&&UI.saveFail.full&&slotOthers().length?btn(tr('slots.free_up_space'),'slotSpace',{},'pink'):''}
</div> </div>
<div class="menu-tiles">${[['🗂️',tr('slots.your_networks'),'toTitle'],['🧩',tr('puzzles.puzzles'),'puzzleMenu'],['🏆',tr('common.scenarios'),'scenarios'],['🧑‍💻',tr('ops.standing_orders'),'opsOpen'],['📐',tr('bstd.title'),'bstdOpen'],['📸',tr('common.share'),'share'],['⚙️',tr('common.settings'),'settings']].map(([i,l,a])=>`<button class="mtile" data-act="${a}"><i aria-hidden="true">${i}</i><span>${l}</span></button>`).join('')}</div> <div class="menu-tiles">${[['🗂️',tr('slots.your_networks'),'toTitle'],['🧩',tr('puzzles.puzzles'),'puzzleMenu'],['🏆',tr('common.scenarios'),'scenarios'],['🧑‍💻',tr('ops.standing_orders'),'opsOpen'],['📐',tr('bstd.title'),'bstdOpen'],...(mpIs()?[['🌐',tr('mp.session'),'mpOpen']]:[]),['📸',tr('common.share'),'share'],['⚙️',tr('common.settings'),'settings']].map(([i,l,a])=>`<button class="mtile" data-act="${a}"><i aria-hidden="true">${i}</i><span>${l}</span></button>`).join('')}</div>
<p class="menu-links">${[saveFailing()?null:[tr('common.export_save'),'exportSave'],[tr('common.import_a_save'),'importPick'],[tr('common.how_to_play'),'help'],RELEASE_NOTES.length?[tr('common.what_s_new_in_v',{v:esc(APP_VERSION)}),'whatsNewShow']:null,[tr('common.start_a_new_network'),'resetAsk']].filter(Boolean).map(([l,a])=>`<button class="lnk" data-act="${a}">${l}</button>`).join(' · ')}</p> <p class="menu-links">${[saveFailing()?null:[tr('common.export_save'),'exportSave'],[tr('common.import_a_save'),'importPick'],[tr('common.how_to_play'),'help'],RELEASE_NOTES.length?[tr('common.what_s_new_in_v',{v:esc(APP_VERSION)}),'whatsNewShow']:null,[tr('common.start_a_new_network'),'resetAsk']].filter(Boolean).map(([l,a])=>`<button class="lnk" data-act="${a}">${l}</button>`).join(' · ')}</p>
</div><div class="menu-plugs"><a class="mplug" href="${SIGNAL}" target="_blank" rel="noopener">💬 ${tr('modal_and_names.join_the_noc_chat')} →</a><a class="mplug" href="${ISSUES}" target="_blank" rel="noopener">🐛 ${tr('modal_and_names.found_a_bug_or_have_an')} →</a></div>`);}, </div><div class="menu-plugs"><a class="mplug" href="${SIGNAL}" target="_blank" rel="noopener">💬 ${tr('modal_and_names.join_the_noc_chat')} →</a><a class="mplug" href="${ISSUES}" target="_blank" rel="noopener">🐛 ${tr('modal_and_names.found_a_bug_or_have_an')} →</a></div>`);},
settings:()=>{UI.setOpen=true;openModal(settingsHtml());}, settings:()=>{UI.setOpen=true;openModal(settingsHtml());},

View file

@ -43,7 +43,7 @@ function bbCost(c){return 15000+CITY[c].P*20;}
/* A click that changes nothing routing reads (the log, offers, cash, names, settings…) keeps the routing it has: /* A click that changes nothing routing reads (the log, offers, cash, names, settings…) keeps the routing it has:
compute() gives the same R again for the same state (tests/compute-idempotent), so it is skipped. The key is the save compute() gives the same R again for the same state (tests/compute-idempotent), so it is skipped. The key is the save
without the fields routing never reads (tests/route-skip checks each one); any other change routes again. */ without the fields routing never reads (tests/route-skip checks each one); any other change routes again. */
const RK_SKIP=new Set(['name','log','offers','usedNames','stats','cash','seen','tut','ach','achP','won','loanOffers','loanStrikes','uiSpeed','cam','richTold','demo','nextEvent','nextFail','done','confReg','auNews','calV','solWon','seatOff','chartSet','t1Now','ltv','capDeal','auV','pdeskRep','sv','popStd']); const RK_SKIP=new Set(['name','log','offers','usedNames','stats','cash','seen','tut','ach','achP','won','loanOffers','loanStrikes','uiSpeed','cam','richTold','demo','nextEvent','nextFail','done','confReg','auNews','calV','solWon','seatOff','chartSet','t1Now','ltv','capDeal','auV','pdeskRep','sv','popStd','mp']);
function routeKey(){const o={};for(const k in S)if(!RK_SKIP.has(k))o[k]=S[k];return JSON.stringify(o);} function routeKey(){const o={};for(const k in S)if(!RK_SKIP.has(k))o[k]=S[k];return JSON.stringify(o);}
function routeIfChanged(){const k=S&&!pzOn()?routeKey():null;if(k&&k===UI.rk&&R===UI.rkR)return false;compute();UI.rk=k;UI.rkR=R;return true;} function routeIfChanged(){const k=S&&!pzOn()?routeKey():null;if(k&&k===UI.rk&&R===UI.rkR)return false;compute();UI.rk=k;UI.rkR=R;return true;}
function after(){if(pzOn()){pzAfter();return;}NOC.dirty=true;if(S)purgeInc();routeIfChanged();checkGoals();renderAll();if(S&&!$('dash').hidden)renderDash();save();} function after(){if(pzOn()){pzAfter();return;}NOC.dirty=true;if(S)purgeInc();routeIfChanged();checkGoals();renderAll();if(S&&!$('dash').hidden)renderDash();save();}

View file

@ -31,4 +31,4 @@ function gameClear(){S=null;R=emptyR();UI.started=false;UI.sel=null;UI.nm=null;U
// Back from the title (or a puzzle) into a loaded network. // Back from the title (or a puzzle) into a loaded network.
function gameResume(){UI.started=true;UI.sel=null;UI.confirm=null;$('dash').hidden=true;$('bankBox').hidden=true;setSpeed([0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1); function gameResume(){UI.started=true;UI.sel=null;UI.confirm=null;$('dash').hidden=true;$('bankBox').hidden=true;setSpeed([0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1);
if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;cam.z=innerWidth<760?1.1:1.4;}} if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;cam.z=innerWidth<760?1.1:1.4;}}
closeModal();renderAll();toast(tr('loop.welcome_back_name_your_network_is',{name:esc(S.name),date:dateStr(S.day)}),'good');} closeModal();renderAll();toast(tr('loop.welcome_back_name_your_network_is',{name:esc(S.name),date:dateStr(S.day)}),'good');if(MP_API)mpResume();}

View file

@ -0,0 +1,34 @@
// Multiplayer (60-features/89-multiplayer.js, 95-modals/48-multiplayer.js). Every one does nothing unless the build
// stamped MP_API; the title-screen ones are in the click delegate's no-game list (96-map/95-clicks.js).
Object.assign(ACT,{
mpDoor:()=>{if(!MP_API)return;const i=$('nmIn');UI.nm=((i&&i.value)||UI.nm||randomNetworkName()).slice(0,24);openModal(mpStartHtml());
const n=$('mpName');if(n)n.addEventListener('input',e=>{UI.nm=e.target.value;});
const c=$('mpCode');if(c)c.addEventListener('keydown',e=>{if(e.key==='Enter'){e.preventDefault();ACT.mpJoin({});}});},
mpBack:()=>{const n=$('mpName');if(n)UI.nm=n.value.slice(0,24);showTitle();},
mpStart:()=>{if(!MP_API||UI.mpBusy)return;const nm=mpNameIn(),home=homeOk(UI.startCity)?UI.startCity:'fra',preset=NORMAL_PRESETS.includes(UI.preset)?UI.preset:'oncall',t=$('mpTitle');
mpBusy(true);mpReq('POST','/sessions',{net:{name:nm,home},preset,title:(t&&t.value||'').slice(0,40),avoid:mpAvoid()}).then(j=>{mpBusy(false);mpBegin(j,nm,home,false);},e=>{mpBusy(false);mpErr(e);});},
mpJoin:()=>{if(!MP_API||UI.mpBusy)return;const i=$('mpCode'),code=mpNorm(i?i.value:'');if(!code){toast(tr('mp.err_code'),'bad');if(i)i.focus();return;}
const nm=mpNameIn(),home=homeOk(UI.startCity)?UI.startCity:'fra';
mpBusy(true);mpReq('POST','/sessions/'+code+'/join',{net:{name:nm,home},avoid:mpAvoid()}).then(j=>{mpBusy(false);mpBegin(j,nm,home,true);},e=>{mpBusy(false);mpErr(e);});},
mpOpen:()=>{if(!mpIs())return;openModal(mpPanelHtml(),'mp');const s=$('mpSay');if(s)s.addEventListener('keydown',e=>{if(e.key==='Enter'){e.preventDefault();ACT.mpChat({});}});
// About to move to another device: the server gets what this one has first, so the link opens it as it is now.
const d=document.querySelector('#mpPanel details.mpmove');if(d)d.addEventListener('toggle',()=>{if(d.open)mpSyncNow();});mpPoll();},
mpShare:()=>{if(!mpIs())return;mpSend(tr('mp.share_line',{code:mpShow(S.mp.code),url:location.origin+location.pathname}));},
// The link carries the secret: it goes to the clipboard, or is selected for copying by hand, never into a toast.
mpCopyLink:()=>{if(!mpIs())return;const l=mpLink(S.mp);if(!l)return;mpSyncNow();const sel=()=>{const i=$('mpLink');if(i){i.focus();i.select();}};
try{navigator.clipboard.writeText(l).then(()=>toast(tr('mp.link_copied'),'good'),sel);}catch(e){sel();}},
mpChat:()=>{if(!mpIs()||MP.gone)return;const i=$('mpSay'),t=(i?i.value:'').trim().slice(0,200);if(!t)return;const m=S.mp;
mpReq('POST',mpPath(m,'/feed'),{text:t},{auth:m}).then(j=>{if(i)i.value='';mpOk(j);},e=>{if(e&&e.status===429)toast(tr('mp.slow_down'),'bad');else mpFail(e);});},
mpLeaveAsk:()=>{if(!mpIs())return;openModal(`<h2 style="font-size:26px">${tr('mp.leave_q',{code:mpShow(S.mp.code)})}</h2><p class="tagline">${tr('mp.leave_d',{name:esc(S.name)})}</p><div class="btns">${btn(tr('mp.leave'),'mpLeave',{},'red big')}${btn(tr('common.keep_playing'),'mpOpen',{},'ghost big')}</div>`);},
// Leaving keeps the network, as a game of its own; the session forgets it (and a session that forgot it already too).
mpLeave:()=>{if(!mpIs())return;const m=S.mp,out=()=>{if(!S||S.mp!==m)return;S.mp=null;mpTokSet(m.code,m.pid,null);mpReset();
closeModal();renderAll();save(true);toast(tr('mp.left',{name:esc(S.name)}),'good');};
mpReq('DELETE',mpPath(m,'/me'),undefined,{auth:m}).then(out,e=>{if(e&&(e.status===401||e.status===404))out();else toast(tr('mp.server_away'),'bad');});},
// Only a save at least as new as the one the server said it has (after a conflict), or newer than this one, is loaded:
// "Load the newer save" never takes the player back to an older one.
mpNewer:()=>{if(!mpIs())return;const m=S.mp,min=(m.seq||0)+(MP.stale?0:1);
mpReq('GET',mpPath(m,'/save'),undefined,{auth:m}).then(j=>{if(!S||S.mp!==m)return;const sq=int(j&&j.seq,0,1e15,0);if(sq>=min){mpAdopt(j,m);return;}
m.seq=Math.max(m.seq||0,sq);MP.stale=false;toast(tr('mp.no_newer',{name:esc(S.name)}),'good');mpPanelUpdate();},mpFail);},
// Overwrite the server's save with this one: with a number past the server's, at the next save (never half a day).
mpKeep:()=>{if(!mpIs())return;S.mp.seq=Math.max(S.mp.seq||0,MP.staleSeq||0);Object.assign(MP,{stale:false,force:true,wait:0});save(true);mpPanelUpdate();},
});

View file

@ -14,7 +14,8 @@ function save(force,st){if(!st)st=pzOn()?UI.pzKeep:S;const id=UI.slot;
UI.lastSave=performance.now(); UI.lastSave=performance.now();
// Set aside for a puzzle, it cannot change: once its save has landed (or is still compressing), there is nothing to do. // Set aside for a puzzle, it cannot change: once its save has landed (or is still compressing), there is nothing to do.
if(st!==S&&!failed&&(SLOT.top[id]||0)>0)return; if(st!==S&&!failed&&(SLOT.top[id]||0)>0)return;
const txt=JSON.stringify(packSave(st)); // A network in a multiplayer session: the server keeps a copy too (60-features/89-multiplayer.js).
const txt=MP_API&&st===S&&S.mp?mpSave(st):JSON.stringify(packSave(st));
let tier=null;if(st===S)try{tier=tierLabel();}catch(e){} let tier=null;if(st===S)try{tier=tierLabel();}catch(e){}
const seq=SLOT.top[id]=Math.max(SLOT.top[id]||0,SLOT.sq[id]||0)+1,j={id,s:st,txt,seq,meta:slotMeta(st,tier)}; const seq=SLOT.top[id]=Math.max(SLOT.top[id]||0,SLOT.sq[id]||0)+1,j={id,s:st,txt,seq,meta:slotMeta(st,tier)};
if(txt.length>=GZ_MIN&&gzOk())gzSave(j);else slotPut(j,slotStamp(txt,seq));} if(txt.length>=GZ_MIN&&gzOk())gzSave(j);else slotPut(j,slotStamp(txt,seq));}

View file

@ -22,8 +22,11 @@ function slotClean(e){if(!e||typeof e!=='object'||!slotOkId(e.id))return null;
tier:['Tier 1','Tier 2','Tier 3'].includes(e.tier)?e.tier:null,cash:num(e.cash,0),at:num(e.at,0),size:int(e.size,0,1e10,0),seq:int(e.seq,0,1e15,0),gz:!!e.gz, tier:['Tier 1','Tier 2','Tier 3'].includes(e.tier)?e.tier:null,cash:num(e.cash,0),at:num(e.at,0),size:int(e.size,0,1e10,0),seq:int(e.seq,0,1e15,0),gz:!!e.gz,
// A save marked damaged (bv: the game version that could not load it) is tried again by the next version: the fault is // A save marked damaged (bv: the game version that could not load it) is tried again by the next version: the fault is
// usually in the game, and the save itself is fine once it is fixed. // usually in the game, and the save itself is fine once it is fixed.
...(e.broken&&e.bv===APP_VERSION?{broken:true,bv:e.bv}:{broken:false})};} ...(e.broken&&e.bv===APP_VERSION?{broken:true,bv:e.bv}:{broken:false}),
const slotMeta=(s,tier)=>({name:s.name,asn:s.asn,mode:s.mode,preset:s.rules&&s.rules.preset,scn:s.scn&&s.scn.name||null,day:s.day,cash:s.cash,tier}); // A network in a multiplayer session: <code>.<pid>, so a link from another device finds it again.
...(typeof e.mp==='string'&&/^[0-9A-HJKMNP-TV-Z]{6}\.[a-z0-9]{8}$/.test(e.mp)?{mp:e.mp}:{})};}
// mp is always there (null outside a session), so a network that left its session loses its badge in the list.
const slotMeta=(s,tier)=>({name:s.name,asn:s.asn,mode:s.mode,preset:s.rules&&s.rules.preset,scn:s.scn&&s.scn.name||null,day:s.day,cash:s.cash,tier,mp:s.mp&&s.mp.code?s.mp.code+'.'+s.mp.pid:null});
function slotKeys(){const out=[];try{for(let i=0;i<localStorage.length;i++){const k=localStorage.key(i);if(k===SLOT_OLD)out.old=true;else if(k&&k.startsWith(SLOT_K)&&slotOkId(k.slice(SLOT_K.length)))out.push(k.slice(SLOT_K.length));}}catch(e){}return out;} function slotKeys(){const out=[];try{for(let i=0;i<localStorage.length;i++){const k=localStorage.key(i);if(k===SLOT_OLD)out.old=true;else if(k&&k.startsWith(SLOT_K)&&slotOkId(k.slice(SLOT_K.length)))out.push(k.slice(SLOT_K.length));}}catch(e){}return out;}
// An index entry rebuilt from the save itself. A compressed one can only be read in the background: slotFix() fills it in. // An index entry rebuilt from the save itself. A compressed one can only be read in the background: slotFix() fills it in.
function slotFromKey(id){const raw=slotRaw(id)||'';if(raw.startsWith(GZ))return slotClean({id,gz:true,size:raw.length}); function slotFromKey(id){const raw=slotRaw(id)||'';if(raw.startsWith(GZ))return slotClean({id,gz:true,size:raw.length});
@ -46,7 +49,7 @@ function slotIdx(scan){const raw=lsGet(SLOT_IX);let list=null;
function slotIdxPut(list){const t=JSON.stringify({v:1,slots:list});try{localStorage.setItem(SLOT_IX,t);SLOT.ixRaw=t;SLOT.ixList=list.map(e=>({...e}));return true;}catch(e){SLOT.ixRaw=null;return false;}} function slotIdxPut(list){const t=JSON.stringify({v:1,slots:list});try{localStorage.setItem(SLOT_IX,t);SLOT.ixRaw=t;SLOT.ixList=list.map(e=>({...e}));return true;}catch(e){SLOT.ixRaw=null;return false;}}
function slotFix(list){for(const e of list)if(e.gz&&!e.name&&!e.broken&&!SLOT['fix'+e.id]){SLOT['fix'+e.id]=1;const raw=slotRaw(e.id); function slotFix(list){for(const e of list)if(e.gz&&!e.name&&!e.broken&&!SLOT['fix'+e.id]){SLOT['fix'+e.id]=1;const raw=slotRaw(e.id);
gunzip(raw).then(t=>{const s=JSON.parse(t);return s&&s.v===1?slotMeta(s,null):null;},()=>null).then(m=>{const l=slotIdx(),x=l.find(y=>y.id===e.id);if(!x)return; gunzip(raw).then(t=>{const s=JSON.parse(t);return s&&s.v===1?slotMeta(s,null):null;},()=>null).then(m=>{const l=slotIdx(),x=l.find(y=>y.id===e.id);if(!x)return;
if(m)Object.assign(x,slotClean({...x,...m}));else{x.broken=true;x.bv=APP_VERSION;}slotIdxPut(l);slotRefresh();});}} if(m){const c=slotClean({...x,...m});if(!c.mp)delete x.mp;Object.assign(x,c);}else{x.broken=true;x.bv=APP_VERSION;}slotIdxPut(l);slotRefresh();});}}
const slotByAt=l=>l.slice().sort((a,b)=>b.at-a.at); const slotByAt=l=>l.slice().sort((a,b)=>b.at-a.at);
// ---------- one writer per slot ---------- // ---------- one writer per slot ----------
// The heartbeat: who has a slot open, refreshed every few seconds. A hidden tab's timers can be slowed to once a // The heartbeat: who has a slot open, refreshed every few seconds. A hidden tab's timers can be slowed to once a
@ -88,7 +91,7 @@ function slotWrite(j,data){const id=j.id;if(SLOT.no.has(id))return false;
if(id!==SLOT_MAIN||lsGet(SLOT_OLD)==null)throw e;localStorage.setItem(SLOT_OLD,data);lsDel(k);k=SLOT_OLD;} if(id!==SLOT_MAIN||lsGet(SLOT_OLD)==null)throw e;localStorage.setItem(SLOT_OLD,data);lsDel(k);k=SLOT_OLD;}
if(id===SLOT_MAIN&&k!==SLOT_OLD)lsDel(SLOT_OLD);// the new key has a newer save now: the old one is no longer needed if(id===SLOT_MAIN&&k!==SLOT_OLD)lsDel(SLOT_OLD);// the new key has a newer save now: the old one is no longer needed
SLOT.sq[id]=Math.max(SLOT.sq[id]||0,j.seq); SLOT.sq[id]=Math.max(SLOT.sq[id]||0,j.seq);
const e=ent||{id};if(!ent)list.push(e);Object.assign(e,slotClean({...e,...j.meta,tier:j.meta.tier||e.tier,seq:j.seq,at:Date.now(),size:data.length,gz:data.startsWith(GZ),broken:false})); const e=ent||{id};if(!ent)list.push(e);const c=slotClean({...e,...j.meta,tier:j.meta.tier||e.tier,seq:j.seq,at:Date.now(),size:data.length,gz:data.startsWith(GZ),broken:false});if(!c.mp)delete e.mp;Object.assign(e,c);
slotIdxPut(list);return true;} slotIdxPut(list);return true;}
function slotPut(j,data){try{if(slotWrite(j,data))UI.saveFail=null;}catch(e){saveErr(e,j.s);}} function slotPut(j,data){try{if(slotWrite(j,data))UI.saveFail=null;}catch(e){saveErr(e,j.s);}}
// ---------- opening, leaving, losing ---------- // ---------- opening, leaving, losing ----------

View file

@ -6,6 +6,7 @@ function renderHUD(){
// A locked clock has no buttons: whoever locked it shows what it runs at (HOOKS.hud). // A locked clock has no buttons: whoever locked it shows what it runs at (HOOKS.hud).
{const ck=!S||rule('clock'),lk=UI.clockLocked;for(const v of [0,0.5,1,2,4,8]){const b=$('sp'+v);if(b){b.classList.toggle('on',!lk&&UI.speed===v);b.hidden=lk||!ck;}}HOOKS.hud?.();} {const ck=!S||rule('clock'),lk=UI.clockLocked;for(const v of [0,0.5,1,2,4,8]){const b=$('sp'+v);if(b){b.classList.toggle('on',!lk&&UI.speed===v);b.hidden=lk||!ck;}}HOOKS.hud?.();}
$('muteBtn').style.opacity=UI.muted?.4:1; $('muteBtn').style.opacity=UI.muted?.4:1;
if(MP_API)mpHud();// the session chip: also hidden again on the title screen and in a puzzle
if(!S)return; if(!S)return;
if(pzOn()){$('hName').textContent=pzName(pzDef(S.pz.id)||S.pz);$('hAsn').textContent=tr('puzzles.puzzle');renderTabbar();return;} if(pzOn()){$('hName').textContent=pzName(pzDef(S.pz.id)||S.pz);$('hAsn').textContent=tr('puzzles.puzzle');renderTabbar();return;}
{const rt=ruleTag(),ha=$('hAsn');ha.title=rt?tr('rules.rules_are_locked_for_this_network',{rules:rt}):'';} {const rt=ruleTag(),ha=$('hAsn');ha.title=rt?tr('rules.rules_are_locked_for_this_network',{rules:rt}):'';}

View file

@ -22,7 +22,7 @@ function showTitle(){
${top?`<div class="btns tcont" style="margin-bottom:6px">${btn(tr('title.continue_name_date',{name:esc(top.name||tr('common.unnamed_network')),date:dateStr(top.day)}),'cont',{id:top.id},'pink big')}</div>`:''} ${top?`<div class="btns tcont" style="margin-bottom:6px">${btn(tr('title.continue_name_date',{name:esc(top.name||tr('common.unnamed_network')),date:dateStr(top.day)}),'cont',{id:top.id},'pink big')}</div>`:''}
${many?slotsHtml():''} ${many?slotsHtml():''}
<label class="f" for="nmIn">${tr('title.name_your_network')}</label><div class="network-name"><div class="nmwrap"><input class="t" id="nmIn" maxlength="24" value="${esc(UI.nm)}" autocomplete="off"><button class="reroll" data-act="randomName" aria-label="${tr('common.another_one')}" title="${tr('common.another_one')}">↻</button></div><div class="asnwrap"><span aria-hidden="true">AS</span><input class="t" id="asnIn" inputmode="numeric" maxlength="10" value="${esc(UI.asnTxt==null?'':UI.asnTxt)}" placeholder="${UI.asnSug}" aria-label="${tr('title.as_number')}" autocomplete="off"></div></div> <label class="f" for="nmIn">${tr('title.name_your_network')}</label><div class="network-name"><div class="nmwrap"><input class="t" id="nmIn" maxlength="24" value="${esc(UI.nm)}" autocomplete="off"><button class="reroll" data-act="randomName" aria-label="${tr('common.another_one')}" title="${tr('common.another_one')}">↻</button></div><div class="asnwrap"><span aria-hidden="true">AS</span><input class="t" id="asnIn" inputmode="numeric" maxlength="10" value="${esc(UI.asnTxt==null?'':UI.asnTxt)}" placeholder="${UI.asnSug}" aria-label="${tr('title.as_number')}" autocomplete="off"></div></div>
${doorsHtml()} ${doorsHtml()}${MP_API?mpDoorHtml():''}
<label class="f" id="homeLbl" for="homeSel">${tr('title.pick_your_home_city')}</label>${homePick()}<p class="note" id="homeWhat">${homeWhat()}</p> <label class="f" id="homeLbl" for="homeSel">${tr('title.pick_your_home_city')}</label>${homePick()}<p class="note" id="homeWhat">${homeWhat()}</p>
<div class="btns cta tcta" style="margin-top:16px">${btn(list.length?tr('common.start_a_new_network'):tr('common.start_building'),'start',{},'big')}${btn(tr('common.how_to_play'),'help',{},'ghost')}${btn(tr('common.import_a_save'),'importPick',{},'ghost')}${btn(tr('common.settings'),'settings',{},'ghost')}</div><p class="ver">v${APP_VERSION} · <a href="https://github.com/fjaeckel/seriesoftubes" target="_blank" rel="noopener">${tr('title.source_on_github')}</a> · <a href="${SIGNAL}" target="_blank" rel="noopener">${tr('title.chat_on_signal')}</a> · ${tr('title.cookieless_stats_no_tracking')}</p>`); <div class="btns cta tcta" style="margin-top:16px">${btn(list.length?tr('common.start_a_new_network'):tr('common.start_building'),'start',{},'big')}${btn(tr('common.how_to_play'),'help',{},'ghost')}${btn(tr('common.import_a_save'),'importPick',{},'ghost')}${btn(tr('common.settings'),'settings',{},'ghost')}</div><p class="ver">v${APP_VERSION} · <a href="https://github.com/fjaeckel/seriesoftubes" target="_blank" rel="noopener">${tr('title.source_on_github')}</a> · <a href="${SIGNAL}" target="_blank" rel="noopener">${tr('title.chat_on_signal')}</a> · ${tr('title.cookieless_stats_no_tracking')}</p>`);
$('nmIn').addEventListener('input',e=>{UI.nm=e.target.value;}); $('nmIn').addEventListener('input',e=>{UI.nm=e.target.value;});
@ -44,8 +44,10 @@ const DOORS=[['puzzle','🧩',tr('title.puzzles'),tr('title.one_network_one_knot
const doorAct={puzzle:'puzzleDoor',sandbox:'modeSet',normal:'modeSet',scn:'scenarios'}; const doorAct={puzzle:'puzzleDoor',sandbox:'modeSet',normal:'modeSet',scn:'scenarios'};
// The chosen preset in one line: its joke, then what actually changes. // The chosen preset in one line: its joke, then what actually changes.
const presetWhat=k=>`${esc(PRESETS[k].d)} <span class="meta">${esc(PRESETS[k].x)}</span>`; const presetWhat=k=>`${esc(PRESETS[k].d)} <span class="meta">${esc(PRESETS[k].x)}</span>`;
// The Normal presets, one toggle each: on the title screen, and for a multiplayer session (48-multiplayer.js).
const presetBtns=pr=>`<label class="f">${tr('title.how_much_trouble')}</label><div class="presets">${NORMAL_PRESETS.map(k=>{const P=PRESETS[k];return `<button class="preset${k===pr?' on':''}" data-preset="${k}" data-act="presetSet" data-args='{"p":"${k}"}' aria-pressed="${k===pr}"><i aria-hidden="true">${P.i}</i><b>${P.n}</b></button>`;}).join('')}</div><p class="note" id="presetWhat">${presetWhat(pr)}</p>`;
function doorsHtml(){const m=UI.mode==='sandbox'?'sandbox':'normal',pr=own(PRESETS,UI.preset)&&NORMAL_PRESETS.includes(UI.preset)?UI.preset:'oncall',ch=own(CHAOS,UI.sbChaos)?UI.sbChaos:'none'; function doorsHtml(){const m=UI.mode==='sandbox'?'sandbox':'normal',pr=own(PRESETS,UI.preset)&&NORMAL_PRESETS.includes(UI.preset)?UI.preset:'oncall',ch=own(CHAOS,UI.sbChaos)?UI.sbChaos:'none';
return `<label class="f">${tr('title.pick_a_door')}</label><div class="doors">${DOORS.map(([k,i,n,d])=>`<button class="door${k===m?' on':''}" data-door="${k}" data-act="${doorAct[k]}" data-args='${k==='sandbox'||k==='normal'?`{"m":"${k}"}`:'{}'}'><i aria-hidden="true">${i}</i><b>${n}</b><span>${d}</span>${k==='puzzle'&&pzWkNew()||k==='scn'&&wsNew()?`<em class="pznew">${tr('puzzles.new_this_sunday')}</em>`:''}</button>`).join('')}</div> return `<label class="f">${tr('title.pick_a_door')}</label><div class="doors">${DOORS.map(([k,i,n,d])=>`<button class="door${k===m?' on':''}" data-door="${k}" data-act="${doorAct[k]}" data-args='${k==='sandbox'||k==='normal'?`{"m":"${k}"}`:'{}'}'><i aria-hidden="true">${i}</i><b>${n}</b><span>${d}</span>${k==='puzzle'&&pzWkNew()||k==='scn'&&wsNew()?`<em class="pznew">${tr('puzzles.new_this_sunday')}</em>`:''}</button>`).join('')}</div>
<div id="doorNormal"${m==='normal'?'':' hidden'}><label class="f">${tr('title.how_much_trouble')}</label><div class="presets">${NORMAL_PRESETS.map(k=>{const P=PRESETS[k];return `<button class="preset${k===pr?' on':''}" data-preset="${k}" data-act="presetSet" data-args='{"p":"${k}"}' aria-pressed="${k===pr}"><i aria-hidden="true">${P.i}</i><b>${P.n}</b></button>`;}).join('')}</div><p class="note" id="presetWhat">${presetWhat(pr)}</p></div> <div id="doorNormal"${m==='normal'?'':' hidden'}>${presetBtns(pr)}</div>
<div id="doorSandbox"${m==='sandbox'?'':' hidden'}><label class="f">${tr('title.chaos_in_your_sandbox')}</label><div class="chaos">${Object.entries(CHAOS).map(([k,C])=>`<button class="chs${k===ch?' on':''}" data-chaos="${k}" data-act="chaosSet" data-args='{"c":"${k}"}'><i aria-hidden="true">${C.i}</i><b>${C.n}</b><span>${C.d}</span></button>`).join('')}</div></div> <div id="doorSandbox"${m==='sandbox'?'':' hidden'}><label class="f">${tr('title.chaos_in_your_sandbox')}</label><div class="chaos">${Object.entries(CHAOS).map(([k,C])=>`<button class="chs${k===ch?' on':''}" data-chaos="${k}" data-act="chaosSet" data-args='{"c":"${k}"}'><i aria-hidden="true">${C.i}</i><b>${C.n}</b><span>${C.d}</span></button>`).join('')}</div></div>
<p class="note lockn">🔒 ${tr('title.rules_are_picked_once_and_locked')}</p>`;} <p class="note lockn">🔒 ${tr('title.rules_are_picked_once_and_locked')}</p>`;}

View file

@ -5,7 +5,7 @@ const slotIcon=e=>e.broken?'🩹':e.mode==='scenario'?'🏆':e.mode==='sandbox'?
// The network to continue: the most recent one that is not open in another window (or damaged). // The network to continue: the most recent one that is not open in another window (or damaged).
function slotTop(list){return slotByAt(list).find(e=>!e.broken&&!slotBusy(e.id))||null;} function slotTop(list){return slotByAt(list).find(e=>!e.broken&&!slotBusy(e.id))||null;}
function slotLine(e){if(e.broken)return tr('slots.damaged_export_or_delete'); function slotLine(e){if(e.broken)return tr('slots.damaged_export_or_delete');
const bits=[e.asn?'AS'+e.asn:'',e.name||e.gz?dateStr(e.day):''];if(e.mode==='scenario'&&e.scn)bits.push(esc(e.scn));else if(e.tier)bits.push(e.tier); const bits=[e.asn?'AS'+e.asn:'',e.name||e.gz?dateStr(e.day):''];if(e.mode==='scenario'&&e.scn)bits.push(esc(e.scn));else if(e.tier)bits.push(e.tier);if(MP_API&&e.mp)bits.push('🌐 '+mpShow(e.mp.slice(0,6)));
return bits.filter(Boolean).join(' · ');} return bits.filter(Boolean).join(' · ');}
function slotRow(e,top){const busy=slotBusy(e.id),nm=esc(e.name||tr('common.unnamed_network')); function slotRow(e,top){const busy=slotBusy(e.id),nm=esc(e.name||tr('common.unnamed_network'));
const tag=busy?`<span class="tag">${tr('slots.open_in_another_window')}</span>`:top?`<span class="tag">▶ ${tr('slots.continue')}</span>`:''; const tag=busy?`<span class="tag">${tr('slots.open_in_another_window')}</span>`:top?`<span class="tag">▶ ${tr('slots.continue')}</span>`:'';

View file

@ -0,0 +1,73 @@
/* Multiplayer on screen (89-multiplayer.js has the logic): the title screen's door, the start/join sheet, the session
panel (leaderboard, feed and chat, the code to share, the link to another device) and the HUD chip. Only ever drawn
when the build stamped MP_API. Everything another player wrote is escaped here. */
const MP_FEED_L={join:N_('mp.feed_join'),leave:N_('mp.feed_leave'),t2:N_('mp.feed_t2'),t1:N_('mp.feed_t1'),t1first:N_('mp.feed_t1first')};
const mpDoorHtml=()=>`<div class="mpdoor-row"><button class="door mpdoor" data-act="mpDoor"><i aria-hidden="true">🌐</i><b>${tr('mp.multiplayer')}</b><span>${tr('mp.door_d')}</span></button></div>`;
function mpStartHtml(){const pr=NORMAL_PRESETS.includes(UI.preset)?UI.preset:'oncall';
return `<div style="display:flex;align-items:center"><div class="grow"><div class="eyebrow">🌐 ${tr('mp.multiplayer')}</div><h2 style="font-size:26px">${tr('mp.play_with_friends')}</h2></div><button class="x" data-act="mpBack" aria-label="${tr('common.close')}">×</button></div>
<p class="tagline">${tr('mp.intro')}</p>
<label class="f" for="mpName">${tr('title.name_your_network')}</label><input class="t" id="mpName" maxlength="24" value="${esc(UI.nm||'')}" autocomplete="off">
<label class="f" id="homeLbl" for="homeSel">${tr('title.pick_your_home_city')}</label>${homePick()}<p class="note" id="homeWhat">${homeWhat()}</p>
<div class="mpbox"><h3>${tr('mp.start_a_session')}</h3>${presetBtns(pr)}
<label class="f" for="mpTitle">${tr('mp.session_title')}</label><input class="t" id="mpTitle" maxlength="40" autocomplete="off">
<div class="btns">${btn(tr('mp.start_a_session'),'mpStart',{},'pink big mpgo')}</div></div>
<div class="mpbox"><h3>${tr('mp.join_a_session')}</h3><label class="f" for="mpCode">${tr('mp.code')}</label>
<div class="mpjoin"><input class="t" id="mpCode" maxlength="8" placeholder="K7Q-2XD" autocomplete="off" autocapitalize="characters" spellcheck="false">${btn(tr('mp.join'),'mpJoin',{},'big mpgo')}</div>
<p class="note">${tr('mp.join_note')}</p></div>
<p class="note" id="mpBusy" hidden>${tr('mp.talking')}</p>
<div class="btns cta">${btn(tr('common.back'),'mpBack',{},'ghost')}</div>`;}
function mpBusy(on){UI.mpBusy=on;document.querySelectorAll('.mpgo').forEach(b=>{b.disabled=on;});const b=$('mpBusy');if(b)b.hidden=!on;}
function mpErr(e){const st=e&&e.status;sfx('err');
toast(st===404?tr('mp.err_no_session'):st===409?tr('mp.err_full'):st===429?tr('mp.err_slow'):st===503?tr('mp.err_server_full'):st===400?tr('mp.err_refused'):tr('mp.err_offline'),'bad');}
const mpNameIn=()=>{const n=$('mpName'),v=String((n&&n.value)||UI.nm||randomNetworkName()).trim().slice(0,24)||randomNetworkName();UI.nm=v;return v;};
// The server said yes: the token goes to this browser's storage, the rest into a new game.
function mpBegin(j,nm,home,joined){const m=mpJoinOk(j);if(!m){toast(tr('mp.err_offline'),'bad');return;}
mpTokSet(m.code,m.pid,m.token);delete m.token;beginGame(nm,home,{mode:'normal',preset:m.preset,mp:{...m,joined}});}
// Called by beginGame just before its first save, which then pushes the day-0 save and the card: this player is on the
// leaderboard at once, and a link to another device works from the start.
function mpStarted(m){mpReset({day:-1,last:-1e9});mpHud();UI.mpLater={joined:!!(m&&m.joined)};}
// The code to share, with its buttons. A new Normal game asks for its charter first, on top of everything: the code
// waits until it is signed (ACT.charter), or its buttons could not be pressed.
function mpStartTell(){const b=UI.mpLater;if(!b||!mpIs())return;if(!$('modal').hidden&&$('modal').className==='charter')return;UI.mpLater=null;
const code=mpShow(S.mp.code),acts=[{l:tr('common.share'),act:'mpShare',args:{}},{l:tr('mp.session'),act:'mpOpen',args:{}}];
toast(b.joined?tr('mp.joined',{code}):tr('mp.session_live',{code}),'goal',acts);}
/* ---------- the session panel ---------- */
function mpBoardHtml(){const r=MP.roster;if(MP.gone)return `<p class="why">${tr('mp.not_in_session')}</p>`;
// Another device moved on: the toast with the choice is long gone, the choice stays here until it is made.
const st=MP.stale?`<p class="why">${tr('mp.moved_on_elsewhere')}</p><div class="btns">${btn(tr('mp.load_newer'),'mpNewer',{},'pink')}${btn(tr('mp.keep_mine'),'mpKeep',{},'')}</div>`:'';
if(st)return st;if(!r)return `<p class="note">${tr('mp.loading')}</p>`;const me=S&&S.mp&&S.mp.pid;
return mpRank(r.players).map((p,i)=>{const c=p.card,mine=p.pid===me;
const meta=c?[`AS${p.asn}`,c.t1?'Tier 1':c.tier==='t2'?'Tier 2':'Tier 3',trn('mp.n_pops',c.pops.length),fmtG(c.peak),trn('mp.n_customers',c.cust)].join(' · '):`AS${p.asn} · ${tr('mp.no_card')}`;
return `<div class="mprow${mine?' me':''}"><span class="mprk">${i+1}</span><i class="mpdot" style="background:${p.color}" aria-hidden="true"></i><div class="grow"><b>${esc(p.name)}</b>${mine?` <span class="tag">${tr('mp.you')}</span>`:''}<div class="meta">${meta}</div></div><small class="mpseen">${p.seen?slotAgo(p.seen):''}</small></div>`;}).join('');}
function mpFeedHtml(){const r=MP.roster;if(!r)return '';const f=r.feed.slice(-30).reverse();if(!f.length)return `<p class="note">${tr('mp.feed_empty')}</p>`;
const col=pid=>{const p=r.players.find(x=>x.pid===pid);return p?p.color:'#888888';};
return f.map(x=>{const who=`<b>${esc(x.name)}</b>`,t=x.k==='chat'?`${who}: ${esc(x.text)}`:tr(MP_FEED_L[x.k],{name:who});
return `<div class="mpf ${x.k}"><i class="mpdot" style="background:${col(x.pid)}" aria-hidden="true"></i><span class="grow">${t}</span><small>${x.at?slotAgo(x.at):''}</small></div>`;}).join('');}
function mpPanelHtml(){const m=S.mp,code=mpShow(m.code),link=mpLink(m);
return `<div class="mp-panel" id="mpPanel"><div style="display:flex;align-items:center"><div class="grow"><div class="eyebrow">🌐 ${tr('mp.session')} · ${esc(PRESETS[m.preset].n)}</div><h2 style="font-size:26px">${m.title?esc(m.title):tr('mp.session_code',{code})}</h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div>
<div class="mpcode"><div class="grow"><small>${tr('mp.code')}</small><b>${code}</b></div>${btn(tr('common.share'),'mpShare',{},'pink')}</div>
<p class="note">${tr('mp.share_note')}</p>
<h3>${tr('mp.leaderboard')}</h3><div class="mpboard" id="mpBoard">${mpBoardHtml()}</div>
<h3>${tr('mp.feed')}</h3><div class="mpchat"><input class="t" id="mpSay" maxlength="200" placeholder="${esc(tr('mp.say'))}" aria-label="${esc(tr('mp.say'))}" autocomplete="off">${btn(tr('mp.send'),'mpChat',{},'')}</div><div class="mpfeed" id="mpFeed">${mpFeedHtml()}</div>
${link?`<details class="mpmove"><summary>${tr('mp.move_device')}</summary><p class="note">${tr('mp.move_note')}</p><input class="t" id="mpLink" readonly value="${esc(link)}" aria-label="${esc(tr('mp.move_device'))}"><p class="why">${tr('mp.move_warn')}</p><div class="btns">${btn(tr('mp.copy_link'),'mpCopyLink',{},'')}</div></details>`:''}
<div class="btns cta">${btn(tr('common.back_to_the_map'),'closeModal',{},'pink big')}${btn(tr('mp.leave'),'mpLeaveAsk',{},'ghost')}</div></div>`;}
// The roster moved on: only the leaderboard and the feed are redrawn, so a chat line being typed stays.
function mpPanelUpdate(){const b=$('mpBoard'),f=$('mpFeed');if(!b||$('modal').hidden)return;b.innerHTML=mpBoardHtml();if(f)f.innerHTML=mpFeedHtml();}
// While the panel is open, the roster every 5 s; it stops by itself once the panel is gone.
function mpPoll(){clearInterval(MP.poll);MP.poll=null;if(!mpIs())return;mpRefresh();if(!window.__TUBES_TEST__)MP.poll=setInterval(mpPollTick,MP_POLL);}
function mpPollTick(){if($('modal').hidden||!$('mpPanel')||!mpIs()){clearInterval(MP.poll);MP.poll=null;return;}mpRefresh(true);}
/* The HUD chip: the session code and where you stand. A phone's top bar has no room for it (the menu has the session):
there, and on a tablet whose top bar is still too full (fitHud's last step), where you stand is a badge on the menu
button instead. Made the first time a session network is on screen. */
function mpHud(){let c=$('hMp');const on=mpIs();
if(!c){if(!on)return;c=document.createElement('button');c.className='chip mpchip hide-sm';c.id='hMp';c.dataset.act='mpOpen';
c.innerHTML='<span class="lbl" id="hMpCode"></span><span class="val num" id="hMpRank"></span>';const n=$('hNoc');n.parentNode.insertBefore(c,n.nextSibling);
const b=document.createElement('span');b.className='badge mpbadge num';b.id='hMpB';b.setAttribute('aria-hidden','true');const mb=document.querySelector('#hud .menubtn');if(mb)mb.appendChild(b);}
const b=$('hMpB');c.hidden=!on;if(b)b.hidden=!on;if(!on)return;
const r=MP.roster,i=r?mpRank(r.players).findIndex(p=>p.pid===S.mp.pid):-1,rk=i>=0?`#${i+1}/${r.players.length}`:'—';
c.setAttribute('aria-label',tr('mp.session'));c.title=tr('mp.session');c.style.borderColor=S.mp.color;
$('hMpCode').textContent=mpShow(S.mp.code);$('hMpRank').textContent='🌐 '+rk;if(b)b.textContent=i>=0?`#${i+1}`:'🌐';}
// Share text: the phone's share sheet, or the clipboard.
function mpSend(t){const copied=()=>toast(tr('puzzles.copied_paste_it_anywhere',{t:esc(t)}),'good');
if(navigator.share&&isPhone()){navigator.share({text:t}).catch(()=>{});return;}
try{navigator.clipboard.writeText(t).then(copied,()=>toast(esc(t),''));}catch(e){toast(esc(t),'');}}

View file

@ -11,5 +11,5 @@ let PD={t:0,b:null};
document.addEventListener('pointerdown',e=>{PD={t:performance.now(),b:e.target.closest('[data-act]')};},true); document.addEventListener('pointerdown',e=>{PD={t:performance.now(),b:e.target.closest('[data-act]')};},true);
function tapOk(e,b){if(!e.isTrusted||!PD.t||e.detail===0)return true;const now=performance.now();if(now-PD.t>4000)return true; function tapOk(e,b){if(!e.isTrusted||!PD.t||e.detail===0)return true;const now=performance.now();if(now-PD.t>4000)return true;
if(PD.b!==b)return false;if((UI.layerAt||0)>PD.t)return false;const ts=b.closest('.toast');if(ts&&PD.t-(+ts.dataset.born||0)<500)return false;return true;} if(PD.b!==b)return false;if((UI.layerAt||0)>PD.t)return false;const ts=b.closest('.toast');if(ts&&PD.t-(+ts.dataset.born||0)<500)return false;return true;}
document.addEventListener('click',e=>{const b=e.target.closest('[data-act]');if(!b||b.disabled)return;if(!$('modal').hidden&&!b.closest('#modal'))return;if(!tapOk(e,b))return;audioInit();const fn=ACT[b.dataset.act];if(!fn)return;if(!S&&!['start','keys','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','mapSet','soundSet','langSet','closeModal','speed','bankClose','whatsNewShow','updateNow','updateLater','importPick','importGo','modeSet','presetSet','chaosSet','puzzleDoor','puzzleMenu','pzStart','pzArStart','pzWeekly','scenarios','startScn','startWeekly','settings','settingsClose','prefSet','vpSet','install','pitchSkip','slotMenu','slotExport','slotDel','slotDelGo','slotBack','slotSwitch','slotTake','slotSpace','toTitle'].includes(b.dataset.act))return;let a={};try{a=JSON.parse(b.dataset.args||'{}');}catch(_){}fn(a);}); document.addEventListener('click',e=>{const b=e.target.closest('[data-act]');if(!b||b.disabled)return;if(!$('modal').hidden&&!b.closest('#modal'))return;if(!tapOk(e,b))return;audioInit();const fn=ACT[b.dataset.act];if(!fn)return;if(!S&&!['start','keys','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','mapSet','soundSet','langSet','closeModal','speed','bankClose','whatsNewShow','updateNow','updateLater','importPick','importGo','modeSet','presetSet','chaosSet','puzzleDoor','puzzleMenu','pzStart','pzArStart','pzWeekly','scenarios','startScn','startWeekly','settings','settingsClose','prefSet','vpSet','install','pitchSkip','slotMenu','slotExport','slotDel','slotDelGo','slotBack','slotSwitch','slotTake','slotSpace','toTitle','mpDoor','mpBack','mpStart','mpJoin'].includes(b.dataset.act))return;let a={};try{a=JSON.parse(b.dataset.args||'{}');}catch(_){}fn(a);});

View file

@ -43,7 +43,7 @@ function boot(data){
if(data&&data.S){S=migrate(data.S);UI.started=true;if(data.cam)Object.assign(cam,data.cam);compute();renderAll();} if(data&&data.S){S=migrate(data.S);UI.started=true;if(data.cam)Object.assign(cam,data.cam);compute();renderAll();}
else{const sv=UI.slot?loadSave():null,stamp=sv&&sv.sv;if(sv)delete sv.sv; else{const sv=UI.slot?loadSave():null,stamp=sv&&sv.sv;if(sv)delete sv.sv;
let okSave=false;if(sv){try{S=migrate(sv);compute();okSave=true;}catch(e){console.error('[tubes] loading the network failed',e);S=null;UI.started=false;}} let okSave=false;if(sv){try{S=migrate(sv);compute();okSave=true;}catch(e){console.error('[tubes] loading the network failed',e);S=null;UI.started=false;}}
if(okSave){slotIn(UI.slot,stamp);UI.started=true;setSpeed([0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1); if(okSave){slotIn(UI.slot,stamp);if(MP_API)mpResume();UI.started=true;setSpeed([0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1);
if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;cam.z=innerWidth<760?1.1:1.4;}} if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;cam.z=innerWidth<760?1.1:1.4;}}
renderAll();if(S.grace&&S.grace.until>S.day&&R.graceNets&&!S.grace.told){S.grace.told=1;toast(tr('loop.new_networks_on_the_map_this',{n:S.grace.until-S.day}),'goal',[{l:tr('common.open_noc'),act:'leftTab',args:{t:'noc'}}]);} renderAll();if(S.grace&&S.grace.until>S.day&&R.graceNets&&!S.grace.told){S.grace.told=1;toast(tr('loop.new_networks_on_the_map_this',{n:S.grace.until-S.day}),'goal',[{l:tr('common.open_noc'),act:'leftTab',args:{t:'noc'}}]);}
if(S.auNews){delete S.auNews;const c=Object.keys(S.pops).find(x=>CITY[x].au);toast(tr('loop.australia_got_more_australian'),'bad',[{l:tr('common.open'),act:'focusCity',args:{city:c}}],{a:'city',v:c});} if(S.auNews){delete S.auNews;const c=Object.keys(S.pops).find(x=>CITY[x].au);toast(tr('loop.australia_got_more_australian'),'bad',[{l:tr('common.open'),act:'focusCity',args:{city:c}}],{a:'city',v:c});}
@ -51,8 +51,9 @@ function boot(data){
// A save that cannot be loaded stays where it is, marked damaged: it can still be exported, or deleted. // A save that cannot be loaded stays where it is, marked damaged: it can still be exported, or deleted.
else if(UI.slot&&(sv||UI.loadBad))slotBroke(UI.slot); else if(UI.slot&&(sv||UI.loadBad))slotBroke(UI.slot);
else{showTitle();if(UI.bootBusy)slotBusyModal(UI.bootBusy);else whatsNew(false);if(UI.bootBroken)toast(tr('loop.your_saved_game_could_not_be'),'bad');}} else{showTitle();if(UI.bootBusy)slotBusyModal(UI.bootBusy);else whatsNew(false);if(UI.bootBroken)toast(tr('loop.your_saved_game_could_not_be'),'bad');}}
renderHUD();renderLeft(); renderHUD();renderLeft();if(MP_API)mpBootTell();
window.claude?.hot?.snapshot?.(()=>({S:S&&JSON.parse(JSON.stringify(S)),cam:{...cam}})); window.claude?.hot?.snapshot?.(()=>({S:S&&JSON.parse(JSON.stringify(S)),cam:{...cam}}));
if(!window.__TUBES_TEST__){requestAnimationFrame(frame);setTimeout(checkUpdate,4000);setInterval(checkUpdate,10*60*1000);} if(!window.__TUBES_TEST__){requestAnimationFrame(frame);setTimeout(checkUpdate,4000);setInterval(checkUpdate,10*60*1000);}
} }
if(NOC.win)nocWinBoot();else if(!RW_IN)slotBoot(()=>window.claude?.hot?.ready ? window.claude.hot.ready(boot) : boot(window.claude?.hot?.data ?? {})); // A #mp= link (a multiplayer network moving to this device) is read first: it picks the slot slotBoot opens.
if(NOC.win)nocWinBoot();else if(!RW_IN)mpBoot(()=>slotBoot(()=>window.claude?.hot?.ready ? window.claude.hot.ready(boot) : boot(window.claude?.hot?.data ?? {})));

View file

@ -3084,6 +3084,65 @@
"modal_and_names.the_real_thing_follow_a_packet":"The real thing: follow a packet from Wi-Fi to undersea fiber.", "modal_and_names.the_real_thing_follow_a_packet":"The real thing: follow a packet from Wi-Fi to undersea fiber.",
"modals.lay_your_own_subsea_cable":"Lay your own subsea cable…", "modals.lay_your_own_subsea_cable":"Lay your own subsea cable…",
"modals.your_own_subsea_cable_level_n":"Your own subsea cable <small>level {n} or Tier 1</small>", "modals.your_own_subsea_cable_level_n":"Your own subsea cable <small>level {n} or Tier 1</small>",
"mp.code":"Session code",
"mp.copy_link":"Copy the link",
"mp.door_d":"One world, your friends' networks next to yours: share a code and race to Tier 1.",
"mp.err_code":"A session code has six letters and digits, like K7Q-2XD.",
"mp.err_full":"That session is full: every seat in it is taken.",
"mp.err_no_session":"There is no session with that code.",
"mp.err_offline":"The multiplayer server cannot be reached right now. Try again in a moment.",
"mp.err_refused":"The server did not take that. Try another network name.",
"mp.err_server_full":"The server is not taking new sessions right now.",
"mp.err_slow":"Too many tries from here. Wait a little and try again.",
"mp.feed":"Feed",
"mp.feed_empty":"Nothing yet. Say hello!",
"mp.feed_join":"{name} joined the session.",
"mp.feed_leave":"{name} left the session.",
"mp.feed_t1":"{name} is Tier 1 too.",
"mp.feed_t1first":"{name} is the first Tier 1 in this session!",
"mp.feed_t2":"{name} made Tier 2.",
"mp.intro":"Everyone builds their own network in the same world, from the same day 0, under the same rules. The leaderboard and the feed show who is ahead.",
"mp.join":"Join",
"mp.join_a_session":"Join a session",
"mp.join_note":"The world and the rules come from whoever started the session, and the session hands you your AS number.",
"mp.joined":"<b>You joined session {code}.</b> Open the session to see who is ahead.",
"mp.keep_mine":"Keep this one",
"mp.leaderboard":"Leaderboard",
"mp.leave":"Leave the session",
"mp.leave_d":"{name} stays on this device as a game of its own. The session forgets it, and its save on the server is deleted.",
"mp.leave_q":"Leave session {code}?",
"mp.left":"You left the session. {name} plays on here on its own.",
"mp.link_bad":"That multiplayer link did not work: it is old, or that network never saved to the session.",
"mp.link_copied":"Link copied. Open it on your other device.",
"mp.load_newer":"Load the newer save",
"mp.loaded_newer":"Loaded the newer save of {name} from the session ({date}).",
"mp.loading":"Asking the server…",
"mp.move_device":"Move to another device",
"mp.move_note":"Open this link on your other phone or computer to carry on with this network there. Whichever device saves last wins.",
"mp.move_warn":"Anyone with this link can play as you. Keep it to yourself.",
"mp.moved_on_elsewhere":"<b>This session moved on elsewhere.</b> Your network was played on another device since. Load that save, or keep this one and overwrite it.",
"mp.multiplayer":"Multiplayer",
"mp.n_customers":{"one":"{n} customer","other":"{n} customers"},
"mp.n_pops":{"one":"{n} POP","other":"{n} POPs"},
"mp.no_card":"has not finished a day yet",
"mp.no_newer":"The session has no newer save of {name}. This one stays, and goes to the server with the next save.",
"mp.not_in_session":"This network is no longer in its session. It keeps playing here on its own.",
"mp.play_with_friends":"Play with friends",
"mp.save_unreadable":"The session's save of this network could not be read. Playing on with the one here.",
"mp.say":"Say something",
"mp.send":"Send",
"mp.server_away":"The multiplayer server is away. Your network keeps playing here and catches up when it is back.",
"mp.session":"Multiplayer session",
"mp.session_code":"Session {code}",
"mp.session_live":"<b>Session {code} is live.</b> Share the code: whoever joins builds in the same world.",
"mp.session_title":"Session name (optional)",
"mp.share_line":"Join my Series of Tubes session {code}: {url}",
"mp.share_note":"Friends join from the title screen: Multiplayer, then this code.",
"mp.slow_down":"Slow down a little: one line a second.",
"mp.start_a_session":"Start a session",
"mp.talking":"Talking to the server…",
"mp.welcome_device":"<b>{name}</b> moved to this device. Welcome back to session {code}.",
"mp.you":"you",
"networks.a_mobile_network_named_after_the":"A mobile network named after the sound of a toast. Cheers to every 5G tower.", "networks.a_mobile_network_named_after_the":"A mobile network named after the sound of a toast. Cheers to every 5G tower.",
"networks.a_spanish_carrier_starring_in_every":"A Spanish carrier starring in every Latin American market, at least until it sells the next one.", "networks.a_spanish_carrier_starring_in_every":"A Spanish carrier starring in every Latin American market, at least until it sells the next one.",
"networks.a_tiny_telco_in_a_country":"A tiny telco in a country where the world’s cables come ashore. Prices to match.", "networks.a_tiny_telco_in_a_country":"A tiny telco in a country where the world’s cables come ashore. Prices to match.",

View file

@ -0,0 +1,36 @@
/* Multiplayer (only in a copy built with MP_API): the title row, the start/join sheet, the session panel, the HUD chip. */
.mpdoor-row{margin-top:8px}.mpdoor{width:100%;background:var(--soft)}
.mpbox{border:2px dashed var(--line);border-radius:14px;padding:4px 12px 10px;margin-top:12px}
.mpbox h3,.mp-panel h3{font-family:var(--display);font-size:18px;margin:10px 0 4px}
.mpjoin,.mpchat{display:flex;gap:8px;align-items:center}
.mpjoin input.t,.mpchat input.t{flex:1 1 auto;min-width:0;width:auto}
#mpCode{text-transform:uppercase;letter-spacing:.12em;font-size:18px}
.mpchat input.t{font-size:16px;padding:6px 10px}
.mpcode{display:flex;align-items:center;gap:10px;border:3px solid var(--ink);border-radius:14px;padding:8px 12px;background:var(--soft);margin-top:10px}
.mpcode small{display:block;font-size:10.5px;font-weight:900;letter-spacing:.09em;text-transform:uppercase;color:var(--ink2)}
.mpcode b{font-family:var(--display);font-size:28px;letter-spacing:.08em;line-height:1.1}
.mpboard,.mpfeed{display:flex;flex-direction:column;gap:4px}
.mpfeed{max-height:220px;overflow:auto;margin-top:6px}
.mprow{display:flex;align-items:center;gap:8px;border:2px solid var(--line);border-radius:12px;padding:6px 10px;min-width:0}
.mprow.me{border-color:var(--me);background:#FFF2F8}
.mprow .grow,.mpf .grow{min-width:0;overflow-wrap:anywhere}
.mprow b{font-family:var(--display);font-size:15px}
.mprk{font:900 15px var(--display);width:20px;text-align:center;flex:0 0 auto}
.mpdot{display:inline-block;width:12px;height:12px;border-radius:50%;border:2px solid var(--ink);flex:0 0 auto}
.mpseen,.mpf small{color:var(--ink2);font-size:11px;white-space:nowrap;flex:0 0 auto}
.mpf{display:flex;align-items:baseline;gap:8px;font-size:13px;line-height:1.35}
.mpf .mpdot{width:9px;height:9px;border-width:1.5px}
.mpf.t1first{font-weight:800}
.mpmove{margin-top:12px}.mpmove summary{cursor:pointer;font-weight:800}
.mpmove input.t{font-size:12px;font-family:monospace;padding:6px 8px}
#hud .mpchip{border-width:3px}
/* No room for the chip on a phone (it is hide-sm), nor on a tablet whose top bar still wraps at fitHud's last step:
where you stand shows as a badge on the menu button, which also opens the session. */
#hud .menubtn{position:relative}
.mpbadge{display:none;position:absolute;top:-8px;right:-8px;background:var(--paper);color:var(--ink);border:2.5px solid var(--ink);border-radius:10px;font:900 11px Nunito,sans-serif;padding:0 5px;line-height:16px;pointer-events:none}
#hud.fit3 .mpchip{display:none !important}
#hud.fit3 .mpbadge{display:block}
@media (max-width:760px){
.mpcode b{font-size:24px}
.mpbadge{display:block}
}

View file

@ -14,8 +14,10 @@ const page = (dev) => PAGE[dev] || (PAGE[dev] = assemble({ dev }).html);
// opts.file: a built or older page to load instead (the perf bench, the release build test). // opts.file: a built or older page to load instead (the perf bench, the release build test).
// opts.agent: the development page, with src/agent/. // opts.agent: the development page, with src/agent/.
// opts.mp: the page with multiplayer on, as MP_API=… npm run build stamps it; opts.fetch: the page's fetch, from the start.
function load(opts = {}) { function load(opts = {}) {
const html = opts.file ? fs.readFileSync(opts.file, 'utf8') : page(!!opts.agent); let html = opts.file ? fs.readFileSync(opts.file, 'utf8') : page(!!opts.agent);
if (opts.mp) html = html.replace("/*__MP_API__*/''", () => JSON.stringify(opts.mp));
const errors = []; const errors = [];
const vc = new VirtualConsole(); const vc = new VirtualConsole();
vc.on('jsdomError', (e) => { vc.on('jsdomError', (e) => {
@ -38,6 +40,7 @@ function load(opts = {}) {
// channel and Web Locks, like real tabs; opts.tab is one tab's sessionStorage, which survives a reload. // channel and Web Locks, like real tabs; opts.tab is one tab's sessionStorage, which survives a reload.
if (opts.browser) opts.browser.attach(window, opts.tab || new Map(), opts); if (opts.browser) opts.browser.attach(window, opts.tab || new Map(), opts);
for (const [k, v] of Object.entries(opts.storage || {})) window.localStorage.setItem(k, v); for (const [k, v] of Object.entries(opts.storage || {})) window.localStorage.setItem(k, v);
if (opts.fetch) window.fetch = opts.fetch;
if (opts.navigatorLanguage) Object.defineProperty(window.navigator, 'language', { value: opts.navigatorLanguage }); if (opts.navigatorLanguage) Object.defineProperty(window.navigator, 'language', { value: opts.navigatorLanguage });
// A non-English game: jsdom does not fetch the dictionary script, so register it up front. // A non-English game: jsdom does not fetch the dictionary script, so register it up front.
// (opts.dir: the folder the dictionary comes from, e.g. a build's _site/i18n.) // (opts.dir: the folder the dictionary comes from, e.g. a build's _site/i18n.)

450
tests/mp-server.test.js Normal file
View file

@ -0,0 +1,450 @@
// The multiplayer server (scripts/mp-server.js, docs/MULTIPLAYER.md), run for real on a free port with its own data
// folder: sessions, joining, who may read and write what, saves that never overwrite a newer one, cards cleaned of
// junk, limits, leaving, data that survives a restart, and the built site served without escaping its folder. The
// tests of what happens while a request is still on its way run the API in this process (inproc), where a request can
// be held half-sent and the limits made small.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const http = require('node:http');
const { spawn, execFileSync } = require('node:child_process');
const { until, freePort, kill } = require('./net');
const { createMp, cleanCard, addrKey, limiter } = require('../scripts/lib/mp');
const root = path.join(__dirname, '..');
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-mp-'));
const children = new Set();
test.after(async () => { for (const c of children) await kill(c); fs.rmSync(tmp, { recursive: true, force: true }); });
async function start(opts = {}) {
const port = await freePort(), data = opts.data || fs.mkdtempSync(path.join(tmp, 'data-'));
const args = ['scripts/mp-server.js', '--port', String(port), '--data', data, '--create-per-hour', '50', ...(opts.args || [])];
const child = spawn(process.execPath, args, { cwd: root, stdio: ['ignore', 'pipe', 'pipe'] });
children.add(child);
let out = '';
child.stdout.on('data', (b) => { out += b; });
child.stderr.on('data', (b) => { out += b; });
assert.ok(await until(() => /multiplayer: http/.test(out) || child.exitCode !== null), 'the server starts');
assert.equal(child.exitCode, null, out);
const url = `http://127.0.0.1:${port}`;
const api = async (method, p, body, auth, headers = {}) => {
const r = await fetch(url + '/api/mp' + p, { method, headers: { ...(body !== undefined ? { 'content-type': 'application/json' } : {}), ...(auth ? { authorization: `Bearer ${auth.pid}.${auth.token}` } : {}), ...headers }, body: body === undefined ? undefined : typeof body === 'string' ? body : JSON.stringify(body) });
const t = await r.text();
let j = null; try { j = JSON.parse(t); } catch (e) { /* not JSON */ }
return { status: r.status, json: j, type: r.headers.get('content-type'), text: t };
};
return { child, port, url, data, api, out: () => out, stop: async () => { await kill(child); children.delete(child); } };
}
// A raw request, so paths reach the server exactly as written (fetch would tidy up "..").
const raw = (port, p) => new Promise((res, rej) => {
const r = http.request({ host: '127.0.0.1', port, path: p, method: 'GET' }, (x) => { let b = ''; x.on('data', (c) => { b += c; }); x.on('end', () => res({ status: x.statusCode, body: b, type: x.headers['content-type'] })); });
r.on('error', rej); r.end();
});
const make = (api, name = 'Packet Pals', home = 'fra', extra = {}) => api('POST', '/sessions', { net: { name, home }, preset: 'oncall', ...extra });
// The API in this process, with its own options (small limits), on a free port.
async function inproc(t, opts = {}) {
const dir = opts.dir || fs.mkdtempSync(path.join(tmp, 'data-'));
const mp = createMp({ dir, log: () => {}, ...opts });
const server = http.createServer((req, res) => { if (!mp.handle(req, res)) { res.writeHead(404); res.end(); } });
await new Promise((r) => server.listen(0, '127.0.0.1', r));
t.after(() => new Promise((r) => { server.closeAllConnections(); server.close(r); }));
const port = server.address().port, url = `http://127.0.0.1:${port}`;
const api = async (method, p, body, auth, headers = {}) => {
const r = await fetch(url + '/api/mp' + p, { method, headers: { ...(body !== undefined ? { 'content-type': 'application/json' } : {}), ...(auth ? { authorization: `Bearer ${auth.pid}.${auth.token}` } : {}), ...headers }, body: body === undefined ? undefined : JSON.stringify(body) });
const t = await r.text();
let j = null; try { j = JSON.parse(t); } catch (e) { /* not JSON */ }
return { status: r.status, json: j };
};
return { mp, dir, port, api };
}
// A request sent all but the last byte of its body: it stays on its way until release().
function held(port, method, p, body, auth, headers = {}) {
const b = Buffer.from(JSON.stringify(body));
let r;
const done = new Promise((res, rej) => {
r = http.request({ host: '127.0.0.1', port, path: '/api/mp' + p, method, headers: { 'content-type': 'application/json', 'content-length': b.length, ...(auth ? { authorization: `Bearer ${auth.pid}.${auth.token}` } : {}), ...headers } },
(x) => { let t = ''; x.on('data', (c) => { t += c; }); x.on('end', () => { let j = null; try { j = JSON.parse(t); } catch (e) { /* not JSON */ } res({ status: x.statusCode, json: j }); }); });
r.on('error', rej);
r.write(b.subarray(0, b.length - 1));
});
return { done, release: () => { r.end(b.subarray(b.length - 1)); return done; } };
}
const joinAs = (api, code, name, headers) => api('POST', `/sessions/${code}/join`, { net: { name, home: 'ams' } }, null, headers);
test('mp server: --help documents it; --base is a path on this server, never another host', () => {
const t = execFileSync(process.execPath, ['scripts/mp-server.js', '--help'], { cwd: root, encoding: 'utf8' });
for (const k of ['--port', '--host', '--data', '--site', '--prune-days', '--trust-proxy', '--sessions-per-hour', 'Authorization: Bearer', '/api/mp/sessions/:code/save']) assert.ok(t.includes(k), k);
for (const b of ['//evil-host/mp', '//api', 'api/mp', '/api/mp/']) assert.throws(() => execFileSync(process.execPath, ['scripts/mp-server.js', '--base', b, '--port', '1'], { cwd: root, stdio: 'pipe' }), /--base must be a path/, b);
});
test('mp server: start, join, roster; names cleaned; codes typed any way', async () => {
const s = await start();
const a = await make(s.api, ' <img src=x onerror=alert(1)> & "Co" ', 'fra', { preset: 'bgp', title: 'Friday <b>night</b>', avoid: [200000, 200001] });
assert.equal(a.status, 201);
assert.match(a.json.code, /^[0-9A-HJKMNP-TV-Z]{6}$/);
assert.match(a.json.pid, /^[a-z0-9]{8}$/);
assert.match(a.json.token, /^[0-9a-f]{64}$/);
assert.ok(Number.isInteger(a.json.seed) && a.json.seed >= -(2 ** 31) && a.json.seed < 2 ** 31);
assert.ok(a.json.asn >= 200000 && a.json.asn <= 214999);
assert.equal(a.json.preset, 'bgp');
assert.equal(a.json.title, 'Friday bnight/b');
// Joined by the code as a person types it: lower case, with a dash.
const typed = (a.json.code.slice(0, 3) + '-' + a.json.code.slice(3)).toLowerCase();
const b = await s.api('POST', `/sessions/${typed}/join`, { net: { name: 'Bee', home: 'nyc' }, preset: 'soft' });
assert.equal(b.status, 200);
assert.equal(b.json.code, a.json.code);
assert.equal(b.json.seed, a.json.seed, 'one world: the same seed');
assert.equal(b.json.preset, 'bgp', 'and the creator\'s rules');
assert.notEqual(b.json.asn, a.json.asn);
assert.notEqual(b.json.color, a.json.color);
const r = await s.api('GET', `/sessions/${a.json.code}`, undefined, a.json);
assert.equal(r.status, 200);
assert.equal(r.type, 'application/json; charset=utf-8');
assert.deepEqual(r.json.players.map((p) => p.name), ['img src=x onerror=alert(1) Co', 'Bee']);
assert.ok(r.json.players.every((p) => !('th' in p) && !('token' in p) && !('sv' in p)), 'no secrets in the roster');
assert.deepEqual(r.json.feed.map((f) => f.k), ['join', 'join']);
assert.ok(!JSON.stringify(r.json).includes(a.json.token));
// Junk names and homes are refused.
for (const net of [{ name: ' ', home: 'fra' }, { name: '<>&', home: 'fra' }, { name: 'ok', home: '../x' }, { name: 'ok' }]) assert.equal((await s.api('POST', '/sessions', { net, preset: 'oncall' })).status, 400, JSON.stringify(net));
assert.equal((await s.api('POST', '/sessions', { net: { name: 'x', home: 'fra' }, preset: 'sandbox' })).status, 400, 'only the Normal presets');
assert.equal((await s.api('POST', '/sessions', { net: { name: 'x'.repeat(80), home: 'fra' }, preset: 'soft' })).json.pid.length, 8);
await s.stop();
});
test('mp server: every call but start and join needs the player\'s token', async () => {
const s = await start();
const a = (await make(s.api)).json, b = (await s.api('POST', `/sessions/${a.code}/join`, { net: { name: 'Bee', home: 'nyc' } })).json;
const p = `/sessions/${a.code}`;
assert.equal((await s.api('GET', p)).status, 401);
assert.equal((await s.api('GET', p, undefined, { pid: a.pid, token: b.token })).status, 401, 'someone else\'s token');
assert.equal((await s.api('GET', p, undefined, { pid: a.pid, token: '0'.repeat(64) })).status, 401);
assert.equal((await s.api('GET', p, undefined, { pid: 'zzzzzzzz', token: a.token })).status, 401);
assert.equal((await s.api('GET', p, undefined, null, { authorization: 'Bearer nonsense' })).status, 401);
assert.equal((await s.api('PUT', p + '/card', { card: {} })).status, 401);
assert.equal((await s.api('PUT', p + '/save', { seq: 1, at: 1, data: '{}' })).status, 401);
assert.equal((await s.api('GET', p + '/save')).status, 401);
assert.equal((await s.api('POST', p + '/feed', { text: 'hi' })).status, 401);
assert.equal((await s.api('DELETE', p + '/me')).status, 401);
assert.equal((await s.api('GET', p, undefined, a)).status, 200);
assert.equal((await s.api('GET', '/sessions/ZZZZZZ', undefined, a)).status, 404);
assert.equal((await s.api('DELETE', p, undefined, a)).status, 405);
assert.equal((await s.api('GET', '/nope')).status, 404);
await s.stop();
});
test('mp server: a save never overwrites a newer one unless forced', async () => {
const s = await start();
const a = (await make(s.api)).json, b = (await s.api('POST', `/sessions/${a.code}/join`, { net: { name: 'Bee', home: 'nyc' } })).json;
const p = `/sessions/${a.code}/save`;
assert.equal((await s.api('GET', p, undefined, a)).status, 404, 'nothing saved yet');
const s1 = await s.api('PUT', p, { seq: 1, at: 1000, data: '{"v":1,"day":3}' }, a);
assert.equal(s1.status, 200);
assert.equal(s1.json.seq, 1);
assert.equal(s1.json.roster.players.length, 2, 'the roster rides along');
assert.deepEqual((await s.api('GET', p, undefined, a)).json, { seq: 1, at: 1000, data: '{"v":1,"day":3}' });
assert.equal((await s.api('GET', p, undefined, b)).status, 404, 'only your own save');
const stale = await s.api('PUT', p, { seq: 1, at: 2000, data: '{"v":1,"day":1}' }, a);
assert.equal(stale.status, 409);
assert.equal(stale.json.seq, 1);
assert.equal((await s.api('PUT', p, { seq: 0, at: 1, data: '{}' }, a)).status, 400);
assert.equal((await s.api('PUT', p, { seq: 1.5, at: 1, data: '{}' }, a)).status, 400);
assert.equal((await s.api('PUT', p, { seq: 9, at: 1, data: 'not a save' }, a)).status, 400);
const g = await s.api('PUT', p, { seq: 2, at: 3000, data: 'gz:H4sIAAAA' }, a);
assert.equal(g.json.seq, 2, 'compressed saves are kept as they are');
const f = await s.api('PUT', p, { seq: 1, at: 4000, data: '{"v":1,"day":9}', force: true }, a);
assert.equal(f.status, 200);
assert.equal(f.json.seq, 3, 'forced: it becomes the newest');
assert.deepEqual((await s.api('GET', p, undefined, a)).json, { seq: 3, at: 4000, data: '{"v":1,"day":9}' });
await s.stop();
});
test('mp server: cards keep only what the leaderboard needs, and tell the feed about Tier 1', async () => {
const s = await start();
const a = (await make(s.api)).json, b = (await s.api('POST', `/sessions/${a.code}/join`, { net: { name: 'Bee', home: 'nyc' } })).json;
const junk = { day: 1e12, name: 'Evil', asn: 1, tier: 't0', t1: 'yes', lvl: -5, pops: ['fra', 'fra', '<script>', 'nyc', 7], links: [['fra', 'nyc', 1e99], ['fra', 'fra', 5], ['a"b', 'nyc', 1], 'x', ['ams', 'fra', 'NaN']],
ix: ['fra', 'fra~2', '../etc'], transit: ['cog', 'x'.repeat(40)], ppol: 'evil', reach: 7, peak: -3, served: 'lots', cust: 3.7, rev: 1e20, cashB: 99, score: -1, extra: { deep: true }, __proto__x: 1 };
const r = await s.api('PUT', `/sessions/${a.code}/card`, { card: junk }, a);
assert.equal(r.status, 200);
const c = r.json.players.find((p) => p.pid === a.pid).card;
assert.deepEqual(Object.keys(c).sort(), ['cashB', 'cust', 'day', 'ix', 'links', 'lvl', 'peak', 'pops', 'ppol', 'reach', 'rev', 'score', 'served', 't1', 'tier', 'transit']);
assert.deepEqual(c, { day: 1e7, tier: 't3', t1: false, lvl: 0, pops: ['fra', 'nyc'], links: [['fra', 'nyc', 1e7], ['ams', 'fra', 0]], ix: ['fra', 'fra~2'], transit: ['cog'], ppol: 'open', reach: 1, peak: 0, served: 0, cust: 4, rev: 1e13, cashB: 20, score: 0 });
assert.equal(r.json.players.find((p) => p.pid === a.pid).name, 'Packet Pals', 'the name is the server\'s, not the card\'s');
assert.equal((await s.api('PUT', `/sessions/${a.code}/card`, { card: [1, 2] }, a)).status, 400);
// Tier 2, then Tier 1: the first in the session gets the headline, the next one a plain line.
await s.api('PUT', `/sessions/${a.code}/card`, { card: { tier: 't2' } }, a);
await s.api('PUT', `/sessions/${a.code}/card`, { card: { tier: 't1', t1: true } }, a);
await s.api('PUT', `/sessions/${a.code}/card`, { card: { tier: 't1', t1: true } }, a);
const f = (await s.api('PUT', `/sessions/${a.code}/card`, { card: { tier: 't1', t1: true } }, b)).json.feed;
assert.deepEqual(f.map((x) => x.k), ['join', 'join', 't2', 't1first', 't1']);
assert.equal(f[3].pid, a.pid);
// A network that drops out (transit again, a de-peering) and comes back is not news again: each milestone once.
for (const c of [{ tier: 't2' }, { tier: 't1', t1: true }, { tier: 't3' }, { tier: 't2' }, { tier: 't1', t1: true }]) for (const who of [a, b]) assert.equal((await s.api('PUT', `/sessions/${a.code}/card`, { card: c }, who)).status, 200);
const again = (await s.api('GET', `/sessions/${a.code}`, undefined, a)).json.feed;
assert.deepEqual(again.map((x) => x.k), ['join', 'join', 't2', 't1first', 't1'], 'the first Tier 1 is never "Tier 1 too"');
await s.stop();
});
test('mp server: chat lines are cleaned, capped and rate-limited; the feed keeps the last 100', async () => {
const s = await start();
const a = (await make(s.api)).json;
const p = `/sessions/${a.code}/feed`;
const r = await s.api('POST', p, { text: ' hello\u0000‮ <b>world</b> ' + 'x'.repeat(300) }, a);
assert.equal(r.status, 200);
const line = r.json.feed.at(-1);
assert.equal(line.k, 'chat');
assert.equal(line.text.length, 200);
assert.ok(line.text.startsWith('hello <b>world</b> x'), 'control characters go; the page escapes the rest');
assert.equal((await s.api('POST', p, { text: 'again' }, a)).status, 429, 'one line a second');
assert.equal((await s.api('POST', p, { text: ' ' }, a)).status, 400);
await s.stop();
});
test('mp server: limits: body sizes, JSON only, odd codes, twelve players', async () => {
const s = await start();
const a = (await make(s.api)).json;
const big = await s.api('PUT', `/sessions/${a.code}/save`, { seq: 1, at: 1, data: '{' + 'x'.repeat(5 * 1024 * 1024) }, a);
assert.equal(big.status, 413, 'a save over 4 MB is refused');
assert.equal((await s.api('PUT', `/sessions/${a.code}/card`, { card: { pops: Array(5000).fill('fra') } }, a)).status, 413, 'small calls take small bodies');
assert.equal((await s.api('POST', '/sessions', 'name=x', null, { 'content-type': 'application/x-www-form-urlencoded' })).status, 415);
assert.equal((await s.api('POST', '/sessions', '{"net":', null)).status, 400);
assert.equal((await s.api('POST', '/sessions', '[1]', null)).status, 400);
// A code is checked before it is ever a file name.
for (const p of ['/api/mp/sessions/..%2F..%2Fetc%2Fpasswd', '/api/mp/sessions/%2e%2e', '/api/mp/sessions/../../package.json', `/api/mp/sessions/${a.code}%00/save`, '/api/mp/sessions/%E0%A4%A']) {
const x = await raw(s.port, p);
assert.ok([404, 400].includes(x.status), `${p}: ${x.status}`);
assert.doesNotMatch(x.body, /root:|"name": "seriesoftubes"/);
}
const join = (i) => s.api('POST', `/sessions/${a.code}/join`, { net: { name: 'P' + i, home: 'ams' } });
for (let i = 2; i <= 12; i++) assert.equal((await join(i)).status, 200, `player ${i}`);
const full = await join(13);
assert.equal(full.status, 409);
assert.equal(full.json.full, true);
const ro = (await s.api('GET', `/sessions/${a.code}`, undefined, a)).json;
assert.equal(ro.players.length, 12);
assert.equal(new Set(ro.players.map((p) => p.asn)).size, 12, 'every AS number its own');
assert.equal(new Set(ro.players.map((p) => p.color)).size, 12, 'and every colour');
assert.deepEqual(fs.readdirSync(s.data).filter((f) => !/^[0-9A-Z]{6}\.json$/.test(f)), [], 'nothing but session files in the data folder');
await s.stop();
});
test('mp server: leaving removes the player and their save; the last one out closes the session', async () => {
const s = await start();
const a = (await make(s.api)).json, b = (await s.api('POST', `/sessions/${a.code}/join`, { net: { name: 'Bee', home: 'nyc' } })).json;
await s.api('PUT', `/sessions/${a.code}/save`, { seq: 1, at: 1, data: '{}' }, b);
assert.ok(fs.existsSync(path.join(s.data, `${a.code}.${b.pid}.save`)));
assert.equal((await s.api('DELETE', `/sessions/${a.code}/me`, undefined, b)).status, 200);
assert.ok(!fs.existsSync(path.join(s.data, `${a.code}.${b.pid}.save`)), 'their save is gone');
assert.equal((await s.api('GET', `/sessions/${a.code}`, undefined, b)).status, 401, 'and so is their access');
const ro = (await s.api('GET', `/sessions/${a.code}`, undefined, a)).json;
assert.deepEqual(ro.players.map((p) => p.pid), [a.pid]);
assert.equal(ro.feed.at(-1).k, 'leave');
assert.equal((await s.api('DELETE', `/sessions/${a.code}/me`, undefined, a)).status, 200);
assert.equal((await s.api('POST', `/sessions/${a.code}/join`, { net: { name: 'Late', home: 'nyc' } })).status, 404, 'an empty session is gone');
assert.ok(!fs.existsSync(path.join(s.data, `${a.code}.json`)));
await s.stop();
});
test('mp server: data survives a restart; sessions nobody touched for too long are pruned', async () => {
const s = await start();
const a = (await make(s.api)).json;
await s.api('PUT', `/sessions/${a.code}/save`, { seq: 4, at: 42, data: '{"v":1}', card: { day: 12, pops: ['fra'], tier: 't2' } }, a);
await s.api('PUT', `/sessions/${a.code}/card`, { card: { day: 13, pops: ['fra'], tier: 't2' } }, a);
// An old session left behind, untouched for 100 days.
const old = path.join(s.data, 'ABCDEF.json');
fs.writeFileSync(old, JSON.stringify({ v: 1, code: 'ABCDEF', players: [], feed: [] }));
fs.writeFileSync(path.join(s.data, 'ABCDEF.abcdabcd.save'), '{}');
const t = (Date.now() - 100 * 86400000) / 1000;
fs.utimesSync(old, t, t);
await s.stop();
const s2 = await start({ data: s.data, args: ['--prune-days', '60'] });
assert.ok(!fs.existsSync(old), 'the old session is pruned');
assert.ok(!fs.existsSync(path.join(s.data, 'ABCDEF.abcdabcd.save')), 'with its saves');
const ro = await s2.api('GET', `/sessions/${a.code}`, undefined, a);
assert.equal(ro.status, 200, 'the token still works');
assert.equal(ro.json.players[0].card.day, 13, 'a card is written a moment later, and before the server stops');
assert.deepEqual((await s2.api('GET', `/sessions/${a.code}/save`, undefined, a)).json, { seq: 4, at: 42, data: '{"v":1}' });
assert.equal((await s2.api('PUT', `/sessions/${a.code}/save`, { seq: 4, at: 43, data: '{}' }, a)).status, 409, 'and the sequence with it');
await s2.api('PUT', `/sessions/${a.code}/card`, { card: { tier: 't3' } }, a);
const fd = (await s2.api('PUT', `/sessions/${a.code}/card`, { card: { tier: 't2' } }, a)).json.feed;
assert.deepEqual(fd.map((x) => x.k), ['join', 't2'], 'and what the feed already told');
await s2.stop();
});
test('mp server: --site serves the built game like GitHub Pages, and nothing outside it', async () => {
const site = fs.mkdtempSync(path.join(tmp, 'site-'));
fs.writeFileSync(path.join(site, 'index.html'), '<!doctype html><title>game</title>');
fs.writeFileSync(path.join(site, '404.html'), '<!doctype html><title>lost</title>');
fs.writeFileSync(path.join(site, 'sw.js'), '// sw');
fs.mkdirSync(path.join(site, 'i18n'));
fs.writeFileSync(path.join(site, 'i18n', 'de.js'), '// de');
fs.writeFileSync(path.join(tmp, 'secret.txt'), 'secret');
const s = await start({ args: ['--site', site] });
const home = await raw(s.port, '/');
assert.equal(home.status, 200);
assert.match(home.type, /^text\/html/);
assert.match(home.body, /game/);
const js = await raw(s.port, '/i18n/de.js?v=1');
assert.equal(js.status, 200);
assert.match(js.type, /^text\/javascript/);
const miss = await raw(s.port, '/nope.html');
assert.equal(miss.status, 404);
assert.match(miss.body, /lost/);
for (const p of ['/../secret.txt', '/%2e%2e/secret.txt', '/..%2fsecret.txt', '/i18n/..%2F..%2Fsecret.txt', '/%2e%2e%5csecret.txt']) {
const x = await raw(s.port, p);
assert.notEqual(x.body, 'secret', p);
}
// A path the file system cannot even look at (a name too long for it) is simply not there: the 404 page, no log.
for (const p of ['/' + 'a'.repeat(300), '/x/../../' + 'a'.repeat(300) + '/b', '/i18n/' + 'b'.repeat(4000)]) {
const x = await raw(s.port, p);
assert.equal(x.status, 404, p.slice(0, 20));
assert.match(x.body, /lost/);
}
assert.doesNotMatch(s.out(), /ENAMETOOLONG|\n\s+at /, 'no stack traces from what a client asked');
assert.equal((await s.api('POST', '/sessions', { net: { name: 'x', home: 'fra' }, preset: 'soft' })).status, 201, 'the API rides along');
await s.stop();
});
test('mp server: saves and cards are throttled: one save at a time per player, a few uploads at once, a few a minute', async (t) => {
const s = await inproc(t, { trustProxy: true, maxUploads: 3, maxUploadsPerAddress: 2, savesPerMinute: 4, cardsPerMinute: 3, persistMs: 60000 });
const at = (n) => ({ 'x-forwarded-for': `198.51.100.${n}` });
const a = (await s.api('POST', '/sessions', { net: { name: 'Alpha', home: 'fra' }, preset: 'oncall' }, null, at(1))).json, code = a.code;
const [b, c, d] = await Promise.all(['Bee', 'Cee', 'Dee'].map(async (n, i) => (await joinAs(s.api, code, n, at(i + 1))).json));
const p = `/sessions/${code}/save`, save = (seq) => ({ seq, at: seq, data: `{"v":1,"day":${seq}}` });
// A save on its way holds its place: the same player's next one waits its turn (a token costs nothing, a place does).
const h1 = held(s.port, 'PUT', p, save(1), a, at(1));
assert.ok(await until(() => s.mp.uploads() === 1));
const again = await s.api('PUT', p, save(2), a, at(1));
assert.equal(again.status, 429);
assert.match(again.json.error, /still on its way/);
// Another player from the same address may upload too; a third one from there waits; the whole server takes three.
const h2 = held(s.port, 'PUT', p, save(1), b, at(1));
assert.ok(await until(() => s.mp.uploads() === 2));
assert.equal((await s.api('PUT', p, save(1), c, at(1))).status, 503, 'two at once from one address');
const h3 = held(s.port, 'PUT', p, save(1), c, at(2));
assert.ok(await until(() => s.mp.uploads() === 3));
const busy = await s.api('PUT', p, save(1), d, at(3));
assert.equal(busy.status, 503, 'three at once on the server');
assert.equal(busy.json.busy, true, 'and says it is only busy, so the game waits quietly');
for (const h of [h1, h2, h3]) assert.equal((await h.release()).status, 200);
assert.equal(s.mp.uploads(), 0, 'and the places are free again');
// Not too often: four saves a minute here (the game sends one every 15 s at most).
for (const sq of [2, 3, 4]) assert.equal((await s.api('PUT', p, save(sq), a, at(1))).status, 200);
const often = await s.api('PUT', p, save(5), a, at(1));
assert.equal(often.status, 429);
assert.equal((await s.api('GET', p, undefined, a)).json.seq, 4, 'the refused one changed nothing');
// Stored as it was sent: the save's own text, not wrapped and copied again.
assert.equal(fs.readFileSync(path.join(s.dir, `${code}.${a.pid}.save`), 'utf8'), '{"v":1,"day":4}');
// Cards: three a minute here; their session is written once a moment later, not on every push.
const file = () => JSON.parse(fs.readFileSync(path.join(s.dir, code + '.json'), 'utf8')).players.find((x) => x.pid === b.pid).card;
for (const day of [5, 6, 7]) assert.equal((await s.api('PUT', `/sessions/${code}/card`, { card: { day } }, b, at(1))).status, 200);
assert.equal((await s.api('PUT', `/sessions/${code}/card`, { card: { day: 8 } }, b, at(1))).status, 429);
assert.equal(file(), null, 'not written on every push');
await s.mp.flush();
assert.equal(file().day, 7, 'but before the server stops');
});
test('mp server: wrong codes from an address stop guessing there, never the players of a session there', async (t) => {
const s = await inproc(t, { missesPerHour: 5 });
const a = (await make(s.api)).json, p = `/sessions/${a.code}`, fake = { pid: a.pid, token: '0'.repeat(64) };
assert.equal((await s.api('PUT', p + '/save', { seq: 1, at: 1, data: '{}' }, a)).status, 200);
// A wrong token on a real code is no guess at codes: it does not count.
for (let i = 0; i < 8; i++) assert.equal((await s.api('GET', p, undefined, fake)).status, 401);
for (let i = 0; i < 5; i++) assert.equal((await s.api('GET', `/sessions/ZZZZZ${i}`)).status, 404, `wrong code ${i}`);
// Locked out here: the player who has the code and its token carries on as before.
assert.equal((await s.api('PUT', p + '/save', { seq: 2, at: 2, data: '{}' }, a)).status, 200);
assert.equal((await s.api('GET', p + '/save', undefined, a)).status, 200);
assert.equal((await s.api('GET', p, undefined, a)).status, 200);
assert.equal((await s.api('PUT', p + '/card', { card: { day: 2 } }, a)).status, 200);
assert.equal((await s.api('POST', p + '/feed', { text: 'still here' }, a)).status, 200);
// Everyone else from here gets one and the same answer, whichever way they ask: it tells nobody which codes exist.
const tries = [
s.api('GET', p), s.api('GET', p, undefined, fake), s.api('GET', p, undefined, null, { authorization: 'Bearer nonsense' }),
s.api('GET', '/sessions/ZZZZZZ', undefined, a), s.api('GET', '/sessions/ZZZZZZ', undefined, fake),
s.api('POST', p + '/join', { net: { name: 'Late', home: 'nyc' } }), s.api('POST', '/sessions/ZZZZZZ/join', { net: { name: 'Late', home: 'nyc' } }),
];
const got = await Promise.all(tries);
assert.deepEqual(got.map((x) => x.status), got.map(() => 429));
assert.equal(new Set(got.map((x) => JSON.stringify(x.json))).size, 1);
});
test('mp server: a save that is refused, or cannot be written, leaves the server\'s number as it was', async (t) => {
const s = await inproc(t);
const a = (await make(s.api)).json, p = `/sessions/${a.code}/save`;
assert.equal((await s.api('PUT', p, { seq: 1, at: 1, data: '{"v":1,"day":1}' }, a)).status, 200);
assert.equal((await s.api('PUT', p, { seq: 2, at: 2, data: '{"v":1,"day":2}', card: 5 }, a)).status, 400, 'a bad card');
const ok = await s.api('PUT', p, { seq: 2, at: 2, data: '{"v":1,"day":2}' }, a);
assert.equal(ok.status, 200, 'the same number again: the refused one never counted');
assert.deepEqual((await s.api('GET', p, undefined, a)).json, { seq: 2, at: 2, data: '{"v":1,"day":2}' });
if (process.getuid && process.getuid() === 0) return;// root writes anywhere: no way to make the disk refuse here
fs.chmodSync(s.dir, 0o555);
let r;
try { r = await s.api('PUT', p, { seq: 3, at: 3, data: '{"v":1,"day":3}' }, a); } finally { fs.chmodSync(s.dir, 0o755); }
assert.equal(r.status, 500, 'the disk said no');
assert.deepEqual((await s.api('GET', p, undefined, a)).json, { seq: 2, at: 2, data: '{"v":1,"day":2}' }, 'the server does not claim a save it does not have');
assert.equal((await s.api('PUT', p, { seq: 3, at: 3, data: '{"v":1,"day":3}' }, a)).status, 200, 'and the player is not told someone else saved');
await s.mp.flush();
assert.equal(JSON.parse(fs.readFileSync(path.join(s.dir, a.code + '.json'), 'utf8')).players[0].sv.seq, 3);
assert.equal(fs.readFileSync(path.join(s.dir, `${a.code}.${a.pid}.save`), 'utf8'), '{"v":1,"day":3}');
});
test('mp server: an IPv6 /64 counts as one address, the server fills slowly, and the limits\' memory stays bounded', async (t) => {
assert.equal(addrKey('2001:db8:1:2::5'), '2001:db8:1:2::/64');
assert.equal(addrKey('2001:DB8:1:2:aa:bb:cc:dd'), '2001:db8:1:2::/64');
assert.equal(addrKey('2001:db8::1'), '2001:db8:0:0::/64');
assert.equal(addrKey('::ffff:198.51.100.7'), '198.51.100.7', 'an IPv4 address in IPv6 clothes');
assert.equal(addrKey('fe80::1%eth0'), 'fe80:0:0:0::/64');
for (const bad of ['', 'nonsense', '1.2.3', '::g']) assert.equal(addrKey(bad), null, bad);
const s = await inproc(t, { trustProxy: true, createPerHour: 3, sessionsPerHour: 8 });
const mk = async (ip) => (await s.api('POST', '/sessions', { net: { name: 'X', home: 'fra' }, preset: 'soft' }, null, { 'x-forwarded-for': ip })).status;
const one64 = [];
for (let i = 1; i <= 6; i++) one64.push(await mk(`2001:db8:1:2::${i}`));
assert.deepEqual(one64, [201, 201, 201, 429, 429, 429], 'six addresses of one /64 are one address');
const v4 = [];
for (const ip of ['198.51.100.7', '::ffff:198.51.100.7', '198.51.100.7', '::ffff:198.51.100.7']) v4.push(await mk(ip));
assert.deepEqual(v4, [201, 201, 201, 429]);
assert.equal(await mk('2001:db8:1:3::1'), 201, 'the next /64 is someone else');
assert.equal(await mk('2001:db8:1:4::1'), 201);
assert.equal(await mk('2001:db8:1:5::1'), 503, 'eight new sessions an hour here, from everywhere together');
// Keys go oldest first above the cap, and once nobody used them for a whole window: no call walks them all.
const L = limiter(2, 1000, 50);
for (let i = 0; i < 1000; i++) L.ok('k' + i, i);
assert.ok(L.size() <= 51, `${L.size()} keys`);
assert.equal(L.ok('k999', 1000), true);
assert.equal(L.ok('k999', 1000), false, 'still counting');
L.ok('late', 5000);
assert.equal(L.size(), 1, 'the old ones went');
});
test('mp server: a save still on its way when its player leaves is dropped, and never brings the session back', async (t) => {
const s = await inproc(t);
const a = (await make(s.api)).json, b = (await joinAs(s.api, a.code, 'Bee')).json, p = `/sessions/${a.code}`;
const big = { seq: 1, at: 1, data: '{"x":"' + 'y'.repeat(100000) + '"}', card: { tier: 't2' } };
const hb = held(s.port, 'PUT', p + '/save', big, b);
assert.ok(await until(() => s.mp.uploads() === 1));
assert.equal((await s.api('DELETE', p + '/me', undefined, b)).status, 200);
assert.equal((await hb.release()).status, 401, 'the player left meanwhile');
await s.mp.flush();
assert.deepEqual(fs.readdirSync(s.dir), [a.code + '.json'], 'no save left behind');
assert.deepEqual((await s.api('GET', p, undefined, a)).json.feed.map((f) => f.k), ['join', 'join', 'leave'], 'nor news from someone gone');
// The last one out, with a save on its way.
const ha = held(s.port, 'PUT', p + '/save', big, a);
assert.ok(await until(() => s.mp.uploads() === 1));
assert.equal((await s.api('DELETE', p + '/me', undefined, a)).status, 200);
assert.equal((await ha.release()).status, 401);
await s.mp.flush();
assert.deepEqual(fs.readdirSync(s.dir), [], 'the session is gone, files and all');
assert.equal(createMp({ dir: s.dir, log: () => {} }).sessions(), 0, 'and stays gone after a restart');
});
test('mp server: a card padded with copies costs no more than an honest one', () => {
const ids = Array.from({ length: 499 }, (_, i) => 'c' + i);
let looked = 0;
const spy = (a) => new Proxy(a, { get(o, k) { if (typeof k === 'string' && /^\d+$/.test(k)) looked++; return o[k]; } });
const c = cleanCard({ pops: spy([...ids, ...Array(400000).fill('c498')]), ix: spy([...ids, ...Array(400000).fill('c498')]), links: spy(Array(400000).fill(['fra', 'fra', 1])) });
assert.deepEqual(c.pops, ids);
assert.deepEqual(c.ix, ids);
assert.deepEqual(c.links, []);
assert.ok(looked <= 2 * 4 * 500 + 1200, `${looked} entries looked at`);
});

790
tests/multiplayer.test.js Normal file
View file

@ -0,0 +1,790 @@
// Multiplayer in the page (src/game/60-features/89-multiplayer.js, docs/MULTIPLAYER.md): off in every plain build, and
// with MP_API stamped, starting and joining sessions, the public card, when saves go to the server, a newer save from
// another device, the #mp= link, other players' data shown as text, the session panel on a phone, and old saves.
// The server is faked here (its own tests: tests/mp-server.test.js), except in the last test, which plays two pages
// against the real one.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const http = require('node:http');
const { execFileSync } = require('node:child_process');
const { load, flush, browser } = require('./harness');
const { until } = require('./net');
const { lit } = require('../scripts/lib/js-literal');
const MPA = '/api/mp', CODE = 'K7Q2XD', PID = 'abcd1234', TOK = 'a1'.repeat(32);
const JOINED = { code: CODE, pid: PID, token: TOK, seed: 424242, asn: 201234, preset: 'bgp', color: '#3a86ff', title: 'Friday' };
const roster = (players = [], feed = []) => ({ code: CODE, title: 'Friday', preset: 'bgp', seed: 424242, created: 1, players, feed });
const me = (card = null) => ({ pid: PID, name: 'Packet Pals', asn: 201234, color: '#3a86ff', card, seen: Date.now(), joined: 1 });
// A fake session server: routes are [regexp on "METHOD url", reply | (call) => reply], a reply {status, json}, an Error,
// or a promise of either (an answer still on its way; a call the page aborts meanwhile fails, as fetch does).
function fake(routes = []) {
const calls = [];
const res = (r) => r instanceof Error ? Promise.reject(r) : Promise.resolve({ ok: r.status < 400, status: r.status, json: () => Promise.resolve(r.json) });
const f = (url, o = {}) => {
const c = { url: String(url), method: o.method || 'GET', raw: o.body, body: o.body ? JSON.parse(o.body) : undefined, headers: o.headers || {}, keepalive: !!o.keepalive, signal: o.signal };
calls.push(c);
for (const [re, h] of f.routes) if (re.test(`${c.method} ${c.url}`)) {
const r = typeof h === 'function' ? h(c) : h;
if (!r || typeof r.then !== 'function') return res(r);
return new Promise((ok, no) => { if (o.signal) o.signal.addEventListener('abort', () => no(new Error('aborted'))); r.then((x) => res(x).then(ok, no)); });
}
return Promise.resolve({ ok: false, status: 404, json: () => Promise.resolve({ error: 'not here' }) });
};
f.routes = routes; f.calls = calls;
f.saves = () => calls.filter((c) => c.method === 'PUT' && /\/save$/.test(c.url));
return f;
}
const okSave = [/^PUT \/api\/mp\/sessions\/K7Q2XD\/save$/, (c) => ({ status: 200, json: { ok: true, seq: c.body.seq, at: c.body.at, roster: roster([me(c.body.card)]) } })];
const okStart = [/^POST \/api\/mp\/sessions$/, { status: 201, json: JOINED }];
// A small model of the real server's saves: a number must grow unless forced (409 with the server's number otherwise).
// st.hold: the next save's answer waits until st.go() (an upload still on its way).
function store() {
const st = { save: null, hold: false, go: null };
const put = (c) => {
const old = st.save;
if (old && c.body.seq <= old.seq && c.body.force !== true) return { status: 409, json: { error: 'newer', seq: old.seq, at: old.at } };
const sq = old && c.body.seq <= old.seq ? old.seq + 1 : c.body.seq;
st.save = { seq: sq, at: c.body.at, data: c.body.data };
return { status: 200, json: { ok: true, seq: sq, at: c.body.at, roster: roster([me(c.body.card)]) } };
};
const routes = [okStart,
[/^PUT \/api\/mp\/sessions\/K7Q2XD\/save$/, (c) => { if (!st.hold || c.keepalive) return put(c); st.hold = false; return new Promise((r) => { st.go = () => r(put(c)); }); }],
[/^PUT \/api\/mp\/sessions\/K7Q2XD\/card$/, (c) => ({ status: 200, json: roster([me(c.body.card)]) })],
[/^GET \/api\/mp\/sessions\/K7Q2XD\/save$/, () => st.save ? { status: 200, json: st.save } : { status: 404, json: { error: 'no save yet' } }],
[/^GET \/api\/mp\/sessions\/K7Q2XD$/, { status: 200, json: roster([me()]) }]];
return { st, routes, day: () => JSON.parse(st.save.data).day };
}
const storageOf = (h) => { const o = {}; for (const k of JSON.parse(h.ev('JSON.stringify(Object.keys(localStorage))'))) if (!k.startsWith('sot-open:')) o[k] = h.ev(`localStorage.getItem(${lit(k)})`); return o; };
const hide = (on = true) => `Object.defineProperty(document,'visibilityState',{configurable:true,get:()=>${lit(on ? 'hidden' : 'visible')}});document.dispatchEvent(new Event('visibilitychange'));`;
const quiet = 'S.nextFail=S.nextEvent=1e9;UI.speed=0;closeModal();';
// Start a session from the title screen, as a player does.
async function started(opts = {}) {
const f = opts.fetch || fake([okStart, okSave]);
const h = load({ mp: MPA, fetch: f, ...opts.load });
h.ev(`UI.pitched=true;ACT.mpDoor({});document.getElementById('mpName').value=${lit(opts.name || 'Packet Pals')};ACT.presetSet({p:'bgp'});ACT.mpStart({})`);
assert.ok(await until(() => h.ev('!!(S&&S.mp)')), 'the game started');
await until(() => h.ev('!MP.busy'));
h.ev(quiet);
return { ...h, f };
}
test('multiplayer: a plain build has no door, no chip, no tile and makes no request at all', async () => {
const f = fake();
const { dom, ev, errors } = load({ fetch: f });
const doc = dom.window.document;
assert.equal(ev('MP_API'), '');
assert.equal(doc.querySelector('.mpdoor'), null, 'no door on the title screen');
ev(`ACT.start({});if(UI.pendGame)ACT.pitchSkip();${quiet}ACT.launchBB({city:'fra'});for(let i=0;i<5;i++)dayTick();save(true);ACT.menu({})`);
assert.equal(doc.querySelector('[data-act=mpOpen]'), null, 'no session tile in the menu');
assert.equal(doc.getElementById('hMp'), null, 'no chip in the HUD');
ev('ACT.mpDoor({});ACT.mpOpen({});mpPush("{}",{now:true});mpResume();mpRefresh()');
// A save carrying a session (from a copy that has one) loads and plays, and still talks to nobody.
ev(`S.mp={code:'${CODE}',pid:'${PID}',asn:201234,seed:1,preset:'bgp',color:'#3a86ff',title:'',seq:3};S=migrate(JSON.parse(JSON.stringify(S)));dayTick();save(true);renderAll()`);
assert.equal(ev('S.mp.code'), CODE, 'the session stays in the save');
assert.equal(doc.getElementById('hMp'), null);
await flush();
assert.deepEqual(f.calls, [], 'not one request');
assert.deepEqual(errors, []);
});
test('multiplayer: the build stamps MP_API only when asked, and only a same-origin path', () => {
const root = path.join(__dirname, '..'), OUT = fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-mp-build-'));
const build = (env) => execFileSync(process.execPath, ['scripts/build.js'], { cwd: root, stdio: 'pipe', env: { ...process.env, OUT, VERSION: '1.2.3', BUILD_DATE: '2026-11-06', ...env } });
build({ MP_API: '/api/mp' });
const html = fs.readFileSync(path.join(OUT, 'index.html'), 'utf8');
assert.match(html, /const MP_API='\/api\/mp';/);
assert.doesNotMatch(html, /__MP_API__/);
const { ev, errors } = load({ file: path.join(OUT, 'index.html'), fetch: fake() });
assert.equal(ev('MP_API'), '/api/mp');
assert.ok(ev("!!document.querySelector('.mpdoor')"), 'the built page has the door');
assert.deepEqual(errors, []);
build({ MP_API: '' });
assert.match(fs.readFileSync(path.join(OUT, 'index.html'), 'utf8'), /const MP_API='';/, 'a plain build stays off');
// "//host/path" is another host to a browser, and the player's token would go there.
for (const bad of ['https://evil.example/api', "/api'+alert(1)+'", 'api/mp', '/api/mp/', '/a b', '//evil-host/mp', '//api/mp']) assert.throws(() => build({ MP_API: bad }), bad);
fs.rmSync(OUT, { recursive: true, force: true });
});
test('multiplayer: starting a session takes the server\'s code, seed, rules and AS number; the token stays out of the save', async () => {
const { dom, ev, errors, f } = await started();
const create = f.calls[0];
assert.equal(create.url, '/api/mp/sessions');
assert.equal(create.body.net.name, 'Packet Pals');
assert.equal(create.body.net.home, 'fra');
assert.equal(create.body.preset, 'bgp');
assert.deepEqual(create.body.avoid, JSON.parse(ev('JSON.stringify(NETS.filter(n=>n.asn>=200000&&n.asn<=214999).map(n=>n.asn))')), 'the catalog\'s own AS numbers are off limits');
assert.equal(create.headers.authorization, undefined, 'starting needs no token');
assert.deepEqual(JSON.parse(ev('JSON.stringify(S.mp)')), { code: CODE, pid: PID, asn: 201234, seed: 424242, preset: 'bgp', color: '#3a86ff', title: 'Friday', seq: 1 });
assert.equal(ev('S.asn'), 201234);
assert.equal(ev('S.mode'), 'normal');
assert.equal(ev('S.rules.preset'), 'bgp');
assert.equal(ev('typeof S.rng'), 'number', 'a seeded world');
assert.equal(ev(`localStorage.getItem('sot-mp:${CODE}:${PID}')`), TOK);
assert.ok(!ev('JSON.stringify(S)').includes(TOK), 'the token is not in the game');
assert.ok(!ev('localStorage.getItem(SLOT_K+UI.slot)').includes(TOK), 'nor in its save');
// The first save went at once, with the card, so the player is on the leaderboard (and a link works) from day 0.
const s = f.saves();
assert.equal(s.length, 1);
assert.equal(s[0].body.seq, 1);
assert.equal(s[0].headers.authorization, `Bearer ${PID}.${TOK}`);
assert.equal(JSON.parse(s[0].body.data).mp.code, CODE);
assert.equal(s[0].body.card.day, 0);
assert.ok(ev("$('toasts').textContent").includes('K7Q-2XD'), 'the code to share');
assert.equal(ev("$('hMpRank').textContent"), '🌐 #1/1');
assert.equal(ev('slotIdx().find(e=>e.id===UI.slot).mp'), `${CODE}.${PID}`, 'the slot list knows the session');
assert.match(ev('slotListHtml()'), /🌐 K7Q-2XD/);
ev('ACT.toTitle({})');
assert.equal(ev("$('hMp').hidden"), true, 'back on the title screen, the chip goes');
assert.deepEqual(errors, []);
dom.window.close();
});
test('multiplayer: one session, one world: the same seed makes the same days whatever the browser\'s own luck', async () => {
const run = async (seed) => {
const h = await started({ load: { seed } });
const out = h.ev("ACT.launchBB({city:'fra'});S.nextFail=5;S.nextEvent=5;for(let i=0;i<40;i++)dayTick();JSON.stringify({o:S.offers.map(o=>o.name+o.bw),inc:S.inc.map(i=>i.type),log:S.log.map(l=>l.t).slice(0,20)})");
assert.deepEqual(h.errors, []);
h.dom.window.close();
return out;
};
assert.equal(await run(11), await run(99991));
});
test('multiplayer: joining by a typed code; the session\'s rules win; errors are told plainly', async () => {
const f = fake([[/^POST \/api\/mp\/sessions\/K7Q2XD\/join$/, { status: 200, json: { ...JOINED, preset: 'soft', title: '' } }], okSave]);
const { dom, ev, errors } = load({ mp: MPA, fetch: f });
ev("UI.pitched=true;ACT.mpDoor({});ACT.presetSet({p:'bgp'});document.getElementById('mpCode').value='zz';ACT.mpJoin({})");
assert.equal(f.calls.length, 0, 'a code that is not one never leaves the page');
assert.match(ev("$('toasts').textContent"), /six letters/);
ev("document.getElementById('mpCode').value=' k7q-2xd ';ACT.mpJoin({})");
assert.ok(await until(() => ev('!!(S&&S.mp)')));
assert.equal(f.calls[0].url, '/api/mp/sessions/K7Q2XD/join');
assert.equal(f.calls[0].body.preset, undefined, 'a joiner does not pick the rules');
assert.equal(ev('S.rules.preset'), 'soft', 'the creator did');
assert.match(ev("$('toasts').textContent"), /You joined session K7Q-2XD/);
// "Full" names no number: the server may take fewer than twelve (--max-players).
for (const [status, re] of [[404, /no session with that code/], [409, /^That session is full: every seat in it is taken\.$/], [429, /Too many tries/], [503, /not taking new sessions/], [0, /cannot be reached/]]) {
f.routes = [[/join$/, status ? { status, json: { error: 'x' } } : new Error('offline')]];
ev("UI.mpBusy=false;openModal(mpStartHtml());document.getElementById('mpCode').value='K7Q2XD';$('toasts').innerHTML='';ACT.mpJoin({})");
assert.ok(await until(() => re.test(ev("$('toasts').textContent"))), `${status}: ${ev("$('toasts').textContent")}`);
assert.equal(ev('UI.mpBusy'), false, 'the buttons work again');
}
assert.deepEqual(errors, []);
dom.window.close();
});
test('multiplayer: the card carries what the leaderboard needs and nothing more', async () => {
const { dom, ev, errors } = await started();
ev("S.cash=1e8;S.lvl=3;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buildPop({city:'ams'});UI.pending={a:'fra',b:'ams'};ACT.buildLink({tier:1});ACT.buyIx({city:'fra',tier:0,signed:true});for(let i=0;i<120;i++)dayTick();compute()");
const c = JSON.parse(ev('JSON.stringify(mpCard())'));
assert.deepEqual(Object.keys(c).sort(), ['asn', 'cashB', 'cust', 'day', 'ix', 'links', 'lvl', 'name', 'peak', 'pops', 'ppol', 'reach', 'rev', 'score', 'served', 't1', 'tier', 'transit']);
assert.equal(c.day, ev('S.day'));
assert.deepEqual(c.pops.sort(), ['ams', 'fra']);
assert.deepEqual(c.transit, ['cog']);
assert.deepEqual(c.ix, ['fra']);
assert.equal(c.links.length, 1);
assert.deepEqual(c.links[0].slice(0, 2).sort(), ['ams', 'fra']);
assert.ok(c.links[0][2] > 0);
assert.ok(['t1', 't2', 't3'].includes(c.tier));
assert.equal(c.cashB, Math.floor(Math.log10(ev('S.cash'))), 'cash as an order of magnitude, not the figure');
assert.equal(c.cust, ev('S.biz.length'));
// What comes back is checked against the page's own catalogs.
const back = JSON.parse(ev(`JSON.stringify(mpCardOk(${lit({ ...c, pops: [...c.pops, 'zzz', '<b>'], transit: ['cog', 'nope'], ix: ['fra', 'atlantis'], links: [...c.links, ['fra', 'zzz', 5]], tier: 't9', reach: 9, extra: 1 })}))`));
assert.deepEqual(back.pops.sort(), ['ams', 'fra']);
assert.deepEqual(back.transit, ['cog']);
assert.deepEqual(back.ix, ['fra']);
assert.equal(back.links.length, 1);
assert.equal(back.tier, 't3');
assert.equal(back.reach, 1);
assert.equal(back.extra, undefined);
assert.deepEqual(errors, []);
dom.window.close();
});
test('multiplayer: saves go to the server on a new day, at most every 15 s, never mid-day or in a puzzle; big ones gzipped; on hide a keepalive', async () => {
const { dom, ev, errors, f } = await started({ load: { gzip: true } });
const n = () => f.saves().length;
assert.equal(n(), 1, 'day 0 went at start');
ev('save(true)');
assert.equal(n(), 1, 'same day: nothing new');
ev('dayTick();save(true)');
assert.equal(n(), 1, 'a new day, but not 15 s yet');
ev('MP.last-=16000;save(true)');
assert.equal(n(), 2, 'a new day and 15 s: it goes');
assert.equal(f.saves()[1].body.seq, 2);
await until(() => ev('!MP.busy'));
assert.equal(ev('S.mp.seq'), 2, 'the server\'s number is kept');
ev('dayTick();MP.last-=16000;RW.job={};save(true);RW.job=null');
assert.equal(n(), 2, 'never half a day');
// Starting a puzzle saves the network it sets aside first (that day goes); in the puzzle nothing does.
ev("ACT.pzStart({id:'hello'})");
assert.equal(ev('pzOn()'), true);
await until(() => ev('!MP.busy'));
const k = n();
ev('MP.last-=16000;save(true);UI.pzKeep.day++;MP.last-=16000;save(true)');
assert.equal(n(), k, 'never a puzzle, nor the network set aside for it from here');
ev('pzLeave();closeModal();dayTick();MP.last-=16000;save(true)');
assert.equal(n(), k + 1, 'back from the puzzle, the new day goes');
await until(() => ev('!MP.busy'));
ev(`S.mp.seq++;mpPush('{"x":"'+'a'.repeat(50000)+'"}')`);
assert.ok(await until(() => n() === k + 2), 'a big save');
assert.match(f.saves().at(-1).body.data, /^gz:/, 'goes compressed');
assert.ok(f.saves().at(-1).body.data.length < 5000);
await until(() => ev('!MP.busy'));
// The page is going away: one keepalive request, the save when it fits, else the card alone.
ev("dayTick();window.dispatchEvent(new Event('pagehide'))");
assert.equal(f.calls.at(-1).keepalive, true, 'closing the tab: the page\'s own save on the way out goes as a keepalive');
assert.match(f.calls.at(-1).url, /\/save$/);
await until(() => ev('!MP.busy'));
ev("window.dispatchEvent(new Event('pageshow'))");
assert.equal(ev('MP.leaving'), false);
ev("Object.defineProperty(document,'visibilityState',{configurable:true,get:()=>'hidden'});dayTick();save(true)");
const last = f.calls.at(-1);
assert.equal(last.keepalive, true);
assert.match(last.url, /\/save$/);
await until(() => ev('!MP.busy'));
ev(`dayTick();S.mp.seq++;mpPush('{"x":"'+'a'.repeat(70000)+'"}')`);
assert.equal(f.calls.at(-1).keepalive, true);
assert.match(f.calls.at(-1).url, /\/card$/, 'too big for a keepalive: the card');
assert.deepEqual(errors, []);
dom.window.close();
});
test('multiplayer: when another device moved on, the player hears it once and chooses', async () => {
const f = fake([okStart, okSave]);
const { dom, ev, errors } = await started({ fetch: f });
f.routes = [[/save$/, (c) => c.body && c.body.force ? { status: 200, json: { ok: true, seq: 9, roster: roster([me()]) } } : { status: 409, json: { error: 'newer', seq: 8 } }], [/^GET /, { status: 200, json: roster([me()]) }]];
ev("$('toasts').innerHTML='';dayTick();MP.last-=16000;save(true)");
assert.ok(await until(() => ev('MP.stale')));
assert.match(ev("$('toasts').textContent"), /moved on elsewhere/);
assert.ok(ev("!!document.querySelector('#toasts [data-act=mpNewer]')&&!!document.querySelector('#toasts [data-act=mpKeep]')"));
const k = f.saves().length;
ev('dayTick();MP.last-=16000;save(true)');
assert.equal(f.saves().length, k, 'and nothing is pushed over it meanwhile');
// The toast goes after a few seconds; the choice waits in the session panel.
ev("$('toasts').innerHTML='';ACT.mpOpen({})");
assert.match(ev("$('mpBoard').textContent"), /moved on elsewhere/);
assert.ok(ev("!!document.querySelector('#mpBoard [data-act=mpNewer]')&&!!document.querySelector('#mpBoard [data-act=mpKeep]')"));
ev('closeModal()');
ev('ACT.mpKeep({})');
assert.equal(f.saves().at(-1).body.force, true);
assert.ok(await until(() => ev('S.mp.seq===9&&!MP.stale')), 'keeping this one overwrites, and takes the server\'s number');
// The other choice: load what the other device saved.
const srv = JSON.parse(ev('JSON.stringify(packSave(S))'));
srv.day = 77; srv.cash = 4242;
f.routes = [[/^GET .*\/save$/, { status: 200, json: { seq: 12, at: 1, data: JSON.stringify(srv) } }], [/^GET /, { status: 200, json: roster([me()]) }]];
ev('ACT.mpNewer({})');
assert.ok(await until(() => ev('S.day===77')));
assert.equal(ev('S.cash'), 4242);
assert.equal(ev('S.mp.seq'), 12);
// A save that is some other network is never loaded over this one.
srv.mp.pid = 'zzzzzzzz'; srv.day = 99;
f.routes = [[/^GET .*\/save$/, { status: 200, json: { seq: 13, at: 1, data: JSON.stringify(srv) } }]];
ev("$('toasts').innerHTML='';ACT.mpNewer({})");
assert.ok(await until(() => /could not be read/.test(ev("$('toasts').textContent"))));
assert.equal(ev('S.day'), 77);
assert.deepEqual(errors.filter((e) => !/loading the session save failed/.test(e)), []);
dom.window.close();
});
test('multiplayer: a session network on a device without its token plays on alone, and can leave', async () => {
const a = await started();
const save = a.ev('JSON.stringify(packSave(S))');
a.dom.window.close();
// The same network imported from a file on another device: the session is in the save, the token is not.
const f = fake([[/./, { status: 500, json: {} }]]);
const { dom, ev, errors } = load({ mp: MPA, fetch: f });
ev(`UI.pitched=true;UI.importing=JSON.parse(${lit(save)});ACT.importGo({});${quiet}`);
assert.equal(ev('S.mp.code'), CODE);
// Importing it checks in with the session at once.
assert.ok(await until(() => ev('MP.gone')));
assert.deepEqual(f.calls, [], 'without a token nothing is even asked');
assert.match(ev("$('toasts').textContent"), /no longer in its session/);
ev('dayTick();MP.last-=16000;save(true)');
assert.deepEqual(f.calls, [], 'nor pushed');
ev('ACT.mpOpen({})');
assert.match(ev("$('mpBoard').textContent"), /no longer in its session/);
ev('ACT.mpLeave({})');
assert.ok(await until(() => ev('S.mp===null')), 'leaving works without the server');
assert.deepEqual(errors, []);
dom.window.close();
});
test('multiplayer: opening a session network loads the newer save another device pushed', async () => {
const a = await started();
a.ev("ACT.launchBB({city:'fra'});for(let i=0;i<3;i++)dayTick();save(true)");
const storage = {};
for (const k of JSON.parse(a.ev('JSON.stringify(Object.keys(localStorage))'))) if (!k.startsWith('sot-open:')) storage[k] = a.ev(`localStorage.getItem(${lit(k)})`);
// The server's copy: the same network, played on to day 30 elsewhere.
const srv = JSON.parse(a.ev('JSON.stringify(packSave(S))'));
srv.day = 30; srv.cash = 7654321; srv.mp.seq = 6;
a.dom.window.close();
const f = fake([[/^GET \/api\/mp\/sessions\/K7Q2XD\/save$/, { status: 200, json: { seq: 7, at: 1, data: JSON.stringify(srv) } }], [/^GET \/api\/mp\/sessions\/K7Q2XD$/, { status: 200, json: roster([me()]) }], okSave]);
const { dom, ev, errors } = load({ mp: MPA, fetch: f, storage });
assert.equal(ev('S.day'), 3, 'this device had day 3');
assert.equal(f.calls[0].url, '/api/mp/sessions/K7Q2XD/save', 'and asked the server first');
assert.ok(await until(() => ev('S.day===30')));
assert.equal(ev('S.cash'), 7654321);
assert.equal(ev('S.mp.seq'), 7);
assert.match(ev("$('toasts').textContent"), /Loaded the newer save/);
assert.ok(f.calls.every((c) => c.method === 'GET'), 'nothing was pushed over it');
assert.ok(JSON.parse(ev('localStorage.getItem(SLOT_K+UI.slot)')).day === 30, 'and it is this device\'s save now');
assert.deepEqual(errors, []);
dom.window.close();
});
test('multiplayer: a #mp= link moves the network to this device; a bad one says so', async () => {
const a = await started();
a.ev("ACT.launchBB({city:'fra'});for(let i=0;i<4;i++)dayTick()");
const data = a.ev('JSON.stringify(packSave(S))'), link = a.ev('mpLink(S.mp)');
a.dom.window.close();
assert.equal(link, `https://tests.invalid/#mp=${CODE}.${PID}.${TOK}`);
const f = fake([[/^GET \/api\/mp\/sessions\/K7Q2XD\/save$/, { status: 200, json: { seq: 4, at: 1, data } }], [/^GET \/api\/mp\/sessions\/K7Q2XD$/, { status: 200, json: roster([me()]) }], okSave]);
const { dom, ev, errors } = load({ mp: MPA, fetch: f, url: link });
assert.ok(await until(() => ev('!!(S&&UI.started)')), 'the network opened');
assert.equal(ev('location.hash'), '', 'the secret is gone from the address bar');
assert.equal(ev('S.name'), 'Packet Pals');
assert.equal(ev('S.day'), 4);
assert.equal(ev('S.mp.seq'), 4);
assert.equal(ev(`localStorage.getItem('sot-mp:${CODE}:${PID}')`), TOK);
assert.equal(ev('slotIdx().length'), 1);
assert.equal(ev('slotIdx()[0].mp'), `${CODE}.${PID}`);
assert.equal(f.calls[0].headers.authorization, `Bearer ${PID}.${TOK}`);
assert.match(ev("$('toasts').textContent"), /moved to this device/);
dom.window.close();
const g = fake([[/save$/, { status: 401, json: { error: 'unauthorized' } }]]);
const b = load({ mp: MPA, fetch: g, url: `https://tests.invalid/#mp=${CODE}.${PID}.${'0'.repeat(64)}` });
assert.ok(await until(() => /did not work/.test(b.ev("$('toasts').textContent"))));
assert.equal(b.ev('S'), null, 'the title screen, nothing loaded');
assert.equal(b.ev('slotIdx().length'), 0);
assert.equal(b.ev('location.hash'), '');
assert.deepEqual(errors, []);
assert.deepEqual(b.errors, []);
b.dom.window.close();
});
test('multiplayer: other players\' names, chat and colours are text, never markup', async () => {
const f = fake([okStart, okSave]);
const { dom, ev, errors } = await started({ fetch: f });
const doc = dom.window.document;
const evil = {
pid: 'eeeeeeee', name: '<img src=x onerror=__xss=1>', asn: 210000, color: 'red;background:url(//evil)', seen: 1, joined: 2,
card: { day: 9, tier: 't1', t1: true, pops: ['fra', 'nyc', '<b>x</b>', 'zzz'], links: [['fra', 'nyc', 5]], ix: [], transit: [], ppol: 'open', reach: 1, peak: 12, served: 1e99, cust: 4, rev: 1, cashB: 3, score: 1 },
};
const feed = [{ k: 'chat', pid: 'eeeeeeee', name: '<script>window.__xss=2</script>', text: '<img src=y onerror="window.__xss=3">', at: 1 }, { k: 'join', pid: 'eeeeeeee', name: '<i>x</i>', at: 1 }, { k: 'evil', name: 'x', at: 1 }];
f.routes = [[/^GET \/api\/mp\/sessions\/K7Q2XD$/, { status: 200, json: roster([me(), evil, { pid: '../../x', name: 'bad' }], feed) }]];
ev('ACT.mpOpen({})');
assert.ok(await until(() => ev("document.querySelectorAll('#mpBoard .mprow').length===2")));
for (const id of ['mpBoard', 'mpFeed']) {
const el = doc.getElementById(id);
assert.equal(el.querySelector('img,script,i:not(.mpdot)'), null, `${id}: no markup from the server`);
}
assert.ok(doc.getElementById('mpBoard').textContent.includes('<img src=x onerror=__xss=1>'), 'the name shows as text');
assert.ok(doc.getElementById('mpFeed').textContent.includes('<img src=y'), 'and the chat line');
assert.equal(doc.querySelectorAll('#mpBoard .mprow').length, 2, 'a player without a proper id is dropped');
assert.equal(doc.querySelectorAll('#mpFeed .mpf').length, 2, 'and an unknown kind of feed line');
assert.ok([...doc.querySelectorAll('.mpdot')].every((d) => /^background: ?#[0-9a-f]{6};?$/i.test(d.getAttribute('style'))), 'colours are colours');
assert.match(doc.querySelector('#mpBoard .mprow').textContent, /Tier 1/, 'Tier 1 leads the board');
assert.match(doc.querySelector('#mpBoard .mprow').textContent, /2 POPs/, 'with only real cities');
assert.equal(ev('window.__xss'), undefined);
assert.deepEqual(errors, []);
dom.window.close();
});
test('multiplayer: the session panel and the chip on a phone; chat, leaving', async () => {
const f = fake([okStart, okSave]);
const { dom, ev, errors } = await started({ fetch: f, load: { gzip: false } });
const doc = dom.window.document;
ev('window.innerWidth=360;window.innerHeight=740;renderAll()');
assert.equal(ev('isPhone()'), true);
const chip = doc.getElementById('hMp');
assert.ok(chip && !chip.hidden, 'the chip is there');
assert.match(chip.textContent, /K7Q-2XD/);
// A phone's top bar has no room for it (cash and the date would be cut): hide-sm. Where you stand is a badge on the
// menu button instead, there and on a tablet whose top bar still wraps at fitHud's last step (no layout in jsdom).
assert.ok(chip.classList.contains('hide-sm'), 'not in a phone\'s top bar');
const badge = doc.querySelector('#hud .menubtn #hMpB');
assert.ok(badge && !badge.hidden, 'a badge on the menu button');
const css = [...doc.querySelectorAll('style')].map((x) => x.textContent).join('');
assert.match(css, /#hud\.fit3 \.mpchip\{display:none !important\}/, 'a tablet drops the chip before the top bar wraps');
assert.match(css, /\.mpbadge\{display:block\}/);
ev('ACT.menu({})');
assert.ok(doc.querySelector('#modalCard .mtile[data-act=mpOpen]'), 'the menu has the session');
f.routes = [[/^GET \/api\/mp\/sessions\/K7Q2XD$/, { status: 200, json: roster([me({ day: 1, tier: 't2', t1: false, pops: ['fra'], links: [], ix: [], transit: [], ppol: 'open', reach: 0.5, peak: 3, served: 2, cust: 1, rev: 1, cashB: 5, score: 1 }), { ...me(null), pid: 'bbbbbbbb', name: 'Bee', color: '#ff4f9a' }], [{ k: 'join', pid: PID, name: 'Packet Pals', at: Date.now() }]) }],
[/feed$/, (c) => c.body.text === 'fast' ? { status: 429, json: { error: 'slow' } } : { status: 200, json: roster([me()], [{ k: 'chat', pid: PID, name: 'Packet Pals', text: c.body.text, at: Date.now() }]) }],
[/^DELETE .*\/me$/, { status: 200, json: { ok: true } }]];
doc.querySelector('#modalCard .mtile[data-act=mpOpen]').click();
assert.ok(await until(() => doc.querySelectorAll('#mpBoard .mprow').length === 2));
const card = doc.getElementById('modalCard');
assert.ok(card.querySelector('.btns.cta'), 'the main buttons stay in reach (sticky on a phone)');
assert.equal(card.querySelector('.mpcode b').textContent, 'K7Q-2XD');
assert.ok(card.querySelector('details.mpmove #mpLink'), 'the link to another device, folded away');
assert.match(card.querySelector('#mpLink').value, /#mp=K7Q2XD\.abcd1234\.[0-9a-f]{64}$/);
assert.match(doc.querySelector('#mpBoard .mprow.me').textContent, /you/);
assert.match(doc.getElementById('mpBoard').textContent, /has not finished a day yet/);
assert.equal(ev("$('hMpRank').textContent"), '🌐 #1/2');
assert.equal(badge.textContent, '#1');
// Chat.
ev("document.getElementById('mpSay').value='hello there';ACT.mpChat({})");
assert.ok(await until(() => /hello there/.test(doc.getElementById('mpFeed').textContent)));
assert.equal(doc.getElementById('mpSay').value, '', 'the line went');
ev("$('toasts').innerHTML='';document.getElementById('mpSay').value='fast';ACT.mpChat({})");
assert.ok(await until(() => /Slow down/.test(ev("$('toasts').textContent"))));
// Landscape on a phone: still a phone layout.
ev('window.innerWidth=740;window.innerHeight=360;renderAll()');
assert.ok(doc.getElementById('mpPanel'));
// Leaving: the network stays, the session and the token go.
ev('ACT.mpLeaveAsk({})');
assert.match(doc.getElementById('modalCard').textContent, /Leave session K7Q-2XD\?/);
ev('ACT.mpLeave({})');
assert.ok(await until(() => ev('S.mp===null')));
assert.equal(ev(`localStorage.getItem('sot-mp:${CODE}:${PID}')`), null);
assert.equal(doc.getElementById('hMp').hidden, true);
assert.equal(badge.hidden, true);
assert.equal(JSON.parse(ev('localStorage.getItem(SLOT_K+UI.slot)')).mp, null, 'saved without it');
assert.equal(ev('slotIdx().find(e=>e.id===UI.slot).mp'), undefined, 'and the list of networks forgets the session too');
assert.doesNotMatch(ev('slotListHtml()'), /K7Q-2XD/);
ev('dayTick();save(true)');
assert.equal(ev('slotIdx().find(e=>e.id===UI.slot).mp'), undefined, 'for good');
assert.deepEqual(errors, []);
dom.window.close();
});
test('multiplayer: the server away: the game plays on, backs off, says so once', async () => {
const f = fake([okStart, okSave]);
const { dom, ev, errors } = await started({ fetch: f });
f.routes = [[/./, new Error('offline')]];
ev("$('toasts').innerHTML='';dayTick();MP.last-=16000;save(true)");
assert.ok(await until(() => ev('MP.fails===1')));
assert.ok(ev('MP.wait>performance.now()'), 'it waits before the next try');
assert.match(ev("$('toasts').textContent"), /server is away/);
ev('dayTick();MP.last-=16000;save(true)');
assert.equal(f.saves().length, 2, 'not while it waits');
ev("$('toasts').innerHTML='';MP.wait=0;dayTick();MP.last-=16000;save(true)");
assert.ok(await until(() => ev('MP.fails===2')));
assert.equal(ev("$('toasts').textContent"), '', 'told once');
// Too many at once (429, or the server's own 503 "busy") is not "away": a short wait, quietly, and the back-off stays
// where it was. Behind a proxy without --trust-proxy every player is one address, so this happens to honest players.
for (const r of [{ status: 429, json: { error: 'slow down' } }, { status: 503, json: { error: 'busy', busy: true } }]) {
f.routes = [[/save$/, r]];
ev("MP.told=false;MP.wait=0;dayTick();MP.last-=16000;save(true)");
assert.ok(await until(() => ev('!MP.busy&&MP.wait>performance.now()')));
assert.equal(ev('MP.fails'), 2, String(r.status));
assert.ok(ev('MP.wait-performance.now()') <= 30000);
assert.equal(ev("$('toasts').textContent"), '', 'nothing to tell');
}
// A proxy's own 503 (the server behind it is down) is "away".
f.routes = [[/save$/, { status: 503, json: null }]];
ev("MP.wait=0;dayTick();MP.last-=16000;save(true)");
assert.ok(await until(() => ev('MP.fails===3')));
assert.match(ev("$('toasts').textContent"), /server is away/);
f.routes = [okSave];
ev('MP.wait=0;dayTick();MP.last-=16000;save(true)');
assert.ok(await until(() => ev('MP.fails===0&&!MP.told')), 'back: all forgotten');
assert.ok(ev('S.day') >= 4, 'and the game went on all along');
assert.deepEqual(errors, []);
dom.window.close();
});
test('multiplayer: S.mp from a save is checked; saves without it load as before', () => {
const { ev, errors } = load({ mp: MPA, fetch: fake() });
ev(`ACT.start({});if(UI.pendGame)ACT.pitchSkip();${quiet}`);
assert.equal(ev('S.mp'), null, 'a game outside a session');
const fix = (m, mode = 'normal') => JSON.parse(ev(`(()=>{const s=JSON.parse(JSON.stringify(S));s.mode=${lit(mode)};s.mp=${lit(m)};return JSON.stringify(sanitize(s).mp);})()`));
assert.deepEqual(fix({ code: CODE, pid: PID, asn: 999, seed: 1e12, preset: 'sandbox', color: 'javascript:x', title: 'x'.repeat(99), seq: -4, token: TOK, extra: 1 }),
{ code: CODE, pid: PID, asn: 200000, seed: 2147483647, preset: 'oncall', color: '#ff4f9a', title: 'x'.repeat(40), seq: 0 });
for (const bad of [null, 7, 'K7Q2XD', [], { code: '../../x', pid: PID }, { code: CODE, pid: 'ABC' }, { code: 'k7q2xd', pid: PID }]) assert.equal(fix(bad), null, JSON.stringify(bad));
assert.equal(fix({ code: CODE, pid: PID }, 'sandbox'), null, 'only a Normal game can be in a session');
// An old save: no mp at all.
ev('const s=JSON.parse(JSON.stringify(S));delete s.mp;S=migrate(s);compute();dayTick();save(true)');
assert.equal(ev('S.mp'), null);
assert.equal(ev("'mp' in S"), true);
ev('S=sanitize(JSON.parse(JSON.stringify(S)))');
assert.equal(ev('S.mp'), null, 'and it round-trips');
assert.equal(ev("slotClean({id:'abc',mp:'K7Q2XD.abcd1234'}).mp"), 'K7Q2XD.abcd1234');
assert.equal(ev("slotClean({id:'abc',mp:'<b>.x'}).mp"), undefined, 'the slot list checks it too');
assert.deepEqual(errors, []);
});
test('multiplayer: two players against the real server: start, join, see each other', async (t) => {
const { createMp } = require('../scripts/lib/mp');
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-mp-e2e-'));
const mp = createMp({ dir, log: () => {} });
const server = http.createServer((req, res) => { if (!mp.handle(req, res)) { res.writeHead(404); res.end(); } });
await new Promise((r) => server.listen(0, '127.0.0.1', r));
t.after(() => { server.close(); fs.rmSync(dir, { recursive: true, force: true }); });
const base = `http://127.0.0.1:${server.address().port}`;
// The page's fetch, on the real network (the page's own AbortSignal stays behind: it belongs to another realm).
const net = (u, o = {}) => { const { signal, ...rest } = o; return fetch(base + u, rest); };
const a = await started({ fetch: net, name: 'Alpha Net' });
const code = a.ev('S.mp.code');
const b = load({ mp: MPA, fetch: net, seed: 777 });
b.ev(`UI.pitched=true;ACT.mpDoor({});document.getElementById('mpName').value='Beta <b>Net</b>';ACT.pickStart({city:'nyc'});document.getElementById('mpCode').value=${lit(code.toLowerCase())};ACT.mpJoin({})`);
assert.ok(await until(() => b.ev('!!(S&&S.mp)')), 'B joined');
b.ev(quiet);
assert.equal(b.ev('S.mp.seed'), a.ev('S.mp.seed'), 'one world');
assert.equal(b.ev('S.rules.preset'), 'bgp', 'one set of rules');
assert.notEqual(b.ev('S.asn'), a.ev('S.asn'));
assert.equal(b.ev('S.home'), 'nyc');
await until(() => b.ev('!MP.busy'));
a.ev('mpRefresh()');
assert.ok(await until(() => a.ev('MP.roster&&MP.roster.players.length===2')), 'A sees B');
assert.deepEqual(JSON.parse(a.ev('JSON.stringify(MP.roster.players.map(p=>p.name))')), ['Alpha Net', 'Beta bNet/b']);
assert.equal(a.ev("MP.roster.players[1].card&&MP.roster.players[1].card.pops.join()"), 'nyc', 'and B\'s card');
assert.deepEqual(JSON.parse(a.ev('JSON.stringify(MP.roster.feed.map(f=>f.k))')), ['join', 'join']);
// A plays on a few days and pushes; B's panel shows it.
a.ev("ACT.launchBB({city:'fra'});dayTick();MP.last-=16000;save(true)");
await until(() => a.ev('!MP.busy'));
assert.equal(a.ev('S.mp.seq'), 2);
b.ev('ACT.mpOpen({})');
assert.ok(await until(() => /Alpha Net/.test(b.ev("document.getElementById('mpBoard').textContent"))));
b.ev("document.getElementById('mpSay').value='hi from B';ACT.mpChat({})");
assert.ok(await until(() => /hi from B/.test(b.ev("document.getElementById('mpFeed').textContent"))));
// B moves to another device by its link.
const link = b.ev('mpLink(S.mp)');
await until(() => b.ev('!MP.busy'));
const c = load({ mp: MPA, fetch: net, url: link });
assert.ok(await until(() => c.ev('!!(S&&S.mp&&UI.started)')), 'B on the other device');
assert.equal(c.ev('S.name'), 'Beta <b>Net</b>');
assert.equal(c.ev('S.home'), 'nyc');
for (const h of [a, b, c]) { assert.deepEqual(h.errors, []); h.dom.window.close(); }
await mp.flush();
});
test('multiplayer: the save here and the one on the server carry the same number: reopening finds nothing newer', async () => {
const srv = store(), f = fake(srv.routes);
const a = await started({ fetch: f });
const slot = (h) => JSON.parse(h.ev('localStorage.getItem(SLOT_K+UI.slot)'));
a.ev("ACT.launchBB({city:'fra'});dayTick();MP.last-=16000;save(true)");
await until(() => a.ev('!MP.busy'));
assert.equal(srv.st.save.seq, 2);
assert.equal(JSON.parse(srv.st.save.data).mp.seq, 2, 'the server\'s copy says 2');
assert.equal(slot(a).mp.seq, 2, 'and so does the one here: the number was picked before the save was written');
// Closing the tab after a new day: the last save goes as a keepalive request, numbered the same here and there.
a.ev("dayTick();window.dispatchEvent(new Event('pagehide'))");
assert.equal(f.calls.at(-1).keepalive, true);
await until(() => a.ev('!MP.busy'));
assert.equal(srv.st.save.seq, 3);
assert.equal(slot(a).mp.seq, 3);
assert.equal(slot(a).day, srv.day());
const storage = storageOf(a);
a.dom.window.close();
// Reopened on the same device: nothing newer on the server, nothing loaded, nothing said.
const g = fake(srv.routes);
const b = load({ mp: MPA, fetch: g, storage });
assert.ok(await until(() => g.calls.some((c) => /K7Q2XD$/.test(c.url))), 'asked, then took the roster');
await flush();
assert.doesNotMatch(b.ev("$('toasts').textContent"), /Loaded the newer save/);
// A push still on its way when the page goes away: the newer save goes anyway, and cuts the slower one short.
b.ev(quiet);
srv.st.hold = true;
b.ev('dayTick();MP.last-=16000;save(true)');
const slow = g.calls.at(-1);
assert.equal(slow.keepalive, false);
assert.equal(b.ev('MP.busy'), true);
const k = g.calls.length;
b.ev('for(let i=0;i<3;i++)dayTick();MP.last-=16000;save(true)');
assert.equal(g.calls.length, k, 'one push at a time while the page is on screen');
b.ev("window.dispatchEvent(new Event('pagehide'))");
const last = g.calls.at(-1);
assert.equal(last.keepalive, true);
assert.equal(last.body.seq, slow.body.seq + 1);
assert.equal(JSON.parse(last.body.data).day, b.ev('S.day'), 'the days played meanwhile go too');
assert.equal(slow.signal.aborted, true, 'the slower one was cut short');
await until(() => b.ev('!MP.busy'));
assert.equal(srv.day(), b.ev('S.day'));
assert.equal(slot(b).mp.seq, srv.st.save.seq);
// Reopened once more: the server's copy is this one, so the days stay.
const day = b.ev('S.day'), again = storageOf(b);
b.dom.window.close();
const c = load({ mp: MPA, fetch: fake(srv.routes), storage: again });
await flush(10);
assert.equal(c.ev('S.day'), day);
assert.doesNotMatch(c.ev("$('toasts').textContent"), /Loaded the newer save|moved on elsewhere/);
for (const h of [b, c]) assert.deepEqual(h.errors, []);
assert.deepEqual(a.errors, []);
c.dom.window.close();
});
test('multiplayer: the server briefly away when the network opens is no conflict later', async () => {
const srv = store(), a = await started({ fetch: fake(srv.routes) });
a.ev("ACT.launchBB({city:'fra'});dayTick();MP.last-=16000;save(true)");
await until(() => a.ev('!MP.busy'));
a.ev("dayTick();window.dispatchEvent(new Event('pagehide'))");
await until(() => a.ev('!MP.busy'));
const storage = storageOf(a);
a.dom.window.close();
const g = fake([[/./, new Error('offline')]]);
const b = load({ mp: MPA, fetch: g, storage });
assert.ok(await until(() => b.ev('MP.fails===1')));
b.ev(quiet + "for(let i=0;i<10;i++)dayTick();MP.wait=0;MP.last-=16000");
g.routes = srv.routes;
b.ev('save(true)');
await until(() => b.ev('!MP.busy'));
assert.equal(b.ev('MP.stale'), false, 'one device, so no "moved on elsewhere"');
assert.equal(srv.day(), b.ev('S.day'));
assert.deepEqual(b.errors, []);
b.dom.window.close();
});
test('multiplayer: hiding the page sends what changed on the same game day, only then, in a request that fits', async () => {
const srv = store(), f = fake(srv.routes);
const { dom, ev, errors } = await started({ fetch: f });
const n = () => f.saves().length, k = n();
// A paused game: the player builds, and the day never moves.
ev("ACT.launchBB({city:'fra'})");
assert.equal(n(), k, 'same day, page on screen: nothing yet');
ev(hide());
assert.equal(n(), k + 1, 'hidden: what changed goes');
assert.equal(f.saves().at(-1).keepalive, true);
assert.ok(JSON.parse(f.saves().at(-1).body.data).pops.fra.bb, 'with the change');
await until(() => ev('!MP.busy'));
ev(hide());
assert.equal(n(), k + 1, 'hidden again, nothing changed: nothing sent');
// Moving to another device: the link goes with what this one has now.
ev(hide(false) + "S.name='Packet Pals Two';ACT.mpOpen({});ACT.mpCopyLink({})");
assert.equal(n(), k + 2);
assert.equal(JSON.parse(f.saves().at(-1).body.data).name, 'Packet Pals Two');
await until(() => ev('!MP.busy'));
ev("S.name='Packet Pals Three';const d=document.querySelector('#mpPanel details.mpmove');d.open=true;d.dispatchEvent(new Event('toggle'))");
assert.equal(n(), k + 3, 'opening "Move to another device" pushes too');
await until(() => ev('!MP.busy'));
// A keepalive request may carry 64 KiB in all: the request is measured, in bytes, quotes escaped, card and all.
ev('closeModal();' + hide());
const send = (t) => { ev(`dayTick();S.mp.seq++;mpPush(${lit(t)})`); const c = f.calls.at(-1); return c.url.replace(/.*\//, ''); };
assert.equal(send('{"x":"' + 'a'.repeat(50000) + '"}'), 'save', '50 kB of plain text fits');
await until(() => ev('!MP.busy'));
assert.equal(send('{"x":[' + Array(10000).fill('"ab"').join(',') + ']}'), 'card', '50 kB of text with quotes does not');
await until(() => ev('!MP.busy'));
assert.equal(send('{"x":"' + 'é'.repeat(40000) + '"}'), 'card', '40 000 characters of two bytes do not');
await until(() => ev('!MP.busy'));
for (const c of f.calls.filter((x) => x.keepalive)) assert.ok(Buffer.byteLength(c.raw) < 63000, `${c.url}: ${Buffer.byteLength(c.raw)} bytes`);
assert.deepEqual(errors, []);
dom.window.close();
});
test('multiplayer: "Load the newer save" never loads an older one; "Keep this one" waits for the day to end', async () => {
const srv = store(), f = fake(srv.routes);
const { dom, ev, errors } = await started({ fetch: f });
const day0 = srv.st.save;
ev("ACT.launchBB({city:'fra'});for(let i=0;i<5;i++)dayTick();MP.last-=16000;save(true)");
await until(() => ev('!MP.busy'));
// The server says it has a newer save (409, number 3) but holds an older one (number 1, day 0).
srv.st.save = day0;
f.routes = [[/^PUT .*\/save$/, { status: 409, json: { error: 'newer', seq: 3, at: 1 } }], ...srv.routes];
ev("$('toasts').innerHTML='';dayTick();MP.last-=16000;save(true)");
assert.ok(await until(() => ev('MP.stale')));
const day = ev('S.day');
ev('ACT.mpNewer({})');
assert.ok(await until(() => /no newer save/.test(ev("$('toasts').textContent"))));
assert.equal(ev('S.day'), day, 'not rolled back to day 0');
assert.equal(ev('MP.stale'), false);
f.routes = srv.routes;
ev('dayTick();MP.last-=16000;save(true)');
await until(() => ev('!MP.busy'));
assert.equal(srv.day(), ev('S.day'), 'and the next push puts this one on the server');
// Another device pushed number 9 meanwhile; the player keeps theirs, clicking while the day is still routing.
srv.st.save = { ...srv.st.save, seq: 9 };
ev('dayTick();MP.last-=16000;save(true)');
assert.ok(await until(() => ev('MP.stale&&MP.staleSeq===9')));
const k = f.saves().length;
ev('RW.job={};ACT.mpKeep({})');
assert.equal(f.saves().length, k, 'never half a day');
ev('RW.job=null;rwDayDone()');
const kept = f.saves().at(-1);
assert.equal(f.saves().length, k + 1, 'the day\'s end pushes it');
assert.equal(kept.body.force, true);
assert.equal(kept.body.seq, 10, 'past the server\'s number, so it keeps the one it was sent');
await until(() => ev('!MP.busy'));
assert.equal(srv.st.save.seq, 10);
assert.equal(JSON.parse(ev('localStorage.getItem(SLOT_K+UI.slot)')).mp.seq, 10);
assert.equal(ev('MP.force'), false);
assert.deepEqual(errors, []);
dom.window.close();
});
test('multiplayer: a #mp= link never replaces nor deletes the token this browser has; a busy network is not copied', async () => {
const srv = store(), b = browser(), tab1 = new Map();
const real = (c) => c.method === 'POST' || c.headers.authorization === `Bearer ${PID}.${TOK}`;
const guarded = srv.routes.map(([re, h]) => [re, (c) => (real(c) ? (typeof h === 'function' ? h(c) : h) : { status: 401, json: { error: 'unauthorized' } })]);
const f1 = fake(guarded);
const t1 = await started({ fetch: f1, load: { browser: b, tab: tab1 } });
t1.ev("ACT.launchBB({city:'fra'});for(let i=0;i<3;i++)dayTick();MP.last-=16000;save(true)");
await until(() => t1.ev('!MP.busy'));
const link = t1.ev('mpLink(S.mp)'), wrong = link.replace(/[0-9a-f]{64}$/, '0'.repeat(64)), tok = () => b.ls.get(`sot-mp:${CODE}:${PID}`);
const slots = () => JSON.parse(b.ls.get('sot-slots')).slots.length;
// A wrong link (a rival's, or one mistyped character) while the game is open in another tab.
const t2 = load({ mp: MPA, fetch: fake(guarded), browser: b, tab: new Map(), url: wrong });
assert.ok(await until(() => /did not work/.test(t2.ev("$('toasts').textContent"))));
assert.equal(tok(), TOK, 'the real token stays');
assert.equal(slots(), 1);
t1.ev('dayTick();MP.last-=16000;save(true)');
assert.equal(f1.calls.at(-1).headers.authorization, `Bearer ${PID}.${TOK}`, 'and the open tab plays on in its session');
await until(() => t1.ev('!MP.busy'));
assert.equal(t1.ev('MP.gone'), false);
// The right link, while the network is open in the other tab: no second copy, the choice to take it over.
const t3 = load({ mp: MPA, fetch: fake(guarded), browser: b, tab: new Map(), url: link });
assert.ok(await until(() => t3.ev("!!document.querySelector('#modal [data-act=slotTake]')")), 'offered to take it over');
assert.equal(slots(), 1, 'not copied into a second slot');
// The server away: the link may be fine, so it is not called bad, stays for a reload, and no token changes.
b.close(t1.dom.window);
const t4 = load({ mp: MPA, fetch: fake([[/./, new Error('offline')]]), browser: b, tab: new Map(), url: wrong });
assert.ok(await until(() => /cannot be reached/.test(t4.ev("$('toasts').textContent"))));
assert.equal(t4.ev('location.hash'), new URL(wrong).hash, 'kept for a reload');
assert.equal(tok(), TOK);
// A wrong link once the game's tab is closed: still told, still the real token.
const t5 = load({ mp: MPA, fetch: fake(guarded), browser: b, tab: new Map(), url: wrong });
assert.ok(await until(() => /did not work/.test(t5.ev("$('toasts').textContent"))));
assert.equal(tok(), TOK);
assert.equal(t5.ev('location.hash'), '', 'a bad link is gone from the address bar');
// A fresh browser, server away: nothing stored at all.
const b2 = browser(), t6 = load({ mp: MPA, fetch: fake([[/./, { status: 503, json: { error: 'busy' } }]]), browser: b2, tab: new Map(), url: link });
assert.ok(await until(() => /cannot be reached/.test(t6.ev("$('toasts').textContent"))));
assert.equal(b2.ls.get(`sot-mp:${CODE}:${PID}`), undefined);
for (const h of [t1, t2, t3, t4, t5, t6]) assert.deepEqual(h.errors.filter((e) => !/moving the network here failed/.test(e)), []);
for (const h of [t1, t2, t3, t4, t5, t6]) h.dom.window.close();
});
test('multiplayer: the session panel\'s refresh while the server is away says so once and never stretches the wait', async () => {
const f = fake([okStart, okSave, [/^GET /, { status: 200, json: roster([me()]) }]]);
const { dom, ev, errors } = await started({ fetch: f });
ev('ACT.mpOpen({})');
await flush();
f.routes = [[/./, new Error('offline')]];
ev("$('toasts').innerHTML=''");
for (let i = 0; i < 6; i++) { ev('mpPollTick()'); await flush(); }
assert.equal(f.calls.filter((c) => c.method === 'GET').length >= 6, true, 'it still looks every few seconds');
assert.equal(ev('MP.fails'), 1);
assert.ok(ev('MP.wait-performance.now()') <= 30000, 'the push back-off stays at its first step');
assert.equal(ev("$('toasts').textContent.split('server is away').length-1"), 1, 'said once');
f.routes = [okSave, [/^GET /, { status: 200, json: roster([me()]) }]];
ev('mpPollTick()');
assert.ok(await until(() => ev('MP.fails===0&&MP.wait===0')), 'back: all forgotten');
const k = f.calls.length;
ev('closeModal();mpPollTick()');
assert.equal(f.calls.length, k, 'a closed panel stops asking');
assert.deepEqual(errors, []);
dom.window.close();
});
test('multiplayer: with a charter to sign first, the session code and its Share button wait for it', async () => {
const f = fake([okStart, okSave]);
const { dom, ev, errors } = load({ mp: MPA, fetch: f });
const doc = dom.window.document;
ev("window.__TUBES_CHARTER__=true;UI.pitched=true;ACT.mpDoor({});document.getElementById('mpName').value='Packet Pals';ACT.presetSet({p:'bgp'});ACT.mpStart({})");
assert.ok(await until(() => ev('!!(S&&S.mp)')));
assert.equal(ev("$('modal').className"), 'charter', 'the charter comes first');
assert.equal(doc.querySelector('#toasts [data-act=mpShare]'), null, 'no buttons under it that cannot be pressed');
ev('ACT.charter({k:Object.keys(CHARTERS)[0]})');
const share = doc.querySelector('#toasts [data-act=mpShare]');
assert.ok(share, 'signed: the code to share');
assert.match(doc.getElementById('toasts').textContent, /K7Q-2XD/);
share.click();
assert.match(doc.getElementById('toasts').textContent, /Join my Series of Tubes session K7Q-2XD/, 'and its button works');
assert.deepEqual(errors, []);
dom.window.close();
});