forked from WikiDeck/wikideck
Play: online results from each player's side; finish timer survives polls
Found with a two-browser test against the modes host: the seat-1 player saw Defeat after winning (ResultView is now viewer-relative), and a poll could cancel the move to the results screen. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+138
-134
@@ -1,134 +1,138 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { ArrowLeft, LoaderCircle, Plus, RefreshCw, Users } from 'lucide-react';
|
||||
import { DEFAULT_RULESET, type Faction, type GameCard, type Stat } from '../../shared/game/index.ts';
|
||||
import { engineAction, resultView, uiActions, viewFromPlayerView } from './adapter.ts';
|
||||
import { toUICard } from './cards.ts';
|
||||
import { GameCard as GameCardFace } from './GameCard.tsx';
|
||||
import { MatchBoard } from './MatchBoard.tsx';
|
||||
import { online, type LobbySeat, type LobbyStatus, type OpenLobby } from './online.ts';
|
||||
import type { GameMode, ResultView, UIAction } from './types.ts';
|
||||
|
||||
const POLL_MS = 1000;
|
||||
const message = (e: unknown) => (e instanceof Error ? e.message : 'The host is unreachable.');
|
||||
|
||||
/** Human vs human on a mode hosted by this node: lobby list → (draft) → match, all via the host API. */
|
||||
export function OnlinePlay({ mode, playerName, onExit, onFinish }: {
|
||||
mode: GameMode; playerName: string; onExit: () => void; onFinish: (r: ResultView) => void;
|
||||
}) {
|
||||
const modeId = mode.remoteId ?? mode.id;
|
||||
const hostOrigin = (mode.host.kind === 'peer' && mode.host.url) || location.origin;
|
||||
const [lobbies, setLobbies] = useState<OpenLobby[]>();
|
||||
const [seat, setSeat] = useState<LobbySeat>();
|
||||
const [status, setStatus] = useState<LobbyStatus>();
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const inFlight = useRef(false);
|
||||
const finished = useRef(false);
|
||||
|
||||
const refreshLobbies = useCallback(() => {
|
||||
online.openLobbies(modeId).then(l => { setLobbies(l); setError(''); }, e => setError(message(e)));
|
||||
}, [modeId]);
|
||||
useEffect(() => {
|
||||
if (seat) return;
|
||||
refreshLobbies();
|
||||
const t = setInterval(refreshLobbies, 4000);
|
||||
return () => clearInterval(t);
|
||||
}, [seat, refreshLobbies]);
|
||||
|
||||
const poll = useCallback(async () => {
|
||||
if (!seat || inFlight.current) return;
|
||||
inFlight.current = true;
|
||||
try { setStatus(await online.status(seat)); setError(''); }
|
||||
catch (e) { setError(message(e)); }
|
||||
finally { inFlight.current = false; }
|
||||
}, [seat]);
|
||||
useEffect(() => {
|
||||
if (!seat) return;
|
||||
void poll();
|
||||
const t = setInterval(() => { void poll(); }, POLL_MS);
|
||||
return () => clearInterval(t);
|
||||
}, [seat, poll]);
|
||||
|
||||
useEffect(() => {
|
||||
const st = status?.state;
|
||||
if (finished.current || !status || !seat || status.phase !== 'finished' || !st?.result) return;
|
||||
finished.current = true;
|
||||
const names = st.lanes.map(l => l.topic.name);
|
||||
const t = setTimeout(() => onFinish(resultView(st.result!, seat.seat, names)), 900);
|
||||
return () => clearTimeout(t);
|
||||
}, [status, seat, onFinish]);
|
||||
|
||||
const enter = async (fn: () => Promise<LobbySeat>) => {
|
||||
setBusy(true); setError('');
|
||||
try { setSeat(await fn()); } catch (e) { setError(message(e)); } finally { setBusy(false); }
|
||||
};
|
||||
const leave = async () => {
|
||||
if (seat && status && !['finished', 'expired'].includes(status.phase)) await online.resign(seat).catch(() => {});
|
||||
onExit();
|
||||
};
|
||||
const send = async (fn: () => Promise<LobbyStatus>) => {
|
||||
try { setStatus(await fn()); setError(''); } catch (e) { setError(message(e)); void poll(); }
|
||||
};
|
||||
|
||||
// ----- lobby list -----
|
||||
if (!seat) return <section className="play-panel online-lobby" aria-labelledby="online-title">
|
||||
<div className="section-eyebrow">{mode.name.toUpperCase()} · ONLINE</div>
|
||||
<h2 id="online-title">Play a person</h2>
|
||||
<p className="muted">Matches run on this node{mode.host.kind === 'peer' ? `, hosted by ${mode.host.name}` : ''}. Decks come from the mode’s rules. You play as <b>{playerName}</b>.</p>
|
||||
<h3 className="lobby-label">Open lobbies <button className="icon-button" onClick={refreshLobbies} aria-label="Refresh lobbies"><RefreshCw size={14} /></button></h3>
|
||||
<div className="mode-list">
|
||||
{lobbies === undefined ? <p className="muted small"><LoaderCircle className="spin" size={13} /> Loading…</p>
|
||||
: lobbies.length ? lobbies.map(l => <button key={l.lobbyId} className="mode" disabled={busy} onClick={() => enter(() => online.join(l.lobbyId, playerName, hostOrigin))}>
|
||||
<span className="mode-icon"><Users size={18} /></span>
|
||||
<span className="mode-copy"><b>{String(l.host).slice(0, 24)}</b><small>Waiting {Math.max(0, Math.round((Date.now() - l.createdAt) / 60000))} min · tap to join</small></span>
|
||||
</button>)
|
||||
: <p className="muted small">No one is waiting. Create a lobby and share this page with a friend.</p>}
|
||||
</div>
|
||||
{error && <p className="dock-error small" role="alert">{error}</p>}
|
||||
<div className="play-dock"><div className="play-actions">
|
||||
<button className="button outline" onClick={onExit}><ArrowLeft size={16} /> Back</button>
|
||||
<button className="button dark play-cta" disabled={busy} onClick={() => enter(() => online.create(modeId, playerName, hostOrigin))}><Plus size={16} /> Create lobby</button>
|
||||
</div></div>
|
||||
</section>;
|
||||
|
||||
const phase = status?.phase;
|
||||
// ----- match -----
|
||||
if ((phase === 'playing' || phase === 'finished') && status?.state) {
|
||||
const view = viewFromPlayerView(status.state);
|
||||
const legal = uiActions(status.legalActions ?? []);
|
||||
const opp = status.players.find((_, i) => i !== seat.seat)?.name ?? 'Opponent';
|
||||
const act = (a: UIAction) => {
|
||||
if (a.type === 'concede') return void send(() => online.resign(seat));
|
||||
return void send(() => online.act(seat, engineAction(a, seat.seat)));
|
||||
};
|
||||
return <MatchBoard title={`${mode.name} online match`} opponent={opp.slice(0, 24)} view={view} legal={legal} onAct={act}
|
||||
error={error} onTopicBonus={status.state.ruleset.onTopicBonus} />;
|
||||
}
|
||||
|
||||
// ----- draft -----
|
||||
if (phase === 'drafting' && status?.draft) {
|
||||
const mine = status.draft.toPick === seat.seat;
|
||||
const toCard = (c: NonNullable<LobbyStatus['draft']>['pool'][number]['card']) => toUICard({ ...c, rarity: 'Common', source: 'loaner', check: 'loaner',
|
||||
faction: c.faction as Faction, home: c.home as Stat, trend: (Math.sign(c.trend) as -1 | 0 | 1) } as GameCard, DEFAULT_RULESET);
|
||||
return <section className="play-panel" aria-labelledby="draft-title">
|
||||
<div className="section-eyebrow">{mode.name.toUpperCase()} · DRAFT</div>
|
||||
<h2 id="draft-title">{mine ? 'Your pick' : 'Opponent is picking…'}</h2>
|
||||
<p className="muted">Take turns picking cards for your deck. {Math.max(0, Math.round((status.draft.deadline - Date.now()) / 1000))} s left on this pick.</p>
|
||||
<div className="pool-grid">{status.draft.pool.map(p => <GameCardFace key={p.index} card={toCard(p.card)} size="deck"
|
||||
selected={p.takenBy === seat.seat} dim={p.takenBy !== null && p.takenBy !== seat.seat}
|
||||
onClick={mine && p.takenBy === null ? () => void send(() => online.pick(seat, p.index)) : undefined} />)}</div>
|
||||
{error && <p className="dock-error small" role="alert">{error}</p>}
|
||||
<div className="play-dock"><div className="play-actions"><button className="button outline" onClick={leave}>Resign</button></div></div>
|
||||
</section>;
|
||||
}
|
||||
|
||||
// ----- waiting / starting / expired -----
|
||||
return <section className="play-panel" aria-labelledby="wait-title">
|
||||
<div className="section-eyebrow">{mode.name.toUpperCase()} · LOBBY</div>
|
||||
<h2 id="wait-title">{phase === 'expired' ? 'This lobby expired' : phase === 'waiting' ? 'Waiting for an opponent' : 'Starting…'}</h2>
|
||||
<p className="muted">{phase === 'expired' ? 'Nobody joined in time. Create a new lobby to try again.'
|
||||
: <><LoaderCircle className="spin" size={14} /> {phase === 'waiting' ? 'Your lobby is listed for other players on this node.' : 'Setting up the match.'}</>}</p>
|
||||
{error && <p className="dock-error small" role="alert">{error}</p>}
|
||||
<div className="play-dock"><div className="play-actions"><button className="button outline" onClick={leave}><ArrowLeft size={16} /> {phase === 'expired' ? 'Back' : 'Cancel'}</button></div></div>
|
||||
</section>;
|
||||
}
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { ArrowLeft, LoaderCircle, Plus, RefreshCw, Users } from 'lucide-react';
|
||||
import { DEFAULT_RULESET, type Faction, type GameCard, type Stat } from '../../shared/game/index.ts';
|
||||
import { engineAction, resultView, uiActions, viewFromPlayerView } from './adapter.ts';
|
||||
import { toUICard } from './cards.ts';
|
||||
import { GameCard as GameCardFace } from './GameCard.tsx';
|
||||
import { MatchBoard } from './MatchBoard.tsx';
|
||||
import { online, type LobbySeat, type LobbyStatus, type OpenLobby } from './online.ts';
|
||||
import type { GameMode, ResultView, UIAction } from './types.ts';
|
||||
|
||||
const POLL_MS = 1000;
|
||||
const message = (e: unknown) => (e instanceof Error ? e.message : 'The host is unreachable.');
|
||||
|
||||
/** Human vs human on a mode hosted by this node: lobby list → (draft) → match, all via the host API. */
|
||||
export function OnlinePlay({ mode, playerName, onExit, onFinish }: {
|
||||
mode: GameMode; playerName: string; onExit: () => void; onFinish: (r: ResultView) => void;
|
||||
}) {
|
||||
const modeId = mode.remoteId ?? mode.id;
|
||||
const hostOrigin = (mode.host.kind === 'peer' && mode.host.url) || location.origin;
|
||||
const [lobbies, setLobbies] = useState<OpenLobby[]>();
|
||||
const [seat, setSeat] = useState<LobbySeat>();
|
||||
const [status, setStatus] = useState<LobbyStatus>();
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const inFlight = useRef(false);
|
||||
const finished = useRef(false);
|
||||
const done = status?.phase === 'finished' || status?.phase === 'expired';
|
||||
|
||||
const refreshLobbies = useCallback(() => {
|
||||
online.openLobbies(modeId).then(l => { setLobbies(l); setError(''); }, e => setError(message(e)));
|
||||
}, [modeId]);
|
||||
useEffect(() => {
|
||||
if (seat) return;
|
||||
refreshLobbies();
|
||||
const t = setInterval(refreshLobbies, 4000);
|
||||
return () => clearInterval(t);
|
||||
}, [seat, refreshLobbies]);
|
||||
|
||||
const poll = useCallback(async () => {
|
||||
if (!seat || inFlight.current) return;
|
||||
inFlight.current = true;
|
||||
try { setStatus(await online.status(seat)); setError(''); }
|
||||
catch (e) { setError(message(e)); }
|
||||
finally { inFlight.current = false; }
|
||||
}, [seat]);
|
||||
useEffect(() => {
|
||||
if (!seat || done) return;
|
||||
void poll();
|
||||
const t = setInterval(() => { void poll(); }, POLL_MS);
|
||||
return () => clearInterval(t);
|
||||
}, [seat, poll, done]);
|
||||
|
||||
// Once finished, stop polling and show results after a beat. The timer must survive later
|
||||
// re-renders, so it is only cleared on unmount.
|
||||
const finishTimer = useRef<ReturnType<typeof setTimeout>>(undefined);
|
||||
useEffect(() => {
|
||||
const st = status?.state;
|
||||
if (finished.current || !status || !seat || status.phase !== 'finished' || !st?.result) return;
|
||||
finished.current = true;
|
||||
const names = st.lanes.map(l => l.topic.name);
|
||||
finishTimer.current = setTimeout(() => onFinish(resultView(st.result!, seat.seat, names)), 900);
|
||||
}, [status, seat, onFinish]);
|
||||
useEffect(() => () => clearTimeout(finishTimer.current), []);
|
||||
|
||||
const enter = async (fn: () => Promise<LobbySeat>) => {
|
||||
setBusy(true); setError('');
|
||||
try { setSeat(await fn()); } catch (e) { setError(message(e)); } finally { setBusy(false); }
|
||||
};
|
||||
const leave = async () => {
|
||||
if (seat && status && !['finished', 'expired'].includes(status.phase)) await online.resign(seat).catch(() => {});
|
||||
onExit();
|
||||
};
|
||||
const send = async (fn: () => Promise<LobbyStatus>) => {
|
||||
try { setStatus(await fn()); setError(''); } catch (e) { setError(message(e)); void poll(); }
|
||||
};
|
||||
|
||||
// ----- lobby list -----
|
||||
if (!seat) return <section className="play-panel online-lobby" aria-labelledby="online-title">
|
||||
<div className="section-eyebrow">{mode.name.toUpperCase()} · ONLINE</div>
|
||||
<h2 id="online-title">Play a person</h2>
|
||||
<p className="muted">Matches run on this node{mode.host.kind === 'peer' ? `, hosted by ${mode.host.name}` : ''}. Decks come from the mode’s rules. You play as <b>{playerName}</b>.</p>
|
||||
<h3 className="lobby-label">Open lobbies <button className="icon-button" onClick={refreshLobbies} aria-label="Refresh lobbies"><RefreshCw size={14} /></button></h3>
|
||||
<div className="mode-list">
|
||||
{lobbies === undefined ? <p className="muted small"><LoaderCircle className="spin" size={13} /> Loading…</p>
|
||||
: lobbies.length ? lobbies.map(l => <button key={l.lobbyId} className="mode" disabled={busy} onClick={() => enter(() => online.join(l.lobbyId, playerName, hostOrigin))}>
|
||||
<span className="mode-icon"><Users size={18} /></span>
|
||||
<span className="mode-copy"><b>{String(l.host).slice(0, 24)}</b><small>Waiting {Math.max(0, Math.round((Date.now() - l.createdAt) / 60000))} min · tap to join</small></span>
|
||||
</button>)
|
||||
: <p className="muted small">No one is waiting. Create a lobby and share this page with a friend.</p>}
|
||||
</div>
|
||||
{error && <p className="dock-error small" role="alert">{error}</p>}
|
||||
<div className="play-dock"><div className="play-actions">
|
||||
<button className="button outline" onClick={onExit}><ArrowLeft size={16} /> Back</button>
|
||||
<button className="button dark play-cta" disabled={busy} onClick={() => enter(() => online.create(modeId, playerName, hostOrigin))}><Plus size={16} /> Create lobby</button>
|
||||
</div></div>
|
||||
</section>;
|
||||
|
||||
const phase = status?.phase;
|
||||
// ----- match -----
|
||||
if ((phase === 'playing' || phase === 'finished') && status?.state) {
|
||||
const view = viewFromPlayerView(status.state);
|
||||
const legal = uiActions(status.legalActions ?? []);
|
||||
const opp = status.players.find((_, i) => i !== seat.seat)?.name ?? 'Opponent';
|
||||
const act = (a: UIAction) => {
|
||||
if (a.type === 'concede') return void send(() => online.resign(seat));
|
||||
return void send(() => online.act(seat, engineAction(a, seat.seat)));
|
||||
};
|
||||
return <MatchBoard title={`${mode.name} online match`} opponent={opp.slice(0, 24)} view={view} legal={legal} onAct={act}
|
||||
error={error} onTopicBonus={status.state.ruleset.onTopicBonus} />;
|
||||
}
|
||||
|
||||
// ----- draft -----
|
||||
if (phase === 'drafting' && status?.draft) {
|
||||
const mine = status.draft.toPick === seat.seat;
|
||||
const toCard = (c: NonNullable<LobbyStatus['draft']>['pool'][number]['card']) => toUICard({ ...c, rarity: 'Common', source: 'loaner', check: 'loaner',
|
||||
faction: c.faction as Faction, home: c.home as Stat, trend: (Math.sign(c.trend) as -1 | 0 | 1) } as GameCard, DEFAULT_RULESET);
|
||||
return <section className="play-panel" aria-labelledby="draft-title">
|
||||
<div className="section-eyebrow">{mode.name.toUpperCase()} · DRAFT</div>
|
||||
<h2 id="draft-title">{mine ? 'Your pick' : 'Opponent is picking…'}</h2>
|
||||
<p className="muted">Take turns picking cards for your deck. {Math.max(0, Math.round((status.draft.deadline - Date.now()) / 1000))} s left on this pick.</p>
|
||||
<div className="pool-grid">{status.draft.pool.map(p => <GameCardFace key={p.index} card={toCard(p.card)} size="deck"
|
||||
selected={p.takenBy === seat.seat} dim={p.takenBy !== null && p.takenBy !== seat.seat}
|
||||
onClick={mine && p.takenBy === null ? () => void send(() => online.pick(seat, p.index)) : undefined} />)}</div>
|
||||
{error && <p className="dock-error small" role="alert">{error}</p>}
|
||||
<div className="play-dock"><div className="play-actions"><button className="button outline" onClick={leave}>Resign</button></div></div>
|
||||
</section>;
|
||||
}
|
||||
|
||||
// ----- waiting / starting / expired -----
|
||||
return <section className="play-panel" aria-labelledby="wait-title">
|
||||
<div className="section-eyebrow">{mode.name.toUpperCase()} · LOBBY</div>
|
||||
<h2 id="wait-title">{phase === 'expired' ? 'This lobby expired' : phase === 'waiting' ? 'Waiting for an opponent' : 'Starting…'}</h2>
|
||||
<p className="muted">{phase === 'expired' ? 'Nobody joined in time. Create a new lobby to try again.'
|
||||
: <><LoaderCircle className="spin" size={14} /> {phase === 'waiting' ? 'Your lobby is listed for other players on this node.' : 'Setting up the match.'}</>}</p>
|
||||
{error && <p className="dock-error small" role="alert">{error}</p>}
|
||||
<div className="play-dock"><div className="play-actions"><button className="button outline" onClick={leave}><ArrowLeft size={16} /> {phase === 'expired' ? 'Back' : 'Cancel'}</button></div></div>
|
||||
</section>;
|
||||
}
|
||||
|
||||
+4
-3
@@ -115,14 +115,15 @@ export function viewFromPlayerView(v: PlayerView, opts: { log?: string[]; capaci
|
||||
};
|
||||
}
|
||||
|
||||
/** Results from `me`'s point of view (winner stays an absolute seat; the screen compares it to `me`). */
|
||||
/** Results from `me`'s point of view: in a ResultView, 0 always means "you" and 1 "your opponent". */
|
||||
export function resultView(r: MatchResult, me: PlayerId, laneNames: string[]): ResultView {
|
||||
const opp: PlayerId = me === 0 ? 1 : 0;
|
||||
return {
|
||||
winner: r.winner, turns: r.turns, reason: r.reason, totalPower: [r.totalPower[me], r.totalPower[opp]],
|
||||
winner: r.winner === null ? null : r.winner === me ? 0 : 1, turns: r.turns, reason: r.reason,
|
||||
totalPower: [r.totalPower[me], r.totalPower[opp]],
|
||||
lanes: r.lanePower.map((pw, i) => {
|
||||
const a = pw[me], b = pw[opp];
|
||||
return { name: laneNames[i] ?? `Topic ${i + 1}`, myPower: a, theirPower: b, winner: a === b ? null : a > b ? me : opp };
|
||||
return { name: laneNames[i] ?? `Topic ${i + 1}`, myPower: a, theirPower: b, winner: a === b ? null : a > b ? 0 : 1 };
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
+64
-64
@@ -1,64 +1,64 @@
|
||||
// Client for lobbies hosted by this node (modes team, docs/game/HOSTING.md §3). Same-origin only:
|
||||
// peers' modes are opened on the peer's own site. Every response is untrusted input.
|
||||
import type { Action, PlayerView } from '../../shared/game/index.ts';
|
||||
|
||||
export type LobbySeat = { lobbyId: string; seat: 0 | 1; token: string };
|
||||
export type DraftCard = { index: number; takenBy: 0 | 1 | null; card: { cardId: string; title: string; pageId: number | null; faction: string; cost: number; power: number; home: string; trend: number; keyword: string | null } };
|
||||
export type LobbyStatus = {
|
||||
lobbyId: string; phase: 'waiting' | 'starting' | 'drafting' | 'playing' | 'finished' | 'expired';
|
||||
seat: 0 | 1 | null; players: { id: string; name: string }[];
|
||||
outcome: { winner: 0 | 1 | null; reason: string } | null;
|
||||
state?: PlayerView; legalActions?: Action[];
|
||||
draft?: { pool: DraftCard[]; toPick: 0 | 1 | null; deadline: number };
|
||||
};
|
||||
export type OpenLobby = { lobbyId: string; host: string; createdAt: number };
|
||||
|
||||
const MASTER_KEY = 'wikideck-player-master';
|
||||
const b64url = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
||||
|
||||
function masterSecret(): string {
|
||||
try {
|
||||
const existing = localStorage.getItem(MASTER_KEY);
|
||||
if (existing && /^[A-Za-z0-9_-]{43}$/.test(existing)) return existing;
|
||||
const fresh = b64url(crypto.getRandomValues(new Uint8Array(32)));
|
||||
localStorage.setItem(MASTER_KEY, fresh);
|
||||
return fresh;
|
||||
} catch { return b64url(crypto.getRandomValues(new Uint8Array(32))); } // storage blocked: per-session identity
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-host player secret: base64url(HMAC-SHA256(master, hostOrigin)), 43 chars. A host derives the
|
||||
* leaderboard id from it, so a malicious host can't replay it on another host (night-review, #5).
|
||||
*/
|
||||
export async function playerSecret(hostOrigin: string): Promise<string> {
|
||||
const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(masterSecret()), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
|
||||
return b64url(new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(hostOrigin))));
|
||||
}
|
||||
|
||||
/** Host display names allow 1–24 letters, digits, spaces and _ . - */
|
||||
export function lobbyName(name: string | undefined): string {
|
||||
const clean = (name ?? '').normalize('NFC').replace(/[^\p{L}\p{N} _.-]/gu, '').trim().slice(0, 24);
|
||||
return clean || `Guest ${masterSecret().slice(0, 4)}`;
|
||||
}
|
||||
|
||||
async function call<T>(path: string, init: { method?: string; body?: unknown; token?: string } = {}): Promise<T> {
|
||||
const res = await fetch(`/api/game/${path}`, {
|
||||
method: init.method ?? (init.body === undefined ? 'GET' : 'POST'), cache: 'no-store', signal: AbortSignal.timeout(10000),
|
||||
headers: { ...(init.body === undefined ? {} : { 'Content-Type': 'application/json' }), ...(init.token ? { Authorization: `Bearer ${init.token}` } : {}) },
|
||||
...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }),
|
||||
});
|
||||
const data = res.headers.get('content-type')?.includes('json') ? await res.json().catch(() => ({})) : {};
|
||||
if (!res.ok) throw new Error(typeof data?.error === 'string' ? data.error.slice(0, 200) : `The host answered ${res.status}.`);
|
||||
return data as T;
|
||||
}
|
||||
|
||||
const id = (s: string) => encodeURIComponent(s);
|
||||
export const online = {
|
||||
openLobbies: (modeId: string) => call<{ lobbies: OpenLobby[] }>(`modes/${id(modeId)}/lobbies`).then(r => Array.isArray(r.lobbies) ? r.lobbies.slice(0, 50) : []),
|
||||
create: async (modeId: string, name: string, hostOrigin: string) => call<LobbySeat>(`modes/${id(modeId)}/lobbies`, { body: { name, secret: await playerSecret(hostOrigin) } }),
|
||||
join: async (lobbyId: string, name: string, hostOrigin: string) => call<LobbySeat>(`lobbies/${id(lobbyId)}/join`, { body: { name, secret: await playerSecret(hostOrigin) } }),
|
||||
status: (s: LobbySeat) => call<LobbyStatus>(`lobbies/${id(s.lobbyId)}`, { token: s.token }),
|
||||
act: (s: LobbySeat, action: Action) => call<LobbyStatus>(`lobbies/${id(s.lobbyId)}/actions`, { body: { action }, token: s.token }),
|
||||
pick: (s: LobbySeat, index: number) => call<LobbyStatus>(`lobbies/${id(s.lobbyId)}/pick`, { body: { index }, token: s.token }),
|
||||
resign: (s: LobbySeat) => call<LobbyStatus>(`lobbies/${id(s.lobbyId)}/resign`, { body: {}, token: s.token }),
|
||||
};
|
||||
// Client for lobbies hosted by this node (modes team, docs/game/HOSTING.md §3). Same-origin only:
|
||||
// peers' modes are opened on the peer's own site. Every response is untrusted input.
|
||||
import type { Action, PlayerView } from '../../shared/game/index.ts';
|
||||
|
||||
export type LobbySeat = { lobbyId: string; seat: 0 | 1; token: string };
|
||||
export type DraftCard = { index: number; takenBy: 0 | 1 | null; card: { cardId: string; title: string; pageId: number | null; faction: string; cost: number; power: number; home: string; trend: number; keyword: string | null } };
|
||||
export type LobbyStatus = {
|
||||
lobbyId: string; phase: 'waiting' | 'starting' | 'drafting' | 'playing' | 'finished' | 'expired';
|
||||
seat: 0 | 1 | null; players: { id: string; name: string }[];
|
||||
outcome: { winner: 0 | 1 | null; reason: string } | null;
|
||||
state?: PlayerView; legalActions?: Action[];
|
||||
draft?: { pool: DraftCard[]; toPick: 0 | 1 | null; deadline: number };
|
||||
};
|
||||
export type OpenLobby = { lobbyId: string; host: string; createdAt: number };
|
||||
|
||||
const MASTER_KEY = 'wikideck-player-master';
|
||||
const b64url = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
||||
|
||||
function masterSecret(): string {
|
||||
try {
|
||||
const existing = localStorage.getItem(MASTER_KEY);
|
||||
if (existing && /^[A-Za-z0-9_-]{43}$/.test(existing)) return existing;
|
||||
const fresh = b64url(crypto.getRandomValues(new Uint8Array(32)));
|
||||
localStorage.setItem(MASTER_KEY, fresh);
|
||||
return fresh;
|
||||
} catch { return b64url(crypto.getRandomValues(new Uint8Array(32))); } // storage blocked: per-session identity
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-host player secret: base64url(HMAC-SHA256(master, hostOrigin)), 43 chars. A host derives the
|
||||
* leaderboard id from it, so a malicious host can't replay it on another host (night-review, #5).
|
||||
*/
|
||||
export async function playerSecret(hostOrigin: string): Promise<string> {
|
||||
const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(masterSecret()), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
|
||||
return b64url(new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(hostOrigin))));
|
||||
}
|
||||
|
||||
/** Host display names allow 1–24 letters, digits, spaces and _ . - */
|
||||
export function lobbyName(name: string | undefined): string {
|
||||
const clean = (name ?? '').normalize('NFC').replace(/[^\p{L}\p{N} _.-]/gu, '').trim().slice(0, 24);
|
||||
return clean || `Guest ${masterSecret().slice(0, 4)}`;
|
||||
}
|
||||
|
||||
async function call<T>(path: string, init: { method?: string; body?: unknown; token?: string } = {}): Promise<T> {
|
||||
const res = await fetch(`/api/game/${path}`, {
|
||||
method: init.method ?? (init.body === undefined ? 'GET' : 'POST'), cache: 'no-store', signal: AbortSignal.timeout(10000),
|
||||
headers: { ...(init.body === undefined ? {} : { 'Content-Type': 'application/json' }), ...(init.token ? { Authorization: `Bearer ${init.token}` } : {}) },
|
||||
...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }),
|
||||
});
|
||||
const data = res.headers.get('content-type')?.includes('json') ? await res.json().catch(() => ({})) : {};
|
||||
if (!res.ok) throw new Error(typeof data?.error === 'string' ? data.error.slice(0, 200) : `The host answered ${res.status}.`);
|
||||
return data as T;
|
||||
}
|
||||
|
||||
const id = (s: string) => encodeURIComponent(s);
|
||||
export const online = {
|
||||
openLobbies: (modeId: string) => call<{ lobbies: OpenLobby[] }>(`modes/${id(modeId)}/lobbies`).then(r => Array.isArray(r.lobbies) ? r.lobbies.slice(0, 50) : []),
|
||||
create: async (modeId: string, name: string, hostOrigin: string) => call<LobbySeat>(`modes/${id(modeId)}/lobbies`, { body: { name, secret: await playerSecret(hostOrigin) } }),
|
||||
join: async (lobbyId: string, name: string, hostOrigin: string) => call<LobbySeat>(`lobbies/${id(lobbyId)}/join`, { body: { name, secret: await playerSecret(hostOrigin) } }),
|
||||
status: (s: LobbySeat) => call<LobbyStatus>(`lobbies/${id(s.lobbyId)}`, { token: s.token }),
|
||||
act: (s: LobbySeat, action: Action) => call<LobbyStatus>(`lobbies/${id(s.lobbyId)}/actions`, { body: { action }, token: s.token }),
|
||||
pick: (s: LobbySeat, index: number) => call<LobbyStatus>(`lobbies/${id(s.lobbyId)}/pick`, { body: { index }, token: s.token }),
|
||||
resign: (s: LobbySeat) => call<LobbyStatus>(`lobbies/${id(s.lobbyId)}/resign`, { body: {}, token: s.token }),
|
||||
};
|
||||
|
||||
+2
-1
@@ -67,8 +67,9 @@ export type UIAction = (
|
||||
| { type: 'concede' }
|
||||
) & { engine?: Action };
|
||||
|
||||
/** Always from the viewer's side: 0 = you, 1 = your opponent, null = draw. */
|
||||
export type ResultView = {
|
||||
winner: PlayerIndex | null; // null = draw
|
||||
winner: PlayerIndex | null;
|
||||
lanes: { name: string; myPower: number; theirPower: number; winner: PlayerIndex | null }[];
|
||||
turns: number;
|
||||
reason: MatchResult['reason'];
|
||||
|
||||
+108
-106
@@ -1,106 +1,108 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { DEFAULT_RULESET } from '../shared/game/index.ts';
|
||||
import { engine } from '../src/game/adapter.ts';
|
||||
import { randomBot } from '../src/game/bots.ts';
|
||||
import { cardFromBlock, loanerPool, opponentDeck, starterDeck } from '../src/game/cards.ts';
|
||||
import { deckProblem, deckWarning } from '../src/game/DeckBuilder.tsx';
|
||||
import { parseModeList } from '../src/game/useModes.ts';
|
||||
import type { PlayerIndex } from '../src/game/types.ts';
|
||||
import type { TestnetBlock } from '../shared/testnet.ts';
|
||||
|
||||
function rand(seed: number) { return () => ((seed = (seed * 1103515245 + 12345) >>> 0) / 4294967296); }
|
||||
|
||||
/** Both seats driven by the UI bot through the UI adapter, exactly as the match screen does. */
|
||||
function playOut(seed: string) {
|
||||
let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck(seed)], seed);
|
||||
const r = rand(seed.length * 7919 + 1);
|
||||
for (let steps = 0; steps < 2000 && !engine.isOver(s); steps++) {
|
||||
for (const p of [0, 1] as PlayerIndex[]) {
|
||||
const legal = engine.legal(s, p).filter(a => a.type !== 'concede');
|
||||
if (!legal.length) continue;
|
||||
s = engine.apply(s, p, randomBot.choose(engine.view(s, p), legal, r));
|
||||
}
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
test('the starter deck is a legal Standard deck and the bot gets a legal deck too', () => {
|
||||
assert.equal(deckProblem(starterDeck(), DEFAULT_RULESET), '');
|
||||
assert.equal(deckProblem(opponentDeck('x'), DEFAULT_RULESET), '');
|
||||
assert.match(deckProblem(starterDeck().slice(1), DEFAULT_RULESET), /exactly 12/);
|
||||
});
|
||||
|
||||
test('the deck curve warning is soft advice for fewer than 4 cards of cost 2 or less', () => {
|
||||
const pool = loanerPool();
|
||||
const heavy = pool.filter(c => c.cost >= 3).slice(0, 12);
|
||||
assert.match(deckWarning(heavy), /cost 2 or less/);
|
||||
assert.equal(deckWarning(starterDeck()), '');
|
||||
});
|
||||
|
||||
test('UI-driven random play always finishes within the turn cap and is deterministic', () => {
|
||||
for (let i = 0; i < 40; i++) {
|
||||
const a = playOut(`seed-${i}`), b = playOut(`seed-${i}`);
|
||||
assert.ok(engine.isOver(a), `match ${i} finished`);
|
||||
const ra = engine.result(a, 0);
|
||||
assert.ok(ra.turns <= DEFAULT_RULESET.turns, `match ${i}: ${JSON.stringify(ra)}`);
|
||||
assert.deepEqual(ra, engine.result(b, 0));
|
||||
assert.equal(engine.result(a, 1).winner, ra.winner);
|
||||
}
|
||||
});
|
||||
|
||||
test('my view never shows the opponent’s queued cards', () => {
|
||||
// Find a seed where the opponent has a turn-1 play (cost 1 in the opening hand).
|
||||
let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck('h0')], 'hidden-0');
|
||||
for (let i = 1; i < 50 && !engine.legal(s, 1).some(a => a.type === 'play'); i++)
|
||||
s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck(`h${i}`)], `hidden-${i}`);
|
||||
const play = engine.legal(s, 1).find(a => a.type === 'play');
|
||||
assert.ok(play, 'some seed gives the opponent a turn-1 play');
|
||||
s = engine.apply(s, 1, play!);
|
||||
const mine = engine.view(s, 0);
|
||||
assert.equal(mine.lanes.flatMap(l => [...l.theirs, ...l.staged]).length, 0);
|
||||
assert.equal(mine.oppQueued, 1);
|
||||
const theirs = engine.view(s, 1);
|
||||
assert.equal(theirs.lanes.flatMap(l => l.staged).length, 1);
|
||||
assert.ok(!theirs.hand.some(c => play!.type === 'play' && c.id === play!.cardId), 'a queued card leaves the visible hand');
|
||||
});
|
||||
|
||||
test('unstage refunds energy, and illegal plays are explained', () => {
|
||||
let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck('e')], 'energy');
|
||||
const v = engine.view(s, 0);
|
||||
const expensive = v.hand.find(c => c.cost > v.energy);
|
||||
if (expensive) assert.ok(engine.problem(s, 0, { type: 'play', cardId: expensive.id, lane: 0 }));
|
||||
const play = engine.legal(s, 0).find(a => a.type === 'play');
|
||||
if (play?.type === 'play') {
|
||||
s = engine.apply(s, 0, play);
|
||||
assert.ok(engine.view(s, 0).energy < v.energy);
|
||||
s = engine.apply(s, 0, { type: 'unstage', cardId: play.cardId });
|
||||
assert.equal(engine.view(s, 0).energy, v.energy);
|
||||
}
|
||||
});
|
||||
|
||||
test('an owned NFT maps to a sidegrade card that the engine accepts', () => {
|
||||
const block = { tokenId: 'ab'.repeat(32), powHash: '00'.repeat(32), article: { pageId: 42, title: 'Test', category: 'Space', image: undefined },
|
||||
statsSnapshot: { stats: { attention: 100, depth: 100, reach: 100 } } } as unknown as TestnetBlock;
|
||||
const card = cardFromBlock(block);
|
||||
assert.equal(card.source, 'nft');
|
||||
assert.ok(card.cost <= DEFAULT_RULESET.uncheckedCostCap, 'forged max stats are capped');
|
||||
assert.equal(card.basePower, DEFAULT_RULESET.powerByCost[card.cost]);
|
||||
const deck = [card, ...starterDeck().slice(1)];
|
||||
assert.equal(deckProblem(deck, DEFAULT_RULESET), '');
|
||||
});
|
||||
|
||||
test('peer mode lists are parsed defensively', () => {
|
||||
const modes = parseModeList({ host: { origin: 'http://192.168.1.32:3102', operator: 'node-b' }, modes: [
|
||||
{ mode: { id: 'trending', name: 'Trending', description: 'x'.repeat(1000), rules: { turns: 5 } }, stats: { playersOnline: 3, matchesPlayed: 9 } },
|
||||
{ mode: { id: 'bad', name: 'Bad rules', rules: { turns: 999 } } },
|
||||
{ mode: { name: 'no id' } }, 'junk', null,
|
||||
] }, { self: false, origin: 'http://192.168.1.32:3102' });
|
||||
assert.equal(modes.length, 1);
|
||||
const [m] = modes;
|
||||
assert.equal(m.host.kind === 'peer' && m.host.name, 'node-b');
|
||||
assert.equal(m.ruleset.turns, 5);
|
||||
assert.ok(m.description.length <= 280);
|
||||
assert.equal(m.players, 3);
|
||||
assert.deepEqual(parseModeList('nope', { self: true, origin: '' }), []);
|
||||
});
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { DEFAULT_RULESET } from '../shared/game/index.ts';
|
||||
import { engine } from '../src/game/adapter.ts';
|
||||
import { randomBot } from '../src/game/bots.ts';
|
||||
import { cardFromBlock, loanerPool, opponentDeck, starterDeck } from '../src/game/cards.ts';
|
||||
import { deckProblem, deckWarning } from '../src/game/DeckBuilder.tsx';
|
||||
import { parseModeList } from '../src/game/useModes.ts';
|
||||
import type { PlayerIndex } from '../src/game/types.ts';
|
||||
import type { TestnetBlock } from '../shared/testnet.ts';
|
||||
|
||||
function rand(seed: number) { return () => ((seed = (seed * 1103515245 + 12345) >>> 0) / 4294967296); }
|
||||
|
||||
/** Both seats driven by the UI bot through the UI adapter, exactly as the match screen does. */
|
||||
function playOut(seed: string) {
|
||||
let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck(seed)], seed);
|
||||
const r = rand(seed.length * 7919 + 1);
|
||||
for (let steps = 0; steps < 2000 && !engine.isOver(s); steps++) {
|
||||
for (const p of [0, 1] as PlayerIndex[]) {
|
||||
const legal = engine.legal(s, p).filter(a => a.type !== 'concede');
|
||||
if (!legal.length) continue;
|
||||
s = engine.apply(s, p, randomBot.choose(engine.view(s, p), legal, r));
|
||||
}
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
test('the starter deck is a legal Standard deck and the bot gets a legal deck too', () => {
|
||||
assert.equal(deckProblem(starterDeck(), DEFAULT_RULESET), '');
|
||||
assert.equal(deckProblem(opponentDeck('x'), DEFAULT_RULESET), '');
|
||||
assert.match(deckProblem(starterDeck().slice(1), DEFAULT_RULESET), /exactly 12/);
|
||||
});
|
||||
|
||||
test('the deck curve warning is soft advice for fewer than 4 cards of cost 2 or less', () => {
|
||||
const pool = loanerPool();
|
||||
const heavy = pool.filter(c => c.cost >= 3).slice(0, 12);
|
||||
assert.match(deckWarning(heavy), /cost 2 or less/);
|
||||
assert.equal(deckWarning(starterDeck()), '');
|
||||
});
|
||||
|
||||
test('UI-driven random play always finishes within the turn cap and is deterministic', () => {
|
||||
for (let i = 0; i < 40; i++) {
|
||||
const a = playOut(`seed-${i}`), b = playOut(`seed-${i}`);
|
||||
assert.ok(engine.isOver(a), `match ${i} finished`);
|
||||
const ra = engine.result(a, 0);
|
||||
assert.ok(ra.turns <= DEFAULT_RULESET.turns, `match ${i}: ${JSON.stringify(ra)}`);
|
||||
assert.deepEqual(ra, engine.result(b, 0));
|
||||
const rb = engine.result(a, 1);
|
||||
assert.equal(rb.winner, ra.winner === null ? null : 1 - ra.winner, 'each side sees the other side of the same result');
|
||||
assert.deepEqual(rb.totalPower, [ra.totalPower[1], ra.totalPower[0]]);
|
||||
}
|
||||
});
|
||||
|
||||
test('my view never shows the opponent’s queued cards', () => {
|
||||
// Find a seed where the opponent has a turn-1 play (cost 1 in the opening hand).
|
||||
let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck('h0')], 'hidden-0');
|
||||
for (let i = 1; i < 50 && !engine.legal(s, 1).some(a => a.type === 'play'); i++)
|
||||
s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck(`h${i}`)], `hidden-${i}`);
|
||||
const play = engine.legal(s, 1).find(a => a.type === 'play');
|
||||
assert.ok(play, 'some seed gives the opponent a turn-1 play');
|
||||
s = engine.apply(s, 1, play!);
|
||||
const mine = engine.view(s, 0);
|
||||
assert.equal(mine.lanes.flatMap(l => [...l.theirs, ...l.staged]).length, 0);
|
||||
assert.equal(mine.oppQueued, 1);
|
||||
const theirs = engine.view(s, 1);
|
||||
assert.equal(theirs.lanes.flatMap(l => l.staged).length, 1);
|
||||
assert.ok(!theirs.hand.some(c => play!.type === 'play' && c.id === play!.cardId), 'a queued card leaves the visible hand');
|
||||
});
|
||||
|
||||
test('unstage refunds energy, and illegal plays are explained', () => {
|
||||
let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck('e')], 'energy');
|
||||
const v = engine.view(s, 0);
|
||||
const expensive = v.hand.find(c => c.cost > v.energy);
|
||||
if (expensive) assert.ok(engine.problem(s, 0, { type: 'play', cardId: expensive.id, lane: 0 }));
|
||||
const play = engine.legal(s, 0).find(a => a.type === 'play');
|
||||
if (play?.type === 'play') {
|
||||
s = engine.apply(s, 0, play);
|
||||
assert.ok(engine.view(s, 0).energy < v.energy);
|
||||
s = engine.apply(s, 0, { type: 'unstage', cardId: play.cardId });
|
||||
assert.equal(engine.view(s, 0).energy, v.energy);
|
||||
}
|
||||
});
|
||||
|
||||
test('an owned NFT maps to a sidegrade card that the engine accepts', () => {
|
||||
const block = { tokenId: 'ab'.repeat(32), powHash: '00'.repeat(32), article: { pageId: 42, title: 'Test', category: 'Space', image: undefined },
|
||||
statsSnapshot: { stats: { attention: 100, depth: 100, reach: 100 } } } as unknown as TestnetBlock;
|
||||
const card = cardFromBlock(block);
|
||||
assert.equal(card.source, 'nft');
|
||||
assert.ok(card.cost <= DEFAULT_RULESET.uncheckedCostCap, 'forged max stats are capped');
|
||||
assert.equal(card.basePower, DEFAULT_RULESET.powerByCost[card.cost]);
|
||||
const deck = [card, ...starterDeck().slice(1)];
|
||||
assert.equal(deckProblem(deck, DEFAULT_RULESET), '');
|
||||
});
|
||||
|
||||
test('peer mode lists are parsed defensively', () => {
|
||||
const modes = parseModeList({ host: { origin: 'http://192.168.1.32:3102', operator: 'node-b' }, modes: [
|
||||
{ mode: { id: 'trending', name: 'Trending', description: 'x'.repeat(1000), rules: { turns: 5 } }, stats: { playersOnline: 3, matchesPlayed: 9 } },
|
||||
{ mode: { id: 'bad', name: 'Bad rules', rules: { turns: 999 } } },
|
||||
{ mode: { name: 'no id' } }, 'junk', null,
|
||||
] }, { self: false, origin: 'http://192.168.1.32:3102' });
|
||||
assert.equal(modes.length, 1);
|
||||
const [m] = modes;
|
||||
assert.equal(m.host.kind === 'peer' && m.host.name, 'node-b');
|
||||
assert.equal(m.ruleset.turns, 5);
|
||||
assert.ok(m.description.length <= 280);
|
||||
assert.equal(m.players, 3);
|
||||
assert.deepEqual(parseModeList('nope', { self: true, origin: '' }), []);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user