diff --git a/README.md b/README.md index 701e307..59c2949 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,11 @@ Around the two hands: A duel against the bot is saved to the browser's local storage after every change, so it survives reading the rules, a refresh, or a phone putting the tab to sleep. Starting a new one asks first if one is under way. The seats this browser holds at shared duels are remembered the -same way and listed in the hall with whose move it is. Nothing is rendered on the server. +same way and listed in the hall with whose move it is; the hall asks before forgetting one +still in play. A player whose browser lost a seat (Safari's seven days, an app's own browser, +cleared data) can write to the keeper, whose `waving-hands-reseat.sh` gives the seat a new token +and prints a link carrying it in the fragment; the old token opens nothing after. Nothing is +rendered on the server. ## The duel server diff --git a/deploy/README.md b/deploy/README.md index 778d58d..e491582 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -52,6 +52,9 @@ A fresh host, when one is needed: `doctl compute droplet create hall --region ny /etc/cron.d/waving-hands on every deploy, so the live copies are the repo copies: - `waving-hands-visitors.sh [day]`: who is here now and who came that day. +- `waving-hands-reseat.sh ROOM [SEAT]`: who sits at a table; with a seat, a new + token for a player locked out of it, as a link to send them. It answers + through the duel server's `/keeper` door, which Caddy does not proxy. - `waving-hands-pulse.sh`: the weekly health check (service, errors, rollup trend, backup, box). - `waving-hands-rollup.sh [day]`: one JSON line per day of counts, run diff --git a/deploy/deploy.sh b/deploy/deploy.sh index ef1260a..52f9724 100755 --- a/deploy/deploy.sh +++ b/deploy/deploy.sh @@ -43,6 +43,7 @@ ssh "root@$HOST" ' install -m 755 /opt/waving-hands/app/deploy/pulse.sh /usr/local/bin/waving-hands-pulse.sh install -m 755 /opt/waving-hands/app/deploy/waving-hands-rollup.sh /usr/local/bin/waving-hands-rollup.sh install -m 755 /opt/waving-hands/app/deploy/waving-hands-backup.sh /usr/local/bin/waving-hands-backup.sh + install -m 755 /opt/waving-hands/app/deploy/waving-hands-reseat.sh /usr/local/bin/waving-hands-reseat.sh # On a host the hall shares, its hall-nightly.sh runs the rollup and backup # of every game and checks in with Sentry once for all; a game on a box of # its own schedules its own. diff --git a/deploy/waving-hands-reseat.sh b/deploy/waving-hands-reseat.sh new file mode 100755 index 0000000..c998aa1 --- /dev/null +++ b/deploy/waving-hands-reseat.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# A way back for a player whose browser lost their seat: the seat gets a new +# token, the old one stops working, and the link printed carries the new one. +# Whether the one asking holds that seat is the keeper's call; send the link +# only to them. Runs ON the droplet, through the duel server's keeper door. +# waving-hands-reseat.sh ROOM who sits at the table, and when each wizard last moved or spoke +# waving-hands-reseat.sh ROOM SEAT re-seat SEAT and print the link +set -euo pipefail +ROOM="${1:?usage: waving-hands-reseat.sh ROOM [SEAT]}" +DOOR="http://127.0.0.1:8788/keeper/rooms/${ROOM^^}" +if [ $# -lt 2 ]; then + curl -s "$DOOR" | python3 -c ' +import datetime, json, sys +r = json.load(sys.stdin) +if "error" in r: sys.exit(r["error"]) +print("room %s, %s" % (r["roomId"], "in play" if r["started"] else "not begun")) +for s in r["seats"]: + when = "bot" if s["bot"] else "never moved or spoke" if s["lastActed"] is None else "last acted " + datetime.datetime.fromtimestamp(s["lastActed"] / 1000, datetime.timezone.utc).strftime("%Y-%m-%d %H:%M UTC") + print(" %-3s %-24s %s" % (s["id"], s["name"], when)) +' +else + curl -s -X POST -H 'content-type: application/json' -d "{\"seat\":\"${2^^}\"}" "$DOOR/reseat" | python3 -c ' +import json, sys +r = json.load(sys.stdin) +if "error" in r: sys.exit(r["error"]) +print("%s has a new token; their old one opens nothing now. Send them this link:" % r["name"]) +print(r["link"]) +' +fi diff --git a/server/src/index.ts b/server/src/index.ts index 463acdb..bf36e68 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -23,7 +23,11 @@ // GET /api/tally what the ledgers add up to, for the hall // POST /api/reports/:id/answer {roomId, token, text} your word under the keeper's reply // -// Caddy serves the static site and proxies /api and /ws here. +// Caddy serves the static site and proxies /api and /ws here. The keeper's +// door answers only on the host itself (deploy/waving-hands-reseat.sh): +// +// GET /keeper/rooms/:id who sits at the table, and when each wizard last moved or spoke +// POST /keeper/rooms/:id/reseat {seat} a new token for a player locked out, as a link to send them import * as Sentry from '@sentry/node'; import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'; @@ -195,9 +199,24 @@ function readBody(req: IncomingMessage): Promise> { }); } +/** The keeper's door. Caddy proxies only /api and /ws, so it is reached from the host alone; a request Caddy forwarded is turned away besides. */ +async function handleKeeper(req: IncomingMessage, res: ServerResponse, parts: string[]): Promise { + if (req.headers['x-forwarded-for'] || parts[1] !== 'rooms') throw new RoomError('Not here.', 404); + const room = rooms.get(parts[2] ?? ''); + if (parts.length === 3 && req.method === 'GET') return send(res, 200, { roomId: room.id, started: !!room.state, seats: rooms.seatsForKeeper(room) }); + if (parts[3] === 'reseat' && parts.length === 4 && req.method === 'POST') { + const body = await readBody(req); + const { seat, token } = rooms.reseat(room, body.seat); + // The token rides the fragment, which the browser keeps to itself: it reaches neither Caddy's log nor this server. + return send(res, 200, { name: seat.name, link: `${PUBLIC_URL}/join/${room.id}#seat=${seat.id}.${token}` }); + } + throw new RoomError('Not here.', 404); +} + async function handle(req: IncomingMessage, res: ServerResponse): Promise { const url = new URL(req.url ?? '/', 'http://localhost'); const parts = url.pathname.split('/').filter(Boolean); + if (parts[0] === 'keeper') return handleKeeper(req, res, parts); if (parts[0] === 'api' && parts[1] === 'reports') return handleReports(req, res, parts); if (parts[0] === 'api' && parts[1] === 'tally' && parts.length === 2 && req.method === 'GET') return send(res, 200, tallies.get()); if (parts[0] === 'api' && parts[1] === 'transfer' && parts.length === 2 && req.method === 'POST') { diff --git a/server/src/rooms.test.ts b/server/src/rooms.test.ts new file mode 100644 index 0000000..1820dc4 --- /dev/null +++ b/server/src/rooms.test.ts @@ -0,0 +1,49 @@ +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { Rooms } from './rooms'; +import { Store } from './store'; + +let dir: string; +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'rooms-')); +}); +afterEach(() => { + rmSync(dir, { recursive: true, force: true }); +}); + +/** A table of three with Ann, who opened it, and Bo seated, the duel begun. */ +function table() { + const rooms = new Rooms(new Store(dir)); + const host = rooms.create('Ann', 3); + const guest = rooms.join(host.room, 'Bo'); + rooms.begin(host.room, host.token); + return { rooms, room: host.room, ann: host.token, bo: guest.token }; +} + +describe('rooms', () => { + it("gives a seat a new token at the keeper's word: the old one opens nothing, and a restart keeps the change", () => { + const { rooms, room, bo } = table(); + const phrase = rooms.transfer(room, bo).phrase; + const { seat, token } = rooms.reseat(room, 'B'); + expect(seat.name).toBe('Bo'); + expect(rooms.seatOf(room, token).id).toBe('B'); + expect(() => rooms.seatOf(room, bo)).toThrow(/opens no seat/); + // A phrase minted with the old token carries nothing now. + expect(() => rooms.claim(phrase)).toThrow(/unknown or has expired/); + const reopened = new Rooms(new Store(dir)).get(room.id); + expect(rooms.seatOf(reopened, token).id).toBe('B'); + expect(() => rooms.seatOf(reopened, bo)).toThrow(/opens no seat/); + }); + + it('re-seats only a wizard, and says when each last acted', () => { + const { rooms, room, ann } = table(); + expect(() => rooms.reseat(room, 'Z')).toThrow(/No wizard sits/); + rooms.submit(room, ann, { left: 'P', right: '-', casts: [] }, 0); + const seats = rooms.seatsForKeeper(room); + expect(seats.map((s) => [s.id, s.name])).toEqual([['A', 'Ann'], ['B', 'Bo']]); + expect(seats[0].lastActed).toBeGreaterThan(0); + expect(seats[1].lastActed).toBeNull(); + }); +}); diff --git a/server/src/rooms.ts b/server/src/rooms.ts index 520b82f..161d2d6 100644 --- a/server/src/rooms.ts +++ b/server/src/rooms.ts @@ -307,6 +307,30 @@ export class Rooms { return { seat, token }; } + /** + * The keeper gives a wizard's seat a new token, for a player whose browser lost the old one. Whether the one + * asking holds the seat is the keeper's judgment; this carries it out. The old token opens nothing after. + */ + reseat(room: Room, seatId: unknown): { seat: Seat; token: string } { + const seat = room.seats.find((s) => s.id === seatId && !s.bot); + if (!seat) throw new RoomError('No wizard sits in that seat.', 404); + const token = newId(18); + this.commit(room, { t: 'reseat', at: Date.now(), id: seat.id, tokenHash: hashToken(token) }); + // A phrase minted with the old token would carry a seat that no longer answers to it. + for (const [phrase, t] of this.transfers) if (t.roomId === room.id && t.seatId === seat.id) this.transfers.delete(phrase); + return { seat, token }; + } + + /** The table as the keeper sees it before re-seating: who sits where, and when each wizard last moved or spoke. */ + seatsForKeeper(room: Room): { id: WizardId; name: string; bot: boolean; lastActed: number | null }[] { + const last = new Map(); + for (const line of this.store.read(room.id)) { + if (line.t === 'input' || line.t === 'chat') last.set(line.id, line.at); + else if (line.t === 'turn') for (const id of Object.keys(line.inputs)) last.set(id, line.at); + } + return room.seats.map((s) => ({ id: s.id, name: s.name, bot: s.bot, lastActed: s.bot ? null : (last.get(s.id) ?? null) })); + } + /** The host sends a bot away before the duel begins. People leave by not coming back. */ unseat(room: Room, token: string | undefined, seatId: unknown): void { const host = this.seatOf(room, token); @@ -437,6 +461,11 @@ function apply(room: Room, line: LedgerLine): void { case 'seat': room.seats.push({ id: line.id, name: line.name, tokenHash: line.tokenHash ?? (line.token ? hashToken(line.token) : ''), bot: line.bot }); break; + case 'reseat': { + const seat = room.seats.find((s) => s.id === line.id); + if (seat) seat.tokenHash = line.tokenHash; + break; + } case 'input': room.pending[line.id] = line.input; break; diff --git a/server/src/store.ts b/server/src/store.ts index aa8df8a..67dbf1a 100644 --- a/server/src/store.ts +++ b/server/src/store.ts @@ -11,6 +11,8 @@ export type LedgerLine = | { t: 'room'; id: string; seats: number; createdAt: number; rematchOf?: string; expected?: string[] } /** A seat holds only the hash of its token; the token itself goes once to the browser that earned it. Ledgers written before hashing carry `token` and are read once more. */ | { t: 'seat'; id: WizardId; name: string; tokenHash?: string; token?: string; bot: boolean } + /** The keeper gave a wizard's seat a new token, for a player whose browser lost the old one; the old one opens nothing after. */ + | { t: 'reseat'; at: number; id: WizardId; tokenHash: string } /** One seat's move for the turn in progress, so a restart keeps it. The turn line that follows carries every input again. */ | { t: 'input'; at: number; id: WizardId; input: TurnInput } /** A bot sent away by the host before the duel began; its seat id is free again. */ diff --git a/src/lib/components/Hall.svelte b/src/lib/components/Hall.svelte index 31e5d95..8c0eeb1 100644 --- a/src/lib/components/Hall.svelte +++ b/src/lib/components/Hall.svelte @@ -167,7 +167,14 @@ if (c) void goto(`/join/${c}`); } + /** A duel in play asks before it is forgotten: this browser may be the only thing that holds the seat. */ + let forgetting = $state(null); function forget(roomId: string) { + if (!games[roomId]?.state?.over && forgetting !== roomId) { + forgetting = roomId; + return; + } + forgetting = null; forgetSeat(roomId); seats = allSeats(); } @@ -279,12 +286,16 @@ {/if} {#each seats as held (held.roomId)} -
+
{held.roomId} {status(held)}{#if unread(held) > 0} · {unread(held)} new {unread(held) === 1 ? 'line' : 'lines'} of talk{/if} - + {#if forgetting === held.roomId} + This browser may be all that holds your seat. + {:else} + + {/if}
{/each} {#if reports.length} @@ -675,6 +686,16 @@ color: var(--ember); } + /* The question takes a line of its own under the duel on a narrow screen. */ + .ledger-row.asking { + flex-wrap: wrap; + } + + .forget-ask { + font-size: 0.85em; + padding: 0 0.2rem 0.3rem; + } + .ledger-forget { background: none; border: 0; diff --git a/src/lib/game/client.ts b/src/lib/game/client.ts index 32b2dfb..75d290e 100644 --- a/src/lib/game/client.ts +++ b/src/lib/game/client.ts @@ -19,6 +19,12 @@ function heldSeats(): Record { } } +/** A seat the keeper sent in a link, `#seat=.`: a fragment stays in the browser, out of every log. */ +export function seatInLink(hash: string): HeldSeat | null { + const m = /^#seat=([^.]+)\.([A-Za-z0-9_-]+)$/.exec(hash); + return m ? { seat: m[1], token: m[2] } : null; +} + export function seatFor(roomId: string): HeldSeat | null { return heldSeats()[roomId] ?? null; } diff --git a/src/routes/guide/+page.svelte b/src/routes/guide/+page.svelte index abca559..5834380 100644 --- a/src/routes/guide/+page.svelte +++ b/src/routes/guide/+page.svelte @@ -104,7 +104,7 @@

A room's link is an invitation to sit while the table is laid and to watch once the duel has begun. Anyone who opens it without a seat takes a place in the Peanut Gallery. They see the ledger, the result of each turn and the chronicle, and the table can see how many are watching. The gallery is shown only what every wizard at the table could see. A gesture hidden from any one wizard is a question mark to the whole gallery, and the turn being written shows nothing at all.

Table talk, in the rail, is for the wizards seated. A line goes to everyone at the table and in the gallery, and it is kept with the duel. When you come back, the hall says how many lines were said while you were away. The gallery only listens unless the host lets it talk. Then a watcher signs a name, and their lines read Name (gallery).

Before a duel begins, any seated wizard may challenge the keeper, who looks after this site. A seat is held under the keeper's name and the keeper's phone rings. The note beside the button gives the hour where the keeper lives, so you know whether to wait or come back later.

-

When a duel is over, anyone at the table may call for a rematch. That opens a new table of the same size with the same bots, and holds a seat for everyone who played. Transfer seat at the top of the page gives you four words that move your seat to another device. They work for ten minutes, and you enter them in the hall on the other device.

+

When a duel is over, anyone at the table may call for a rematch. That opens a new table of the same size with the same bots, and holds a seat for everyone who played. Transfer seat at the top of the page gives you four words that move your seat to another device. They work for ten minutes, and you enter them in the hall on the other device. If your browser has lost your seat altogether, write to the keeper from the room's page, and the keeper can send you a link that brings it back.

diff --git a/src/routes/join/[code]/+page.svelte b/src/routes/join/[code]/+page.svelte index 304ac9b..8753081 100644 --- a/src/routes/join/[code]/+page.svelte +++ b/src/routes/join/[code]/+page.svelte @@ -1,10 +1,10 @@