Hosting it
import { RoomHub } from "tickcli-js";import { WS_OPTIONS, attach, sameSite, Tickets, GuestPasses, gameHash } from "tickcli-js/node";
const hub = new RoomHub({ secret, saves, onSnapshot: (snap) => writeFile("rooms.json", JSON.stringify(snap)) });try { hub.importRooms(JSON.parse(readFileSync("rooms.json", "utf8"))); } catch {} // the rooms of the last process, if under 2 minutes oldhub.start();process.on("SIGTERM", async () => { await hub.shutdown(); process.exit(0); });const wss = new WebSocketServer({ ...WS_OPTIONS });server.on("upgrade", (req, socket, head) => { if (!sameSite((n) => req.headers[n])) return socket.destroy(); wss.handleUpgrade(req, socket, head, (ws) => attach(ws, { hub, address, identity /* or authenticate: (ticket) => ... */ }));});Identity always comes from your app, never from the page:
- Signed-in people: issue a one-time ticket (
new Tickets(secret).issue({...}), 30 s) from an authenticated route; the relay’sconnect()returns{url, first: {v: 1, t: "auth", ticket}}and the ticket travels as the socket’s first message (proxies log addresses, so not in the URL).authenticate(ticket)turns it into{scope, game, who}. - Anonymous visitors: set a pass cookie (
GuestPasses, HttpOnly, SameSite=Strict, limited to one path) and check it at the upgrade (identity). scopeis your namespace (a team, a public link); a room code only picks a room inside it.gameis the page’s hash: players on another version are told to reload.
Restarts: hub.shutdown() writes pending saves, hands the live rooms to onSnapshot (plain JSON: rooms, matches, shared state, seats; no tickets or passes) and closes every socket with 1012. The next process calls importRooms(snapshot, {maxAgeMs}) (default 2 minutes; an older or other-format snapshot is ignored) before start(): each room comes back in the same match with a new host term, its seats held for 60 s and no host until a member is back; save leases are taken again. Players reconnect (spread over 0.3 to 3 s) and their welcome has kept: true. Keep the file private (it holds seat keys and save slots).
src/serve.ts (what createGameServer and npx tickcli-js run) is a complete host in under 300 lines.
Games hosted on another site (tickcli-js/remote)
Section titled “Games hosted on another site (tickcli-js/remote)”The game page lives anywhere (your own site, GitHub Pages, a game portal) and plays in rooms on a tickcli server. The page needs one tag:
<script src="https://rooms.example/c/dep_ab12.js" data-game="dots" data-version="1"></script> <!-- relay + room.js + game.js, set up --><script> Game({ /* as above */ }) </script>data-game names the game (its saves; default: the page’s file name), data-version keeps players of different versions apart (default 1). The server side:
import { createRemoteServer } from "tickcli-js/remote";
const deployments = { // "http://localhost:*" lets the author test the same page from a laptop; drop it whenever you like dep_ab12: { id: "dep_ab12", origins: ["https://mygame.example", "https://*.portal.example", "http://localhost:*"], caps: { rooms: 20, players: 200, kbPerSec: 2048, joinsPerMinute: 600 } },};const app = createRemoteServer({ deployment: (id) => deployments[id], secret: process.env.TICKCLI_SECRET, saves: "./saves" });await app.listen(8080); // behind https: the pages use wss://Or in your own server: createRemote({ hub, deployment }) gives upgrade(req, socket, head) and request(req, res) (pass roomsPerScope: (s) => remote.roomsPerScope(s) and scopeCaps: (s) => remote.scopeCaps(s) to the hub for the room, data and joins caps).
- A deployment is a public id plus the sites allowed to use it:
https://site, one wildcard levelhttps://*.example, any port:*. The server checks the page’sOriginwhen the socket opens: browsers send it and page scripts cannot change it, so another site cannot use your deployment. There is one kind of deployment: https sites, and http only for this machine (localhost,127.0.0.1,[::1]) when listed, e.g.http://localhost:*to test from a laptop. Pages with no site (null,file://) are refused. - Guests: the page keeps a random 128-bit key in its own
localStorageand sends it as the socket’s first message (no cookie, so it works from any site). The same key is the same seat; other players see a short id made from it, never the key. - Guest names: letters, digits, spaces,
_and-, at most 20 characters. Rude words and slurs (look-alike spellings such assh1ttoo) and staff-like names (admin,moderator,mod,tickcli) are refused: a rename gets the errorbad_name(ref"rude"or"reserved") and the lobby says so; a join keeps the default “Guest 1234”. Signed-in names come from your accounts and are not checked. - Each deployment is its own namespace (rooms and saves never mix).
caps: open rooms, connected sockets, KB a second going out (over it, new sockets are told the game is busy and retry, and its open rooms send less often, down to an eighth, until it is back under 80%; other deployments keep their full rate), joins a minute across the deployment (reconnects count: leave room for every player joining again after a restart).revoked: truerefuses new sockets;remote.revoke(id)also closes its open rooms. - A refused page stops and shows why (“This site is not allowed for deployment dep_ab12.”).
- Not a guard: a script outside a browser can send any
Origin. The caps, the per-address limits and revoking the id are what stop a misused deployment.
Floods and DDoS
Section titled “Floods and DDoS”The hub and adapters cap what one client can cost (table below: sockets and new sockets per address, messages, bytes, lookups, slow headers). Keep ws at 8.23.0 or later (a peer that floods pings while not reading exhausted memory in earlier versions, GHSA-37g9-w4hg-h9qr); WS_OPTIONS keeps compression off and messages at 16 KB (ws’s own default is 100 MiB). What the server cannot do alone:
- Volume (a full uplink, SYN floods): the host’s network filter. Most VPS hosts include one; turn on the game or always-on profile if offered.
- Before Node: a per-address limit on new TCP connections in the firewall, generous enough for a school or office behind one address, e.g. nftables
tcp dport 443 ct state new meter tcli4 { ip saddr limit rate over 30/second burst 60 packets } drop(and the same withip6 saddr). - In the proxy: compression (Caddy
encode; the one-call server already sends its scripts compressed and cached, so the proxy mostly helps the game pages) and short header timeouts (Caddyservers { timeouts { read_header 5s } }). Behind a proxy settrustProxyso limits count players, not the proxy.
Meters
Section titled “Meters”hub.stats().live: frames, bytes and messages per second, tick time p50/p99/max (the last 1,200 sub-ticks of 10 ms, about 12 s), slow readers, matches in progress, saves ok/failed, failed loads, world writes a minute, the 5 busiest rooms (players, bytes out a second, shared size; no names or ids) loop (event-loop delay over the last minute, {p50, p99, max} in ms, from LoopMonitor; a host app with its own server starts one next to its hub), pressure (the server is over its data cap or its loop runs late) and slowedRooms (rooms over their own budget). hub.stats() also has refused: turned-away and dropped counts by reason (full, joins, address, accept_rate, busy_rooms, silent, room_error, room_budget, pressure, too_fast, …). A host app can show the whole stats() on an admin page and a few totals in its health check.