forked from WikiDeck/wikideck
host-pvp: multi-engine host, owned-deck seats, invites, quick match, Elo, ?v= polling (#56)
- Mode schema wikideck.mode/2: required `engine` (editwar | duel); Night 1
wikideck.mode/1 documents are rejected with a clear message. Deck policies:
constructed (owned NFT token ids, minConfirmations), starter (Edit War only),
draft with source preview (Edit War only) or collections. limits.rated and
limits.accountsOnly.
- ModeHost runs every engine it is given, chosen per mode. Duel modes refuse
loaner policies at startup (BRIEF decision 1).
- Seats: eom.dev account via Dex ID token (body or JWT bearer on seat-creating
routes), player id sha256('acct:'+iss+'\n'+sub); guests only in Edit War.
- Constructed decks resolved through an injected OwnershipPort (#57), cards built
by the engine's fromChain; creator's deck re-resolved at join.
- Private lobbies + invite codes (GET /invites/:code, POST /invites/:code/join),
quick match (POST /modes/:id/quick), lobby state version with 204 on ?v=.
- Elo (1200, K 24) per mode for rated account-vs-account matches, recomputed
from matches.jsonl; records carry engine, rated, tokens. /modes/:id/ladder.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+18
-7
@@ -18,12 +18,13 @@ A mode is a JSON document, at most 8 KiB:
|
||||
|
||||
```json
|
||||
{
|
||||
"schema": "wikideck.mode/1",
|
||||
"schema": "wikideck.mode/2",
|
||||
"id": "trending",
|
||||
"version": 1,
|
||||
"name": "Trending",
|
||||
"description": "Live Wikipedia pageview trends power cards up or down.",
|
||||
"tags": ["live-data"],
|
||||
"engine": "editwar",
|
||||
"rules": { "trendUp": 25, "trendDown": -25 },
|
||||
"cards": { "preset": "trending", "percentPerPoint": 25, "maxBonus": 3, "penalise": true },
|
||||
"decks": { "kind": "starter" },
|
||||
@@ -33,12 +34,14 @@ A mode is a JSON document, at most 8 KiB:
|
||||
|
||||
| Field | Meaning |
|
||||
|---|---|
|
||||
| `schema` | `wikideck.mode/2`. Night 1 documents (`wikideck.mode/1`) are rejected with a message saying what to change. |
|
||||
| `engine` | Required: `editwar` (the Night 1 simultaneous-reveal game, `shared/game`) or `duel` (the Night 2 Magic-style duel, `shared/duel`). Duel modes only allow `constructed` and `draft` with `source: "collections"`: every card is one the players own. |
|
||||
| `id`, `version` | Lowercase slug and a version integer. Bump `version` whenever the rules change, so old match records and leaderboards stay attributable (`<origin>#<id>@<version>`). |
|
||||
| `name`, `description`, `tags` | Plain text only: no control characters or `<` `>`. |
|
||||
| `rules` | **Overrides** on top of the engine's `DEFAULT_RULESET` (see `docs/game/ENGINE_API.md`). Objects merge one level deep; arrays and numbers replace. The merged result then goes through the engine's strict `parseRuleset`, so the engine alone decides what's legal (bounded turns, Topics, deck sizes, known keywords and portals only; see DESIGN.md §9 for the keys). |
|
||||
| `cards` | A card-mapping **preset** from a fixed list. `standard` leaves cards as dealt. `live` freezes each card's live trend arrow (DESIGN §1.6, using the ruleset's `trendUp`/`trendDown`) at match start. `trending` does the same and also adds a bounded power bonus from the live pageview trend. The mode only picks a preset and tunes its bounded numbers. |
|
||||
| `decks` | `starter` (everyone gets a seeded starter deck), `draft` (snake draft from a host-seeded pool of preview cards) or `constructed` (bring your own; see "Not yet" below). |
|
||||
| `limits` | Concurrency and lobby expiry for this mode on this host. `turnSeconds` only applies to engines without their own turn timer; with tonight's engine, the ruleset's `turnSeconds` (plus 5 s network grace) is the timer. |
|
||||
| `decks` | `constructed` (each player submits exactly `deckSize` NFT token ids they own; the host verifies ownership and confirmations on the chain, `minConfirmations` default 1, and builds every card from its block), `starter` (Edit War only: a seeded starter deck) or `draft` (snake draft; `source: "preview"` uses preview cards, Edit War only; `source: "collections"` pools both players' owned cards for that match only, and both must own at least `deckSize`). |
|
||||
| `limits` | Concurrency and lobby expiry for this mode on this host. `rated: true` moves Elo (start 1200, K 24) when both seats are eom.dev accounts; `accountsOnly: true` refuses guest seats (owned-card modes always do). `turnSeconds` only applies to engines without their own turn timer; with tonight's engine, the ruleset's `turnSeconds` (plus 5 s network grace) is the timer. |
|
||||
|
||||
The schema is strict: unknown fields are rejected, as are prototype keys
|
||||
(`__proto__`, `constructor`, `prototype`) anywhere in the document, nesting deeper than two
|
||||
@@ -46,6 +49,15 @@ levels inside `rules`, more than 48 rule keys, and oversized strings and arrays.
|
||||
**never** evaluates, imports or runs anything another peer sends. Nothing in a mode can name
|
||||
a file, a URL, a script or a function.
|
||||
|
||||
### Seats, invites, quick match and polling (Night 2)
|
||||
|
||||
- **Seats:** `POST /modes/:id/lobbies`, `POST /lobbies/:id/join` and `POST /modes/:id/quick` take `{idToken, deck?, private?}` for an eom.dev account (the Dex ID token may also be sent as `Authorization: Bearer <jwt>`), or `{name, secret}` for a guest in Edit War modes. The reply is `{lobbyId, seat, token, invite, playerId}`; `token` is the seat bearer for every later call. Account player ids are `sha256("acct:" + iss + "\n" + sub)`.
|
||||
- **Invites:** every lobby gets a 12-character `invite` code. `private: true` hides it from `/lobbies` and quick match. `GET /invites/:code` describes it and `POST /invites/:code/join` joins it (SPA link: `/play/invite/<code>`).
|
||||
- **Quick match:** `POST /modes/:id/quick` joins the oldest open public lobby someone else opened (`matched: true`), or opens one (`matched: false`) to poll.
|
||||
- **Polling:** every lobby view has a `version`. `GET /lobbies/:id?v=<version>` answers **204** while nothing changed. Poll; never hold requests open (the node caps concurrent `/api` requests).
|
||||
- **Ladder:** `GET /modes/:id/ladder` (same as `/leaderboard`): entries carry `rating` (Elo, or null if unrated) plus W/L/D.
|
||||
- **Records:** `GET /matches/:id` has the seed, rules, both decks (as the engine cards), every action, `engine`, `rated`, and for constructed modes `tokens` (the NFT ids each seat played), so the recap can replay the match.
|
||||
|
||||
## 2. Running your own modes
|
||||
|
||||
Configure modes with environment variables on your node:
|
||||
@@ -255,10 +267,9 @@ be pinned in consensus.
|
||||
|
||||
## Not yet
|
||||
|
||||
- `constructed` decks of **owned NFTs**: the policy exists, but tonight the host deals
|
||||
starter decks for it. Playing with your own cards needs a wallet-signed ownership proof
|
||||
for the lobby (and then the engine's `cardFromStats`). That's a follow-up once accounts and
|
||||
wallet linking (#7) settle.
|
||||
- `constructed` decks of **owned NFTs** are verified on the hosting node only, against its
|
||||
own account store (Night 2). Playing them on a *peer* needs a wallet-signed deck claim,
|
||||
because accounts are per node; that's a follow-up.
|
||||
- `trending` never calls Wikipedia when a match starts. The node warms a cache-only trend
|
||||
store in the background, one page every 20 s (configurable, never faster than 15 s), through its existing enrichment cache (6 h TTL),
|
||||
starting with the preview-card pages. A card whose page isn't warm yet gets no bonus. This
|
||||
|
||||
@@ -40,4 +40,32 @@ export interface EnginePort<Rules = unknown, Card = unknown, State = unknown, Ac
|
||||
result(state: State): MatchOutcome;
|
||||
/** What one seat may see (hides the opponent's hand and staged plays). */
|
||||
viewFor(state: State, seat: Seat): unknown;
|
||||
/**
|
||||
* Build a match card from an owned NFT the ownership layer resolved from its block on the
|
||||
* chain. Required for constructed and collection-draft modes. Must be deterministic: the
|
||||
* same block gives the same card (derive once, freeze).
|
||||
*/
|
||||
fromChain?(rules: Rules, card: ChainCard): Card;
|
||||
/** Copies of one Wikipedia page allowed in a deck (MTG-style 4); default 4. */
|
||||
copyLimit?(rules: Rules): number;
|
||||
/** Optional per-seat match log (past tense, no hidden information), stored with the record. */
|
||||
logFor?(state: State, seat: Seat): unknown;
|
||||
}
|
||||
|
||||
/** One owned NFT as built by server/game/ownership.ts from its block (never from client JSON). */
|
||||
export type ChainCard = { tokenId: string; owner: string; confirmations: number; pageId: number; title: string; [k: string]: unknown };
|
||||
|
||||
/** An eom.dev (Dex) account, verified from an ID token. */
|
||||
export type SeatAccount = { sub: string; issuer: string; name: string; username?: string };
|
||||
|
||||
/**
|
||||
* What the host needs from server/game/ownership.ts (#57). Errors carry an HTTP `status`
|
||||
* (400/401/403) and a player-facing message; the host passes both through.
|
||||
*/
|
||||
export interface OwnershipPort {
|
||||
verifyAccount(idToken: unknown): Promise<SeatAccount>;
|
||||
resolveDeck(account: SeatAccount, tokenIds: unknown,
|
||||
opts: { deckSize: number; maxCopiesPerPage: number; minConfirmations: number }): Promise<ChainCard[]>;
|
||||
/** Every card the account owns across its linked wallets. */
|
||||
collection(account: SeatAccount): Promise<ChainCard[]>;
|
||||
}
|
||||
|
||||
+265
-69
@@ -2,15 +2,21 @@
|
||||
* Hosts lobbies and matches for this node's modes, with the deterministic engine.
|
||||
* All state is off-chain and in memory; finished matches go to the MatchStore.
|
||||
*
|
||||
* Trust model: the host is authoritative for its own matches. Players are identified by a
|
||||
* client-held secret (only its SHA-256 is stored or shown) and act through per-seat bearer
|
||||
* tokens. Every action must equal one of the engine's legalActions for that seat.
|
||||
* Trust model: the host is authoritative for its own matches. A seat is either an eom.dev
|
||||
* account (Dex ID token in the create/join body, verified server-side; player id
|
||||
* `sha256('acct:' + iss + '\n' + sub)`) or, in guest-friendly Edit War modes, a client-held
|
||||
* secret (only its SHA-256 is stored). Seats act through per-seat bearer tokens. Every
|
||||
* action must equal one of the engine's legalActions for that seat.
|
||||
*
|
||||
* Engines: each mode names its engine (`editwar` or `duel`); the host runs every engine it
|
||||
* was given. Constructed decks are NFT token ids the player owns, resolved from the chain by
|
||||
* the ownership port (server/game/ownership.ts) and turned into cards by the engine.
|
||||
*/
|
||||
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
|
||||
import { isDeepStrictEqual } from 'node:util';
|
||||
import { modeKey, resolveRuleset, trendBonus, clampPower, MODE_SCHEMA_VERSION,
|
||||
type HostIdentity, type ModeDocument, type ModeList, type ModeStats, type LiveCardData } from '../../shared/game/modes.ts';
|
||||
import type { EnginePort, Seat } from './engine-port.ts';
|
||||
import { modeKey, resolveRuleset, trendBonus, clampPower, requiresAccount, MODE_SCHEMA_VERSION,
|
||||
type EngineId, type HostIdentity, type ModeDocument, type ModeList, type ModeStats, type LiveCardData } from '../../shared/game/modes.ts';
|
||||
import type { ChainCard, EnginePort, OwnershipPort, Seat, SeatAccount } from './engine-port.ts';
|
||||
import { MatchStore, type MatchRecord } from './store.ts';
|
||||
|
||||
export class GameError extends Error {
|
||||
@@ -18,22 +24,40 @@ export class GameError extends Error {
|
||||
constructor(status: number, message: string) { super(message); this.status = status; }
|
||||
}
|
||||
|
||||
type Player = { id: string; name: string; tokenHash: Buffer; seen: number };
|
||||
type AnyEngine = EnginePort<any, any, any, any>;
|
||||
type Player = { id: string; name: string; tokenHash: Buffer; seen: number;
|
||||
/** Set for account seats: who to resolve the deck for. Never the ID token itself. */
|
||||
account?: SeatAccount;
|
||||
/** Constructed modes: the token ids this seat submitted (re-resolved at match start). */
|
||||
deckIds?: string[] };
|
||||
type Phase = 'waiting' | 'starting' | 'drafting' | 'playing' | 'finished' | 'expired';
|
||||
type Lobby = {
|
||||
id: string; mode: ModeDocument; rules: unknown; seed: string; createdAt: number;
|
||||
/** Bumped on every observable change, so unchanged polls (`?v=`) can return 204. */
|
||||
version: number;
|
||||
/** Private lobbies are hidden from lists and quick match; joined through the invite code. */
|
||||
private?: boolean; invite?: string;
|
||||
/** Rated (Elo) iff the mode is rated and both seats are accounts; decided at join. */
|
||||
rated?: boolean;
|
||||
/** Constructed modes: token ids per seat, for the record's references. */
|
||||
tokens?: [string[], string[]];
|
||||
players: Player[]; phase: Phase;
|
||||
draft?: { pool: unknown[]; taken: (Seat | null)[]; order: Seat[]; turn: number; deadline: number };
|
||||
decks?: [unknown[], unknown[]];
|
||||
state?: unknown; actions: { seat: Seat; action: unknown }[]; startedAt?: number; lastMove: number; turnStartedAt?: number; turn?: number;
|
||||
outcome?: { winner: Seat | null; reason: string }; matchId?: string;
|
||||
};
|
||||
type HostedMode = { mode: ModeDocument; rules: unknown };
|
||||
type HostedMode = { mode: ModeDocument; rules: unknown; engine: AnyEngine };
|
||||
|
||||
export type HostOptions = {
|
||||
identity: HostIdentity;
|
||||
modes: ModeDocument[];
|
||||
engine: EnginePort<any, any, any, any>;
|
||||
/** Engines by id. Every mode's `engine` must be present here. */
|
||||
engines?: Partial<Record<EngineId, AnyEngine>>;
|
||||
/** Shorthand for `engines: { editwar: engine }` (Night 1 callers and tests). */
|
||||
engine?: AnyEngine;
|
||||
/** Account verification and server-side ownership (#57). Without it, account seats are unavailable. */
|
||||
ownership?: OwnershipPort;
|
||||
store: MatchStore;
|
||||
/** Optional live Wikipedia trend lookup for `trending` modes. Failures mean "no bonus". */
|
||||
liveData?: (pageId: number) => Promise<LiveCardData | null>;
|
||||
@@ -42,16 +66,19 @@ export type HostOptions = {
|
||||
maxLobbies?: number;
|
||||
};
|
||||
|
||||
export type SeatTicket = { lobbyId: string; seat: Seat; token: string };
|
||||
export type SeatTicket = { lobbyId: string; seat: Seat; token: string; invite?: string; playerId: string };
|
||||
/** Body of create / join / quick match. `idToken` is a Dex ID token; `deck` is NFT token ids. */
|
||||
export type SeatRequest = { name?: unknown; secret?: unknown; idToken?: unknown; deck?: unknown; private?: unknown };
|
||||
|
||||
const NAME = /^[\p{L}\p{N} _.\-]{1,24}$/u;
|
||||
const SECRET = /^[A-Za-z0-9_-]{22,128}$/;
|
||||
const LOBBY_ID = /^[a-f0-9]{24}$/;
|
||||
const INVITE = /^[A-Za-z0-9_-]{12}$/;
|
||||
|
||||
export class ModeHost {
|
||||
readonly identity: HostIdentity;
|
||||
private readonly engine: EnginePort<any, any, any, any>;
|
||||
private readonly store: MatchStore;
|
||||
private readonly ownership?: OwnershipPort;
|
||||
private readonly hosted = new Map<string, HostedMode>();
|
||||
private readonly lobbies = new Map<string, Lobby>();
|
||||
private readonly liveData?: HostOptions['liveData'];
|
||||
@@ -60,24 +87,31 @@ export class ModeHost {
|
||||
|
||||
constructor(options: HostOptions) {
|
||||
this.identity = options.identity;
|
||||
this.engine = options.engine;
|
||||
this.store = options.store;
|
||||
this.ownership = options.ownership;
|
||||
const engines: Partial<Record<EngineId, AnyEngine>> = { ...(options.engine ? { editwar: options.engine } : {}), ...options.engines };
|
||||
this.liveData = options.liveData;
|
||||
this.now = options.now ?? Date.now;
|
||||
this.maxLobbies = options.maxLobbies ?? 512;
|
||||
for (const mode of options.modes) {
|
||||
if (this.hosted.has(mode.id)) throw new Error(`Duplicate mode id ${mode.id}`);
|
||||
const engine = engines[mode.engine];
|
||||
if (!engine) throw new Error(`Mode ${mode.id}: engine "${mode.engine}" is not available on this host`);
|
||||
// Validate rules once at startup with the engine's own parser: a bad mode fails loudly.
|
||||
const rules = resolveRuleset(this.engine.defaultRuleset, mode.rules, v => this.engine.parseRuleset(v));
|
||||
if (mode.decks.kind === 'draft' && mode.decks.poolSize < 2 * this.engine.deckSize(rules)) {
|
||||
const rules = resolveRuleset(engine.defaultRuleset, mode.rules, v => engine.parseRuleset(v));
|
||||
const loaners = mode.decks.kind === 'starter' || (mode.decks.kind === 'draft' && mode.decks.source === 'preview');
|
||||
// BRIEF decision 1: duel decks are only cards the players own. No starter, loaner or preview cards.
|
||||
if (mode.engine === 'duel' && loaners) throw new Error(`Mode ${mode.id}: duel modes use owned cards only (constructed, or a collections draft)`);
|
||||
if (mode.decks.kind === 'draft' && mode.decks.poolSize < 2 * engine.deckSize(rules)) {
|
||||
throw new Error(`Mode ${mode.id}: draft poolSize must be at least 2 × deck size`);
|
||||
}
|
||||
if (mode.decks.kind !== 'draft') {
|
||||
if (!loaners && !engine.fromChain) throw new Error(`Mode ${mode.id}: engine "${mode.engine}" cannot build cards from owned NFTs`);
|
||||
if (mode.decks.kind === 'starter') {
|
||||
// Host-dealt starter decks must be legal under the mode's rules, or the mode is unplayable.
|
||||
try { this.engine.validateDeck(rules, this.engine.starterDeck(rules, 'startup-check')); }
|
||||
try { engine.validateDeck(rules, engine.starterDeck(rules, 'startup-check')); }
|
||||
catch (e) { throw new Error(`Mode ${mode.id}: starter decks are illegal under its rules (${(e as Error).message.slice(0, 120)}); use a draft deck policy`); }
|
||||
}
|
||||
this.hosted.set(mode.id, { mode, rules });
|
||||
this.hosted.set(mode.id, { mode, rules, engine });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,61 +141,140 @@ export class ModeHost {
|
||||
|
||||
openLobbies(modeId: string) {
|
||||
this.mode(modeId);
|
||||
return [...this.lobbies.values()].filter(l => l.mode.id === modeId && l.phase === 'waiting')
|
||||
.slice(0, 50).map(l => ({ lobbyId: l.id, host: l.players[0]!.name, createdAt: l.createdAt }));
|
||||
return [...this.lobbies.values()].filter(l => l.mode.id === modeId && l.phase === 'waiting' && !l.private)
|
||||
.slice(0, 50).map(l => ({ lobbyId: l.id, host: l.players[0]!.name, createdAt: l.createdAt,
|
||||
hostId: l.players[0]!.id, account: !!l.players[0]!.account }));
|
||||
}
|
||||
|
||||
createLobby(modeId: string, player: { name: unknown; secret: unknown }): SeatTicket {
|
||||
/** Look up a private (or public) waiting lobby by its invite code: what an invite link shows. */
|
||||
invite(code: string) {
|
||||
this.sweep();
|
||||
const l = typeof code === 'string' && INVITE.test(code) ? [...this.lobbies.values()].find(x => x.invite === code) : undefined;
|
||||
if (!l) throw new GameError(404, 'Invite not found or expired.');
|
||||
return { lobbyId: l.id, phase: l.phase, open: l.phase === 'waiting', host: this.identity,
|
||||
mode: { id: l.mode.id, version: l.mode.version, name: l.mode.name, engine: l.mode.engine },
|
||||
createdBy: l.players[0]!.name, createdAt: l.createdAt, accountRequired: requiresAccount(l.mode) };
|
||||
}
|
||||
|
||||
async createLobby(modeId: string, request: SeatRequest): Promise<SeatTicket> {
|
||||
const h = this.mode(modeId);
|
||||
this.sweep();
|
||||
this.checkCapacity(h);
|
||||
const p = await this.seat(h, request);
|
||||
if (h.mode.decks.kind === 'constructed') await this.resolveDeck(h, p.player, request.deck);
|
||||
return this.openLobby(h, p, request.private === true);
|
||||
}
|
||||
|
||||
async join(lobbyId: string, request: SeatRequest): Promise<SeatTicket> {
|
||||
const l = this.lobby(lobbyId);
|
||||
this.sweep();
|
||||
if (l.phase !== 'waiting') throw new GameError(409, 'This lobby is no longer open.');
|
||||
const h = this.mode(l.mode.id);
|
||||
const p = await this.seat(h, request);
|
||||
const cards = h.mode.decks.kind === 'constructed' ? await this.resolveDeck(h, p.player, request.deck) : undefined;
|
||||
return this.seatInLobby(l, p, cards);
|
||||
}
|
||||
|
||||
/**
|
||||
* Quick match: join the oldest open public lobby of this mode that someone else opened,
|
||||
* else open a new public lobby and wait. No rating window (the ladder is small).
|
||||
*/
|
||||
async quickMatch(modeId: string, request: SeatRequest): Promise<SeatTicket & { matched: boolean }> {
|
||||
const h = this.mode(modeId);
|
||||
this.sweep();
|
||||
const p = await this.seat(h, request);
|
||||
const cards = h.mode.decks.kind === 'constructed' ? await this.resolveDeck(h, p.player, request.deck) : undefined;
|
||||
const candidates = [...this.lobbies.values()].filter(l => l.mode.id === modeId && l.phase === 'waiting' && !l.private &&
|
||||
l.players[0]!.id !== p.player.id).sort((a, b) => a.createdAt - b.createdAt);
|
||||
for (const l of candidates) {
|
||||
if (l.phase !== 'waiting') continue;
|
||||
return { ...await this.seatInLobby(l, p, cards), matched: true };
|
||||
}
|
||||
this.checkCapacity(h);
|
||||
return { ...this.openLobby(h, p, false), matched: false };
|
||||
}
|
||||
|
||||
/** The lobby's current state version (see `view`). */
|
||||
version(lobbyId: string): number { return this.lobby(lobbyId).version; }
|
||||
|
||||
private checkCapacity(h: HostedMode) {
|
||||
const active = [...this.lobbies.values()].filter(l => l.phase !== 'finished' && l.phase !== 'expired');
|
||||
if (active.length >= this.maxLobbies) throw new GameError(503, 'This host is full; try again later.');
|
||||
if (active.filter(l => l.mode.id === modeId).length >= h.mode.limits.maxConcurrentMatches) {
|
||||
if (active.filter(l => l.mode.id === h.mode.id).length >= h.mode.limits.maxConcurrentMatches) {
|
||||
throw new GameError(503, 'This mode is at its match limit on this host; try again later.');
|
||||
}
|
||||
const p = this.player(player);
|
||||
}
|
||||
|
||||
private openLobby(h: HostedMode, p: { player: Player; token: string }, isPrivate: boolean): SeatTicket {
|
||||
const active = [...this.lobbies.values()].filter(l => l.phase !== 'finished' && l.phase !== 'expired');
|
||||
if (active.filter(l => l.players.some(x => x.id === p.player.id)).length >= 3) {
|
||||
throw new GameError(429, 'Too many open lobbies or matches for this player.');
|
||||
}
|
||||
const id = randomBytes(12).toString('hex');
|
||||
const invite = randomBytes(9).toString('base64url');
|
||||
const now = this.now();
|
||||
this.lobbies.set(id, { id, mode: h.mode, rules: h.rules, seed: randomBytes(16).toString('hex'), createdAt: now,
|
||||
players: [p.player], phase: 'waiting', actions: [], lastMove: now });
|
||||
return { lobbyId: id, seat: 0, token: p.token };
|
||||
version: 1, private: isPrivate, invite, players: [p.player], phase: 'waiting', actions: [], lastMove: now });
|
||||
return { lobbyId: id, seat: 0, token: p.token, invite, playerId: p.player.id };
|
||||
}
|
||||
|
||||
async join(lobbyId: string, player: { name: unknown; secret: unknown }): Promise<SeatTicket> {
|
||||
const l = this.lobby(lobbyId);
|
||||
this.sweep();
|
||||
/** Seat a prepared player in a waiting lobby and start the draft or match. Synchronous until claimed. */
|
||||
private async seatInLobby(l: Lobby, p: { player: Player; token: string }, joinerCards?: ChainCard[]): Promise<SeatTicket> {
|
||||
// Re-check after the caller's awaits: another join may have claimed the lobby meanwhile.
|
||||
if (l.phase !== 'waiting') throw new GameError(409, 'This lobby is no longer open.');
|
||||
const p = this.player(player);
|
||||
if (l.players[0]!.id === p.player.id) throw new GameError(409, 'You cannot play against yourself.');
|
||||
const h = this.mode(l.mode.id);
|
||||
l.players.push(p.player);
|
||||
l.lastMove = this.now();
|
||||
// Claim the lobby before any await, so a concurrent join can't also pass the 'waiting' check.
|
||||
l.phase = 'starting';
|
||||
if (l.mode.decks.kind === 'draft') this.startDraft(l);
|
||||
else await this.startMatch(l, [this.engine.starterDeck(l.rules, `${l.seed}:0`), this.engine.starterDeck(l.rules, `${l.seed}:1`)]);
|
||||
return { lobbyId: l.id, seat: 1, token: p.token };
|
||||
l.rated = h.mode.limits.rated && l.players.every(x => x.account);
|
||||
this.bump(l);
|
||||
const policy = h.mode.decks;
|
||||
if (policy.kind === 'draft' && policy.source === 'collections') {
|
||||
const pools = await Promise.all(l.players.map(x => this.ownershipCall(() => this.ownership!.collection(x.account!))))
|
||||
.catch(e => { this.expire(l); throw e; });
|
||||
const size = h.engine.deckSize(l.rules);
|
||||
pools.forEach((c, seat) => { if (c.length < size) { this.expire(l);
|
||||
throw new GameError(409, `${seat === 0 ? 'The lobby host' : 'You'} own${seat === 0 ? 's' : ''} ${c.length} / ${size} cards: both players must be eligible to draft.`); } });
|
||||
const cards = seededShuffle([...pools[0]!, ...pools[1]!], `${l.seed}:pool`).slice(0, policy.poolSize)
|
||||
.map(c => h.engine.fromChain!(l.rules, c));
|
||||
this.startDraft(l, cards);
|
||||
} else if (policy.kind === 'draft') this.startDraft(l, h.engine.previewPool(l.rules, `${l.seed}:pool`, policy.poolSize));
|
||||
else if (policy.kind === 'constructed') {
|
||||
// The creator's cards may have moved since they opened the lobby: resolve them again.
|
||||
const creator = await this.resolveDeck(h, l.players[0]!, l.players[0]!.deckIds).catch(e => {
|
||||
this.expire(l); throw new GameError(409, `The lobby host's deck is no longer valid: ${(e as Error).message}`.slice(0, 200)); });
|
||||
const decks = [creator, joinerCards!];
|
||||
l.tokens = [decks[0]!.map(c => c.tokenId), decks[1]!.map(c => c.tokenId)];
|
||||
await this.startMatch(l, [decks[0]!.map(c => h.engine.fromChain!(l.rules, c)), decks[1]!.map(c => h.engine.fromChain!(l.rules, c))]);
|
||||
} else await this.startMatch(l, [h.engine.starterDeck(l.rules, `${l.seed}:0`), h.engine.starterDeck(l.rules, `${l.seed}:1`)]);
|
||||
return { lobbyId: l.id, seat: 1, token: p.token, invite: l.invite, playerId: p.player.id };
|
||||
}
|
||||
|
||||
/** Public status, plus the seat's private view when a valid token is given. */
|
||||
view(lobbyId: string, token?: string) {
|
||||
/**
|
||||
* Public status, plus the seat's private view when a valid token is given.
|
||||
* With `since` equal to the lobby's current version, returns null (the router sends 204).
|
||||
*/
|
||||
view(lobbyId: string, token?: string, since?: number) {
|
||||
const l = this.lobby(lobbyId);
|
||||
this.sweep();
|
||||
if (since !== undefined && since === l.version) return null;
|
||||
const engine = this.mode(l.mode.id).engine;
|
||||
const seat = token ? this.seatFor(l, token) : null;
|
||||
const base = { lobbyId: l.id, phase: l.phase, host: this.identity,
|
||||
mode: { id: l.mode.id, version: l.mode.version, name: l.mode.name },
|
||||
players: l.players.map(p => ({ id: p.id, name: p.name })), seat, matchId: l.matchId ?? null,
|
||||
const base = { lobbyId: l.id, version: l.version, phase: l.phase, host: this.identity,
|
||||
mode: { id: l.mode.id, version: l.mode.version, name: l.mode.name, engine: l.mode.engine },
|
||||
players: l.players.map(p => ({ id: p.id, name: p.name, account: !!p.account })), seat, matchId: l.matchId ?? null,
|
||||
rated: l.rated ?? false, private: l.private ?? false, invite: seat === 0 ? l.invite ?? null : undefined,
|
||||
outcome: l.outcome ?? null };
|
||||
if (l.phase === 'drafting' && l.draft) {
|
||||
const d = l.draft;
|
||||
return { ...base, draft: { pool: d.pool.map((c, i) => ({ index: i, card: this.engine.cardSummary(c), takenBy: d.taken[i] })),
|
||||
return { ...base, draft: { pool: d.pool.map((c, i) => ({ index: i, card: engine.cardSummary(c), takenBy: d.taken[i] })),
|
||||
toPick: d.order[d.turn] ?? null, deadline: d.deadline } };
|
||||
}
|
||||
if ((l.phase === 'playing' || l.phase === 'finished') && l.state !== undefined && seat !== null) {
|
||||
return { ...base, state: this.engine.viewFor(l.state, seat),
|
||||
legalActions: l.phase === 'playing' ? this.engine.legalActions(l.state, seat) : [] };
|
||||
return { ...base, state: engine.viewFor(l.state, seat),
|
||||
legalActions: l.phase === 'playing' ? engine.legalActions(l.state, seat) : [] };
|
||||
}
|
||||
return base;
|
||||
}
|
||||
@@ -184,7 +297,7 @@ export class ModeHost {
|
||||
this.sweep();
|
||||
if (l.phase !== 'playing' || l.state === undefined) throw new GameError(409, 'No match in progress.');
|
||||
// The host never trusts a client action: it must be one of the engine's legal actions.
|
||||
const legal = this.engine.legalActions(l.state, seat);
|
||||
const legal = this.mode(l.mode.id).engine.legalActions(l.state, seat);
|
||||
const chosen = legal.find(a => isDeepStrictEqual(a, action));
|
||||
if (chosen === undefined) throw new GameError(400, 'Illegal action.');
|
||||
this.apply(l, seat, chosen);
|
||||
@@ -195,10 +308,11 @@ export class ModeHost {
|
||||
resign(lobbyId: string, token: string) {
|
||||
const l = this.lobby(lobbyId);
|
||||
const seat = this.requireSeat(l, token);
|
||||
if (l.phase === 'waiting') { l.phase = 'expired'; return this.view(lobbyId, token); }
|
||||
if (l.phase === 'waiting') { this.expire(l); return this.view(lobbyId, token); }
|
||||
if (l.phase !== 'playing' && l.phase !== 'drafting') throw new GameError(409, 'Nothing to resign.');
|
||||
if (l.phase === 'playing' && l.state !== undefined && this.engine.concedeAction) {
|
||||
this.apply(l, seat, this.engine.concedeAction(seat), 'resign');
|
||||
const engine = this.mode(l.mode.id).engine;
|
||||
if (l.phase === 'playing' && l.state !== undefined && engine.concedeAction) {
|
||||
this.apply(l, seat, engine.concedeAction(seat), 'resign');
|
||||
if ((l.phase as Phase) === 'finished') return this.view(lobbyId, token);
|
||||
}
|
||||
this.finish(l, seat === 0 ? 1 : 0, 'resign');
|
||||
@@ -239,7 +353,11 @@ export class ModeHost {
|
||||
if (typeof raw.id !== 'string' || !LOBBY_ID.test(raw.id) || this.lobbies.has(raw.id)) continue;
|
||||
if (!['waiting', 'drafting', 'playing'].includes(raw.phase) || !Array.isArray(raw.players) || raw.players.length < 1 || raw.players.length > 2) continue;
|
||||
const lobby: Lobby = { ...raw, mode: h.mode, rules: h.rules,
|
||||
players: raw.players.map((p: any) => ({ id: String(p.id), name: String(p.name), seen: now, tokenHash: Buffer.from(String(p.tokenHash), 'hex') })),
|
||||
players: raw.players.map((p: any) => ({ id: String(p.id), name: String(p.name), seen: now, tokenHash: Buffer.from(String(p.tokenHash), 'hex'),
|
||||
...(p.account && typeof p.account.sub === 'string' && typeof p.account.issuer === 'string'
|
||||
? { account: { sub: p.account.sub, issuer: p.account.issuer, name: String(p.account.name ?? p.name) } } : {}),
|
||||
...(Array.isArray(p.deckIds) ? { deckIds: p.deckIds.map(String).slice(0, 64) } : {}) })),
|
||||
version: Number.isSafeInteger(raw.version) ? raw.version : 1,
|
||||
lastMove: now, createdAt: raw.phase === 'waiting' ? now : raw.createdAt, turnStartedAt: now };
|
||||
if (lobby.players.some(p => p.tokenHash.length !== 32)) continue;
|
||||
if (lobby.draft && lobby.mode.decks.kind === 'draft') lobby.draft.deadline = now + lobby.mode.decks.pickSeconds * 1000;
|
||||
@@ -255,16 +373,17 @@ export class ModeHost {
|
||||
sweep(): void {
|
||||
const now = this.now();
|
||||
for (const l of this.lobbies.values()) {
|
||||
if (l.phase === 'waiting' && now - l.createdAt > l.mode.limits.lobbyMinutes * 60_000) l.phase = 'expired';
|
||||
const engine = this.hosted.get(l.mode.id)!.engine;
|
||||
if (l.phase === 'waiting' && now - l.createdAt > l.mode.limits.lobbyMinutes * 60_000) this.expire(l);
|
||||
else if (l.phase === 'drafting' && l.draft && now > l.draft.deadline) {
|
||||
// Auto-pick the first free card for whoever is stalling; synchronous, no live data.
|
||||
const idx = l.draft.taken.indexOf(null);
|
||||
if (idx >= 0) void this.takePick(l, l.draft.order[l.draft.turn]!, idx).catch(() => { l.phase = 'expired'; });
|
||||
} else if (l.phase === 'playing' && l.state !== undefined && now - (l.turnStartedAt ?? l.lastMove) > this.turnMs(l)) {
|
||||
const waiting = ([0, 1] as Seat[]).filter(s => this.engine.legalActions(l.state, s).length > 0);
|
||||
if (this.engine.timeoutAction) {
|
||||
const waiting = ([0, 1] as Seat[]).filter(s => engine.legalActions(l.state, s).length > 0);
|
||||
if (engine.timeoutAction) {
|
||||
// The engine decides what a timeout means (auto-commit, AFK forfeit); it is logged and replayable.
|
||||
for (const s of waiting) if (l.phase === 'playing') this.apply(l, s, this.engine.timeoutAction(s));
|
||||
for (const s of waiting) if (l.phase === 'playing') this.apply(l, s, engine.timeoutAction(s));
|
||||
l.turnStartedAt = now;
|
||||
} else if (waiting.length === 1) this.finish(l, waiting[0] === 0 ? 1 : 0, 'timeout');
|
||||
else this.finish(l, null, 'abandoned');
|
||||
@@ -273,17 +392,17 @@ export class ModeHost {
|
||||
}
|
||||
}
|
||||
|
||||
private startDraft(l: Lobby) {
|
||||
private startDraft(l: Lobby, pool: unknown[]) {
|
||||
if (l.mode.decks.kind !== 'draft') return;
|
||||
const size = this.engine.deckSize(l.rules);
|
||||
const pool = this.engine.previewPool(l.rules, `${l.seed}:pool`, l.mode.decks.poolSize);
|
||||
if (pool.length < 2 * size) throw new GameError(500, 'Engine returned a short draft pool.');
|
||||
const size = this.mode(l.mode.id).engine.deckSize(l.rules);
|
||||
if (pool.length < 2 * size) { this.expire(l); throw new GameError(409, `The draft pool has only ${pool.length} cards; it needs ${2 * size}.`); }
|
||||
// Snake order 0,1,1,0,0,1,... with a seed-chosen first picker.
|
||||
const first: Seat = parseInt(l.seed.slice(0, 2), 16) % 2 === 0 ? 0 : 1;
|
||||
const order: Seat[] = [];
|
||||
for (let i = 0; i < 2 * size; i++) order.push(((Math.floor((i + 1) / 2) % 2 === 0 ? first : 1 - first)) as Seat);
|
||||
l.draft = { pool, taken: pool.map(() => null), order, turn: 0, deadline: this.now() + l.mode.decks.pickSeconds * 1000 };
|
||||
l.phase = 'drafting';
|
||||
this.bump(l);
|
||||
}
|
||||
|
||||
private async takePick(l: Lobby, seat: Seat, index: number) {
|
||||
@@ -291,6 +410,7 @@ export class ModeHost {
|
||||
d.taken[index] = seat;
|
||||
d.turn++;
|
||||
l.lastMove = this.now();
|
||||
this.bump(l);
|
||||
if (l.mode.decks.kind === 'draft') d.deadline = this.now() + l.mode.decks.pickSeconds * 1000;
|
||||
if (d.turn >= d.order.length) {
|
||||
const decks: [unknown[], unknown[]] = [[], []];
|
||||
@@ -300,34 +420,37 @@ export class ModeHost {
|
||||
}
|
||||
|
||||
private async startMatch(l: Lobby, decks: [unknown[], unknown[]]) {
|
||||
const engine = this.mode(l.mode.id).engine;
|
||||
const mapped = await Promise.all(decks.map(d => this.mapDeck(l.mode, d))) as [unknown[], unknown[]];
|
||||
for (const d of mapped) {
|
||||
try { this.engine.validateDeck(l.rules, d); }
|
||||
catch (e) { l.phase = 'expired'; throw new GameError(400, `Deck rejected by the engine: ${(e as Error).message}`.slice(0, 200)); }
|
||||
try { engine.validateDeck(l.rules, d); }
|
||||
catch (e) { this.expire(l); throw new GameError(400, `Deck rejected by the engine: ${(e as Error).message}`.slice(0, 200)); }
|
||||
}
|
||||
l.decks = mapped;
|
||||
l.state = this.engine.createMatch(l.rules, mapped, l.seed);
|
||||
l.state = engine.createMatch(l.rules, mapped, l.seed);
|
||||
l.phase = 'playing';
|
||||
l.startedAt = l.lastMove = l.turnStartedAt = this.now();
|
||||
l.turn = this.engine.turnOf?.(l.state);
|
||||
l.turn = engine.turnOf?.(l.state);
|
||||
delete l.draft;
|
||||
if (this.engine.isOver(l.state)) { const r = this.engine.result(l.state); this.finish(l, r.winner, r.reason ?? 'complete'); }
|
||||
this.bump(l);
|
||||
if (engine.isOver(l.state)) { const r = engine.result(l.state); this.finish(l, r.winner, r.reason ?? 'complete'); }
|
||||
}
|
||||
|
||||
/** Apply the mode's card-mapping preset. Bonus data is looked up once, before the match. */
|
||||
private async mapDeck(mode: ModeDocument, deck: unknown[]): Promise<unknown[]> {
|
||||
const mapping = mode.cards;
|
||||
if (mapping.preset === 'standard' || !this.liveData) return deck;
|
||||
const { engine, rules } = this.hosted.get(mode.id)!;
|
||||
return Promise.all(deck.map(async card => {
|
||||
const pageId = this.engine.cardPageId(card);
|
||||
const pageId = engine.cardPageId(card);
|
||||
if (pageId === null) return card;
|
||||
const live = await this.liveData!(pageId).catch(() => null);
|
||||
if (!live) return card;
|
||||
// `live` and `trending`: freeze the live trend arrow onto the card (engine rules decide its effect).
|
||||
let mapped = this.engine.applyLive ? this.engine.applyLive(this.hosted.get(mode.id)!.rules, card, live) : card;
|
||||
let mapped = engine.applyLive ? engine.applyLive(rules, card, live) : card;
|
||||
if (mapping.preset === 'trending') {
|
||||
const bonus = trendBonus(mapping, live.trendPercent);
|
||||
if (bonus !== 0) mapped = this.engine.withPower(mapped, clampPower(this.engine.cardPower(mapped) + bonus));
|
||||
if (bonus !== 0) mapped = engine.withPower(mapped, clampPower(engine.cardPower(mapped) + bonus));
|
||||
}
|
||||
return mapped;
|
||||
}));
|
||||
@@ -335,18 +458,20 @@ export class ModeHost {
|
||||
|
||||
/** Apply an action already known to be legal (or host-issued), log it, and settle the match if over. */
|
||||
private apply(l: Lobby, seat: Seat, action: unknown, reason?: string) {
|
||||
l.state = this.engine.applyAction(l.state, seat, action);
|
||||
const engine = this.mode(l.mode.id).engine;
|
||||
l.state = engine.applyAction(l.state, seat, action);
|
||||
l.actions.push({ seat, action });
|
||||
l.lastMove = this.now();
|
||||
const turn = this.engine.turnOf?.(l.state);
|
||||
this.bump(l);
|
||||
const turn = engine.turnOf?.(l.state);
|
||||
if (turn !== l.turn) { l.turn = turn; l.turnStartedAt = l.lastMove; }
|
||||
if (this.engine.isOver(l.state)) { const r = this.engine.result(l.state); this.finish(l, r.winner, reason ?? r.reason ?? 'complete'); }
|
||||
if (engine.isOver(l.state)) { const r = engine.result(l.state); this.finish(l, r.winner, reason ?? r.reason ?? 'complete'); }
|
||||
else if (l.actions.length >= 2000) this.finish(l, null, 'action-limit');
|
||||
}
|
||||
|
||||
/** Turn timer: the engine's own per-turn limit plus a little network grace, else the mode's limit. */
|
||||
private turnMs(l: Lobby): number {
|
||||
const engineSeconds = this.engine.turnSeconds?.(l.rules);
|
||||
const engineSeconds = this.mode(l.mode.id).engine.turnSeconds?.(l.rules);
|
||||
return engineSeconds !== undefined ? (engineSeconds + 5) * 1000 : l.mode.limits.turnSeconds * 1000;
|
||||
}
|
||||
|
||||
@@ -355,12 +480,63 @@ export class ModeHost {
|
||||
l.phase = 'finished';
|
||||
l.outcome = { winner, reason };
|
||||
l.lastMove = this.now();
|
||||
this.bump(l);
|
||||
if (!l.decks || l.players.length !== 2) return; // Resigned during draft: no match record.
|
||||
const matchId = randomBytes(16).toString('hex');
|
||||
l.matchId = matchId;
|
||||
this.store.add({ matchId, modeId: l.mode.id, modeVersion: l.mode.version, seed: l.seed, rules: l.rules,
|
||||
players: l.players.map(p => ({ id: p.id, name: p.name })), winner, reason: reason.slice(0, 40),
|
||||
startedAt: l.startedAt ?? l.createdAt, endedAt: l.lastMove, decks: l.decks, actions: l.actions });
|
||||
this.store.add({ matchId, modeId: l.mode.id, modeVersion: l.mode.version, engine: l.mode.engine, rated: l.rated ?? false,
|
||||
seed: l.seed, rules: l.rules,
|
||||
players: l.players.map(p => ({ id: p.id, name: p.name, account: !!p.account })), winner, reason: reason.slice(0, 40),
|
||||
startedAt: l.startedAt ?? l.createdAt, endedAt: l.lastMove, decks: l.decks, actions: l.actions,
|
||||
...(l.tokens ? { tokens: l.tokens } : {}) });
|
||||
}
|
||||
|
||||
private bump(l: Lobby) { l.version = (l.version ?? 0) + 1; }
|
||||
private expire(l: Lobby) {
|
||||
if (l.phase === 'finished' || l.phase === 'expired') return;
|
||||
l.phase = 'expired'; l.lastMove = this.now(); this.bump(l);
|
||||
}
|
||||
|
||||
/** Verify the seat: an eom.dev account (ID token) or, where the mode allows guests, a secret. */
|
||||
private async seat(h: HostedMode, input: SeatRequest): Promise<{ player: Player; token: string }> {
|
||||
const token = randomBytes(24).toString('base64url');
|
||||
if (input.idToken !== undefined && input.idToken !== null && input.idToken !== '') {
|
||||
if (!this.ownership) throw new GameError(503, 'eom.dev accounts are not available on this host.');
|
||||
const account = await this.ownershipCall(() => this.ownership!.verifyAccount(input.idToken));
|
||||
const id = createHash('sha256').update(`acct:${account.issuer}\n${account.sub}`).digest('hex');
|
||||
const name = displayName(account.name || account.username || '') ?? 'Player';
|
||||
return { player: { id, name, tokenHash: hashToken(token), seen: this.now(),
|
||||
account: { sub: account.sub, issuer: account.issuer, name } }, token };
|
||||
}
|
||||
if (requiresAccount(h.mode)) throw new GameError(401, 'This mode plays with cards you own: log in with your eom.dev account.');
|
||||
return this.player(input, token);
|
||||
}
|
||||
|
||||
/** Resolve a seat's submitted token ids to owned, confirmed chain cards (#57). */
|
||||
private async resolveDeck(h: HostedMode, p: Player, tokenIds: unknown): Promise<ChainCard[]> {
|
||||
if (h.mode.decks.kind !== 'constructed') return [];
|
||||
if (!this.ownership || !p.account) throw new GameError(401, 'Log in with your eom.dev account to play your own cards.');
|
||||
const deckSize = h.engine.deckSize(h.rules);
|
||||
if (!Array.isArray(tokenIds) || tokenIds.length !== deckSize || !tokenIds.every(t => typeof t === 'string' && t.length <= 128)) {
|
||||
throw new GameError(400, `A deck is exactly ${deckSize} card token ids you own.`);
|
||||
}
|
||||
const cards = await this.ownershipCall(() => this.ownership!.resolveDeck(p.account!, tokenIds,
|
||||
{ deckSize, maxCopiesPerPage: h.engine.copyLimit?.(h.rules) ?? 4, minConfirmations: h.mode.decks.kind === 'constructed' ? h.mode.decks.minConfirmations : 1 }));
|
||||
// Belt and braces: the ownership layer must hand back exactly the submitted tokens.
|
||||
if (cards.length !== deckSize || cards.some((c, i) => c.tokenId !== tokenIds[i])) throw new GameError(500, 'Ownership check returned a different deck.');
|
||||
p.deckIds = [...tokenIds as string[]];
|
||||
return cards;
|
||||
}
|
||||
|
||||
/** Pass player-facing ownership errors (status 4xx) through; anything else is a 503. */
|
||||
private async ownershipCall<T>(fn: () => Promise<T>): Promise<T> {
|
||||
try { return await fn(); }
|
||||
catch (e) {
|
||||
if (e instanceof GameError) throw e;
|
||||
const status = (e as { status?: unknown })?.status;
|
||||
if (typeof status === 'number' && status >= 400 && status < 500) throw new GameError(status, String((e as Error).message).slice(0, 200));
|
||||
throw new GameError(503, 'Could not check accounts or ownership right now; try again.');
|
||||
}
|
||||
}
|
||||
|
||||
private mode(modeId: string): HostedMode {
|
||||
@@ -373,12 +549,11 @@ export class ModeHost {
|
||||
if (!l) throw new GameError(404, 'Lobby not found.');
|
||||
return l;
|
||||
}
|
||||
private player(input: { name: unknown; secret: unknown }): { player: Player; token: string } {
|
||||
private player(input: SeatRequest, token: string): { player: Player; token: string } {
|
||||
const name = typeof input.name === 'string' ? input.name.trim() : '';
|
||||
if (!NAME.test(name)) throw new GameError(400, 'Name must be 1-24 letters, digits, spaces, _ . or -');
|
||||
if (typeof input.secret !== 'string' || !SECRET.test(input.secret)) throw new GameError(400, 'Invalid player secret.');
|
||||
const id = createHash('sha256').update(`wikideck-player:${input.secret}`).digest('hex');
|
||||
const token = randomBytes(24).toString('base64url');
|
||||
return { player: { id, name, tokenHash: hashToken(token), seen: this.now() }, token };
|
||||
}
|
||||
private seatFor(l: Lobby, token: string): Seat | null {
|
||||
@@ -394,3 +569,24 @@ export class ModeHost {
|
||||
}
|
||||
|
||||
function hashToken(token: string): Buffer { return createHash('sha256').update(token).digest(); }
|
||||
|
||||
/** An account display name reduced to the lobby name alphabet; null if nothing is left. */
|
||||
function displayName(raw: string): string | null {
|
||||
const cleaned = raw.normalize('NFC').replace(/[^\p{L}\p{N} _.\-]/gu, '').replace(/\s+/g, ' ').trim().slice(0, 24).trim();
|
||||
return NAME.test(cleaned) ? cleaned : null;
|
||||
}
|
||||
|
||||
/** Deterministic Fisher-Yates from a seed (SHA-256 counter stream): replayable draft pools. */
|
||||
export function seededShuffle<T>(items: T[], seed: string): T[] {
|
||||
const out = [...items];
|
||||
let counter = 0, buf = Buffer.alloc(0), off = 0;
|
||||
const next32 = () => {
|
||||
if (off + 4 > buf.length) { buf = createHash('sha256').update(`${seed}:${counter++}`).digest(); off = 0; }
|
||||
const v = buf.readUInt32BE(off); off += 4; return v;
|
||||
};
|
||||
for (let i = out.length - 1; i > 0; i--) {
|
||||
const j = next32() % (i + 1);
|
||||
[out[i], out[j]] = [out[j]!, out[i]!];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
+11
-3
@@ -10,15 +10,23 @@ import { ModeDiscovery } from './discovery.ts';
|
||||
import { ModeHost } from './host.ts';
|
||||
import { createGameRouter } from './router.ts';
|
||||
import { MatchStore } from './store.ts';
|
||||
import type { EnginePort } from './engine-port.ts';
|
||||
import type { EnginePort, OwnershipPort } from './engine-port.ts';
|
||||
import type { EngineId } from '../../shared/game/modes.ts';
|
||||
import { TrendCache } from './trends.ts';
|
||||
|
||||
type Enrichment = { get(pageId: number): Promise<{ pageviews: { trendPercent: number | null } }> };
|
||||
|
||||
export async function gameRouter(options: { dataDir: string | null; enrichment?: Enrichment;
|
||||
engine?: EnginePort<any, any, any, any>; env?: NodeJS.ProcessEnv; warmTrends?: boolean; handleSignals?: boolean }): Promise<express.Router> {
|
||||
/** The Edit War engine (default: the real binding). */
|
||||
engine?: EnginePort<any, any, any, any>;
|
||||
/** Extra engines by id, e.g. `{ duel }` (tests inject stubs). */
|
||||
engines?: Partial<Record<EngineId, EnginePort<any, any, any, any>>>;
|
||||
/** Account verification + server-side ownership, adapted from server/game/ownership.ts (#57). */
|
||||
ownershipPort?: OwnershipPort;
|
||||
env?: NodeJS.ProcessEnv; warmTrends?: boolean; handleSignals?: boolean }): Promise<express.Router> {
|
||||
const env = options.env ?? process.env;
|
||||
const engine = options.engine ?? (await import('./engine-binding.ts')).engineBinding;
|
||||
const engines = { editwar: engine, ...options.engines };
|
||||
const modes = loadModes(env);
|
||||
// Trends come from a slowly warmed, cache-only store: never a Wikipedia call per match.
|
||||
let trends: TrendCache | undefined;
|
||||
@@ -36,7 +44,7 @@ export async function gameRouter(options: { dataDir: string | null; enrichment?:
|
||||
}
|
||||
if (options.warmTrends !== false) trends.start();
|
||||
}
|
||||
const host = new ModeHost({ identity: hostIdentity(env), modes, engine,
|
||||
const host = new ModeHost({ identity: hostIdentity(env), modes, engines, ownership: options.ownershipPort,
|
||||
store: new MatchStore(options.dataDir ? join(options.dataDir, 'game') : null),
|
||||
liveData: trends ? async pageId => trends!.get(pageId) : undefined });
|
||||
const discovery = new ModeDiscovery({ peers: gamePeers(env) });
|
||||
|
||||
@@ -1,12 +1,24 @@
|
||||
{
|
||||
"schema": "wikideck.mode/1",
|
||||
"schema": "wikideck.mode/2",
|
||||
"id": "classic",
|
||||
"version": 1,
|
||||
"name": "Classic",
|
||||
"description": "The base WikiDeck rules with starter decks. Cards use their at-mint snapshot stats.",
|
||||
"tags": ["base", "starter"],
|
||||
"tags": [
|
||||
"base",
|
||||
"starter"
|
||||
],
|
||||
"engine": "editwar",
|
||||
"rules": {},
|
||||
"cards": { "preset": "standard" },
|
||||
"decks": { "kind": "starter" },
|
||||
"limits": { "maxConcurrentMatches": 32, "turnSeconds": 90, "lobbyMinutes": 15 }
|
||||
"cards": {
|
||||
"preset": "standard"
|
||||
},
|
||||
"decks": {
|
||||
"kind": "starter"
|
||||
},
|
||||
"limits": {
|
||||
"maxConcurrentMatches": 32,
|
||||
"turnSeconds": 90,
|
||||
"lobbyMinutes": 15
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"schema": "wikideck.mode/1",
|
||||
"schema": "wikideck.mode/2",
|
||||
"id": "draft",
|
||||
"version": 1,
|
||||
"name": "Snake Draft",
|
||||
@@ -8,6 +8,7 @@
|
||||
"draft",
|
||||
"no-collection"
|
||||
],
|
||||
"engine": "editwar",
|
||||
"rules": {
|
||||
"deckSize": 10,
|
||||
"openingHand": 4
|
||||
@@ -17,6 +18,7 @@
|
||||
},
|
||||
"decks": {
|
||||
"kind": "draft",
|
||||
"source": "preview",
|
||||
"poolSize": 30,
|
||||
"pickSeconds": 30
|
||||
},
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"schema": "wikideck.mode/1",
|
||||
"schema": "wikideck.mode/2",
|
||||
"id": "trending",
|
||||
"version": 1,
|
||||
"name": "Trending",
|
||||
@@ -8,6 +8,7 @@
|
||||
"live-data",
|
||||
"starter"
|
||||
],
|
||||
"engine": "editwar",
|
||||
"rules": {
|
||||
"trendUp": 25,
|
||||
"trendDown": -25
|
||||
|
||||
+27
-6
@@ -40,17 +40,38 @@ export function createGameRouter(host: ModeHost, discovery: ModeDiscovery): expr
|
||||
return { hosts: rows };
|
||||
}));
|
||||
r.get('/modes/:modeId/leaderboard', reads, wrap(req => host.leaderboard(String(req.params.modeId))));
|
||||
// Same body; entries carry `rating` (Elo, null if unrated) plus W/L.
|
||||
r.get('/modes/:modeId/ladder', reads, wrap(req => host.leaderboard(String(req.params.modeId))));
|
||||
r.get('/modes/:modeId/lobbies', reads, wrap(req => ({ lobbies: host.openLobbies(String(req.params.modeId)) })));
|
||||
r.post('/modes/:modeId/lobbies', writes, wrap((req, res) => {
|
||||
// Seat bodies: `{name, secret}` for guests (Edit War only), or `{idToken}` for an eom.dev account
|
||||
// (the Dex ID token travels in the body: Authorization carries seat tokens). Constructed
|
||||
// modes add `deck: tokenId[]`; `private: true` hides the lobby (join it by invite code).
|
||||
const seat = (req: Request) => {
|
||||
const b = body(req);
|
||||
// Also accept the Dex ID token as `Authorization: Bearer <jwt>` on seat-creating routes: a
|
||||
// JWT (three dot-separated parts) can never match the seat-token format above.
|
||||
const m = /^Bearer ([A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)$/.exec(req.get('authorization') ?? '');
|
||||
return { name: b.name, secret: b.secret, idToken: b.idToken ?? m?.[1], deck: b.deck, private: b.private };
|
||||
};
|
||||
r.post('/modes/:modeId/lobbies', writes, wrap(async (req, res) => {
|
||||
const ticket = await host.createLobby(String(req.params.modeId), seat(req));
|
||||
res.status(201);
|
||||
return host.createLobby(String(req.params.modeId), { name: b.name, secret: b.secret });
|
||||
return ticket;
|
||||
}));
|
||||
r.post('/lobbies/:lobbyId/join', writes, wrap(req => {
|
||||
const b = body(req);
|
||||
return host.join(String(req.params.lobbyId), { name: b.name, secret: b.secret });
|
||||
// Quick match: join the oldest open public lobby, else open one (`matched: false`) and poll it.
|
||||
r.post('/modes/:modeId/quick', writes, wrap(req => host.quickMatch(String(req.params.modeId), seat(req))));
|
||||
r.post('/lobbies/:lobbyId/join', writes, wrap(req => host.join(String(req.params.lobbyId), seat(req))));
|
||||
// Invite links (/play/invite/<code> in the SPA) resolve here, then join by lobby id or code.
|
||||
r.get('/invites/:code', reads, wrap(req => host.invite(String(req.params.code))));
|
||||
r.post('/invites/:code/join', writes, wrap(req => host.join(host.invite(String(req.params.code)).lobbyId, seat(req))));
|
||||
// Polling: `?v=<version>` from the last response returns 204 while nothing changed.
|
||||
r.get('/lobbies/:lobbyId', plays, wrap((req, res) => {
|
||||
const raw = typeof req.query.v === 'string' ? req.query.v : undefined;
|
||||
const since = raw !== undefined && /^\d{1,15}$/.test(raw) ? Number(raw) : undefined;
|
||||
const out = host.view(String(req.params.lobbyId), bearer(req) || undefined, since);
|
||||
if (out === null) { res.status(204).end(); return; }
|
||||
return out;
|
||||
}));
|
||||
r.get('/lobbies/:lobbyId', plays, wrap(req => host.view(String(req.params.lobbyId), bearer(req) || undefined)));
|
||||
r.post('/lobbies/:lobbyId/pick', plays, wrap(req => host.pick(String(req.params.lobbyId), bearer(req), body(req).index)));
|
||||
r.post('/lobbies/:lobbyId/actions', plays, wrap(req => host.act(String(req.params.lobbyId), bearer(req), body(req).action)));
|
||||
r.post('/lobbies/:lobbyId/resign', writes, wrap(req => host.resign(String(req.params.lobbyId), bearer(req))));
|
||||
|
||||
+36
-6
@@ -10,21 +10,42 @@ export const MatchRecordSchema = z.object({
|
||||
matchId: z.string().regex(/^[a-f0-9]{32}$/),
|
||||
modeId: z.string().max(40),
|
||||
modeVersion: z.number().int(),
|
||||
/** Engine the match ran on (absent in Night 1 records: `editwar`). */
|
||||
engine: z.enum(['editwar', 'duel']).optional(),
|
||||
/** Counted for Elo: the mode was rated and both seats were eom.dev accounts. */
|
||||
rated: z.boolean().optional(),
|
||||
/** Host-chosen seed. Together with decks and actions it lets anyone replay the match. */
|
||||
seed: z.string().max(128),
|
||||
/** The resolved ruleset the match ran under (mode overrides already applied). */
|
||||
rules: z.unknown(),
|
||||
players: z.array(z.object({ id: z.string().regex(/^[a-f0-9]{64}$/), name: z.string().max(24) }).strict()).length(2),
|
||||
players: z.array(z.object({ id: z.string().regex(/^[a-f0-9]{64}$/), name: z.string().max(24),
|
||||
account: z.boolean().optional() }).strict()).length(2),
|
||||
winner: z.union([z.literal(0), z.literal(1), z.null()]),
|
||||
reason: z.string().max(40),
|
||||
startedAt: z.number().int(),
|
||||
endedAt: z.number().int(),
|
||||
decks: z.array(z.array(z.unknown()).max(64)).length(2),
|
||||
actions: z.array(z.object({ seat: z.union([z.literal(0), z.literal(1)]), action: z.unknown() }).strict()).max(2000),
|
||||
/** Constructed modes: the NFT token ids each seat played, in deck order (recap references). */
|
||||
tokens: z.array(z.array(z.string().max(128)).max(64)).length(2).optional(),
|
||||
}).strict();
|
||||
export type MatchRecord = z.infer<typeof MatchRecordSchema>;
|
||||
|
||||
export type LeaderboardEntry = { playerId: string; name: string; wins: number; losses: number; draws: number; played: number };
|
||||
export type LeaderboardEntry = { playerId: string; name: string; wins: number; losses: number; draws: number; played: number;
|
||||
/** Elo (start 1200, K 24) from rated matches; null if the player has none in this mode. */
|
||||
rating: number | null; ratedPlayed: number };
|
||||
|
||||
/** Elo constants (engineer review §3). Ratings are recomputed by replaying records in order. */
|
||||
export const ELO_START = 1200;
|
||||
export const ELO_K = 24;
|
||||
|
||||
/** New ratings for [seat0, seat1] after one game; winner null is a draw. */
|
||||
export function eloUpdate(r0: number, r1: number, winner: 0 | 1 | null): [number, number] {
|
||||
const e0 = 1 / (1 + 10 ** ((r1 - r0) / 400));
|
||||
const s0 = winner === null ? 0.5 : winner === 0 ? 1 : 0;
|
||||
const d = ELO_K * (s0 - e0);
|
||||
return [r0 + d, r1 - d];
|
||||
}
|
||||
type ModeAgg = { matches: number; players: Map<string, LeaderboardEntry> };
|
||||
|
||||
const KEEP_RECENT = 500;
|
||||
@@ -63,8 +84,10 @@ export class MatchStore {
|
||||
|
||||
leaderboard(modeId: string, limit = 20): LeaderboardEntry[] {
|
||||
const players = [...(this.modes.get(modeId)?.players.values() ?? [])];
|
||||
return players.sort((a, b) => b.wins - a.wins || a.losses - b.losses || b.played - a.played ||
|
||||
a.playerId.localeCompare(b.playerId)).slice(0, limit).map(p => ({ ...p }));
|
||||
// Rated players first, by Elo; then everyone else by W/L (the cut-order fallback).
|
||||
return players.sort((a, b) => (b.rating ?? -Infinity) - (a.rating ?? -Infinity) || b.wins - a.wins || a.losses - b.losses ||
|
||||
b.played - a.played || a.playerId.localeCompare(b.playerId)).slice(0, limit)
|
||||
.map(p => ({ ...p, rating: p.rating === null ? null : Math.round(p.rating) }));
|
||||
}
|
||||
|
||||
private index(r: MatchRecord): void {
|
||||
@@ -72,13 +95,20 @@ export class MatchStore {
|
||||
const agg = this.modes.get(r.modeId) ?? { matches: 0, players: new Map() };
|
||||
this.modes.set(r.modeId, agg);
|
||||
agg.matches++;
|
||||
r.players.forEach((p, seat) => {
|
||||
const entries = r.players.map((p, seat) => {
|
||||
this.allPlayers.add(p.id);
|
||||
const e = agg.players.get(p.id) ?? { playerId: p.id, name: p.name, wins: 0, losses: 0, draws: 0, played: 0 };
|
||||
const e = agg.players.get(p.id) ?? { playerId: p.id, name: p.name, wins: 0, losses: 0, draws: 0, played: 0, rating: null, ratedPlayed: 0 };
|
||||
e.name = p.name; e.played++;
|
||||
if (r.winner === null) e.draws++; else if (r.winner === seat) e.wins++; else e.losses++;
|
||||
agg.players.set(p.id, e);
|
||||
return e;
|
||||
});
|
||||
// Elo only for rated matches between two account seats that actually played (no aborted 0-action games).
|
||||
if (r.rated && r.players.every(p => p.account) && r.actions.length > 0 && r.reason !== 'abandoned') {
|
||||
const [a, b] = entries as [LeaderboardEntry, LeaderboardEntry];
|
||||
[a.rating, b.rating] = eloUpdate(a.rating ?? ELO_START, b.rating ?? ELO_START, r.winner);
|
||||
a.ratedPlayed++; b.ratedPlayed++;
|
||||
}
|
||||
this.recent.set(r.matchId, r);
|
||||
if (this.recent.size > KEEP_RECENT) this.recent.delete(this.recent.keys().next().value!);
|
||||
}
|
||||
|
||||
+45
-8
@@ -11,7 +11,17 @@
|
||||
*/
|
||||
import { z } from 'zod';
|
||||
|
||||
export const MODE_SCHEMA_VERSION = 'wikideck.mode/1' as const;
|
||||
export const MODE_SCHEMA_VERSION = 'wikideck.mode/2' as const;
|
||||
/** Night 1 schema: rejected with a clear message (BRIEF "Modes": versioned schema). */
|
||||
export const LEGACY_MODE_SCHEMA_VERSIONS: readonly string[] = ['wikideck.mode/1'];
|
||||
/**
|
||||
* Which rules engine a mode runs on. `editwar` is the Night 1 simultaneous-reveal game
|
||||
* (shared/game); `duel` is the Night 2 Magic-style duel (shared/duel). A host may not
|
||||
* register every engine; modes for an engine it lacks fail at startup.
|
||||
*/
|
||||
export const ENGINE_IDS = ['editwar', 'duel'] as const;
|
||||
export const EngineIdSchema = z.enum(ENGINE_IDS);
|
||||
export type EngineId = z.infer<typeof EngineIdSchema>;
|
||||
/** Upper bound on the JSON size of one mode document, before parsing. */
|
||||
export const MAX_MODE_BYTES = 8 * 1024;
|
||||
/** Upper bound on modes one node may publish (and that discovery accepts from one peer). */
|
||||
@@ -60,14 +70,25 @@ export type CardMapping = z.infer<typeof CardMappingSchema>;
|
||||
|
||||
/** Where match decks come from. Matches never move or burn NFTs, whatever the policy. */
|
||||
export const DeckPolicySchema = z.discriminatedUnion('kind', [
|
||||
/** Each player brings a deck (starter deck or own cards, validated by the engine). */
|
||||
z.object({ kind: z.literal('constructed'), allowStarter: z.boolean().default(true) }).strict(),
|
||||
/** Host-seeded starter decks only: everyone gets the engine's `starterDeck(seed)`. */
|
||||
/**
|
||||
* Each player brings exactly `deckSize` NFTs they own (token ids), verified server-side
|
||||
* against the chain and built from their blocks. Requires an eom.dev account seat.
|
||||
*/
|
||||
z.object({ kind: z.literal('constructed'),
|
||||
/** Confirmations each card's mint (or last transfer) needs; rated modes should use ≥ 3. */
|
||||
minConfirmations: z.number().int().min(0).max(100).default(1),
|
||||
}).strict(),
|
||||
/** Host-seeded starter decks only (Edit War engine only: the duel has no loaners). */
|
||||
z.object({ kind: z.literal('starter') }).strict(),
|
||||
/** Snake draft from a host-seeded pool of non-NFT preview cards. */
|
||||
/** Snake draft from a host-seeded pool. */
|
||||
z.object({ kind: z.literal('draft'),
|
||||
/**
|
||||
* `preview`: the engine's non-NFT preview cards (Edit War only).
|
||||
* `collections`: both players' owned cards, used for this match only; nothing moves on-chain.
|
||||
*/
|
||||
source: z.enum(['preview', 'collections']).default('preview'),
|
||||
/** Cards in the shared pool; must be at least 2 × the ruleset's deck size. */
|
||||
poolSize: z.number().int().min(8).max(64).default(30),
|
||||
poolSize: z.number().int().min(8).max(200).default(30),
|
||||
/** Seconds per pick before the host auto-picks the first card. */
|
||||
pickSeconds: z.number().int().min(5).max(120).default(30),
|
||||
}).strict(),
|
||||
@@ -81,6 +102,10 @@ export const ModeLimitsSchema = z.object({
|
||||
turnSeconds: z.number().int().min(10).max(600).default(90),
|
||||
/** Lobbies with no opponent expire after this many minutes. */
|
||||
lobbyMinutes: z.number().int().min(1).max(120).default(15),
|
||||
/** Ranked: Elo moves only when both seats are eom.dev accounts. */
|
||||
rated: z.boolean().default(false),
|
||||
/** Seats must be eom.dev accounts (always true for constructed and collection-draft modes). */
|
||||
accountsOnly: z.boolean().default(false),
|
||||
}).strict();
|
||||
export type ModeLimits = z.infer<typeof ModeLimitsSchema>;
|
||||
|
||||
@@ -93,11 +118,13 @@ export const ModeSchema = z.object({
|
||||
name: text(48),
|
||||
description: text(400),
|
||||
tags: z.array(slug).max(5).default([]),
|
||||
/** The rules engine this mode runs on. Required: there is no safe default across engines. */
|
||||
engine: EngineIdSchema,
|
||||
/** Overrides on top of the engine's DEFAULT_RULESET. */
|
||||
rules: RuleOverridesSchema.default({}),
|
||||
cards: CardMappingSchema.default({ preset: 'standard' }),
|
||||
decks: DeckPolicySchema.default({ kind: 'constructed', allowStarter: true }),
|
||||
limits: ModeLimitsSchema.default({ maxConcurrentMatches: 32, turnSeconds: 90, lobbyMinutes: 15 }),
|
||||
decks: DeckPolicySchema.default({ kind: 'constructed', minConfirmations: 1 }),
|
||||
limits: ModeLimitsSchema.default({ maxConcurrentMatches: 32, turnSeconds: 90, lobbyMinutes: 15, rated: false, accountsOnly: false }),
|
||||
}).strict();
|
||||
export type ModeDocument = z.infer<typeof ModeSchema>;
|
||||
export type ModeInput = z.input<typeof ModeSchema>;
|
||||
@@ -145,6 +172,10 @@ export function parseModeJson(json: string): ModeDocument {
|
||||
}
|
||||
export function parseMode(value: unknown): ModeDocument {
|
||||
assertInertKeys(value);
|
||||
const schema = (value as { schema?: unknown } | null)?.schema;
|
||||
if (typeof schema === 'string' && LEGACY_MODE_SCHEMA_VERSIONS.includes(schema)) {
|
||||
throw new Error(`Mode schema ${schema} (Night 1) is no longer accepted: use ${MODE_SCHEMA_VERSION} with an "engine" field (see docs/game/HOSTING.md)`);
|
||||
}
|
||||
const mode = ModeSchema.parse(value);
|
||||
if (byteLength(JSON.stringify(mode)) > MAX_MODE_BYTES) throw new Error(`Mode document exceeds ${MAX_MODE_BYTES} bytes`);
|
||||
return mode;
|
||||
@@ -163,6 +194,12 @@ export function parseModeList(json: string): { list: ModeList; rejected: number
|
||||
return { list: ModeListSchema.parse({ ...raw, modes }), rejected };
|
||||
}
|
||||
|
||||
/** Whether a mode's seats must be eom.dev accounts (owned cards always need one). */
|
||||
export function requiresAccount(mode: ModeDocument): boolean {
|
||||
return mode.limits.accountsOnly || mode.decks.kind === 'constructed' ||
|
||||
(mode.decks.kind === 'draft' && mode.decks.source === 'collections');
|
||||
}
|
||||
|
||||
/** Stable key for a mode on a host: `<origin>#<id>@<version>`. */
|
||||
export function modeKey(origin: string, mode: Pick<ModeDocument, 'id' | 'version'>): string {
|
||||
return `${origin}#${mode.id}@${mode.version}`;
|
||||
|
||||
@@ -0,0 +1,328 @@
|
||||
// host-pvp (#56): multi-engine host, account seats, constructed owned decks, invites, quick
|
||||
// match, Elo and `?v=` polling. Stub engine + fake ownership port: zero network calls.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtempSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import express from 'express';
|
||||
import { parseMode, MODE_SCHEMA_VERSION } from '../shared/game/modes.ts';
|
||||
import { ModeHost, GameError, seededShuffle } from '../server/game/host.ts';
|
||||
import { MatchStore, eloUpdate, ELO_START } from '../server/game/store.ts';
|
||||
import { ModeDiscovery } from '../server/game/discovery.ts';
|
||||
import { createGameRouter } from '../server/game/router.ts';
|
||||
import type { ChainCard, EnginePort, OwnershipPort, SeatAccount } from '../server/game/engine-port.ts';
|
||||
import { stubEngine, type StubCard } from './modes-stub-engine.ts';
|
||||
|
||||
const DECK = 6; // stand-in for the duel's 40, to keep the stub small
|
||||
const identity = { origin: 'http://node-a.test', operator: 'Alice' };
|
||||
|
||||
/** The stub engine, registered as `duel`, that can build cards from owned NFTs. */
|
||||
const duelStub: EnginePort<any, StubCard, any, any> = {
|
||||
...stubEngine,
|
||||
defaultRuleset: { deckSize: DECK, turns: 3, scoring: { tieBreak: 'first' } },
|
||||
fromChain: (_rules, c: ChainCard) => ({ id: c.tokenId, pageId: c.pageId, power: (c.pageId % 9) + 1 }),
|
||||
copyLimit: () => 4,
|
||||
};
|
||||
|
||||
const duelMode = (over: object = {}) => parseMode({ schema: MODE_SCHEMA_VERSION, engine: 'duel', id: 'duel-classic', version: 1,
|
||||
name: 'Duel', description: 'Constructed duel.', decks: { kind: 'constructed', minConfirmations: 1 },
|
||||
limits: { rated: true }, ...over });
|
||||
|
||||
class OwnershipError extends Error { readonly status: number; constructor(status: number, m: string) { super(m); this.status = status; } }
|
||||
|
||||
/** In-memory accounts + ledger: tokens `<who>-<n>` belong to `<who>`. */
|
||||
function fakeOwnership() {
|
||||
const accounts: Record<string, SeatAccount> = {
|
||||
'id-alice': { sub: 'alice', issuer: 'https://dex.test', name: 'Alice Example' },
|
||||
'id-bob': { sub: 'bob', issuer: 'https://dex.test', name: 'Bob <b>' },
|
||||
'id-carol': { sub: 'carol', issuer: 'https://dex.test', name: 'Carol' },
|
||||
};
|
||||
const ledger = new Map<string, { sub: string; confirmations: number; pageId: number }>();
|
||||
const mint = (sub: string, n: number, confirmations = 5) => {
|
||||
for (let i = 0; i < n; i++) ledger.set(`${sub}-${i}`, { sub, confirmations, pageId: 100 + ledger.size });
|
||||
};
|
||||
mint('alice', 10); mint('bob', 10); mint('carol', 3);
|
||||
const card = (tokenId: string): ChainCard => {
|
||||
const e = ledger.get(tokenId)!;
|
||||
return { tokenId, owner: `wallet-${e.sub}`, confirmations: e.confirmations, pageId: e.pageId, title: `Page ${e.pageId}` };
|
||||
};
|
||||
const calls = { verify: 0, resolve: 0, collection: 0 };
|
||||
const port: OwnershipPort = {
|
||||
async verifyAccount(idToken) {
|
||||
calls.verify++;
|
||||
const a = typeof idToken === 'string' ? accounts[idToken] : undefined;
|
||||
if (!a) throw new OwnershipError(401, 'Invalid eom.dev login');
|
||||
return a;
|
||||
},
|
||||
async resolveDeck(account, tokenIds, opts) {
|
||||
calls.resolve++;
|
||||
const ids = tokenIds as string[];
|
||||
if (ids.length !== opts.deckSize) throw new OwnershipError(400, 'wrong size');
|
||||
if (new Set(ids).size !== ids.length) throw new OwnershipError(400, 'duplicate token');
|
||||
for (const t of ids) {
|
||||
const e = ledger.get(t);
|
||||
if (!e) throw new OwnershipError(400, `unknown token ${t}`);
|
||||
if (e.sub !== account.sub) throw new OwnershipError(403, `not yours: ${t}`);
|
||||
if (e.confirmations < opts.minConfirmations) throw new OwnershipError(400, `unconfirmed: ${t}`);
|
||||
}
|
||||
return ids.map(card);
|
||||
},
|
||||
async collection(account) {
|
||||
calls.collection++;
|
||||
return [...ledger.entries()].filter(([, e]) => e.sub === account.sub).map(([t]) => card(t));
|
||||
},
|
||||
};
|
||||
return { port, ledger, calls, mint };
|
||||
}
|
||||
|
||||
const deckOf = (who: string, n = DECK) => Array.from({ length: n }, (_, i) => `${who}-${i}`);
|
||||
|
||||
function playOut(host: ModeHost, lobbyId: string, tokens: string[]) {
|
||||
for (let guard = 0; guard < 50; guard++) {
|
||||
const v0 = host.view(lobbyId, tokens[0]) as any;
|
||||
if (v0.phase !== 'playing') return v0;
|
||||
for (const t of tokens) {
|
||||
const v = host.view(lobbyId, t) as any;
|
||||
if (v.legalActions?.length) void host.act(lobbyId, t, v.legalActions[0]);
|
||||
}
|
||||
}
|
||||
throw new Error('did not finish');
|
||||
}
|
||||
|
||||
function newHost(modes = [duelMode()], store = new MatchStore(null), own = fakeOwnership()) {
|
||||
return { host: new ModeHost({ identity, modes, engines: { duel: duelStub, editwar: stubEngine }, ownership: own.port, store }), own, store };
|
||||
}
|
||||
|
||||
test('host-pvp: two account players finish a hosted constructed duel; rated, Elo moves, record has tokens', async () => {
|
||||
const { host, store } = newHost();
|
||||
const a = await host.createLobby('duel-classic', { idToken: 'id-alice', deck: deckOf('alice') });
|
||||
const b = await host.join(a.lobbyId, { idToken: 'id-bob', deck: deckOf('bob') });
|
||||
const v = host.view(a.lobbyId, a.token) as any;
|
||||
assert.equal(v.phase, 'playing');
|
||||
assert.equal(v.rated, true);
|
||||
assert.equal(v.mode.engine, 'duel');
|
||||
assert.deepEqual(v.players.map((p: any) => [p.name, p.account]), [['Alice Example', true], ['Bob b', true]]);
|
||||
assert.deepEqual(v.state.hand.map((c: any) => c.id), deckOf('alice'), 'cards are built from the chain, in deck order');
|
||||
const end = playOut(host, a.lobbyId, [a.token, b.token]);
|
||||
assert.equal(end.phase, 'finished');
|
||||
assert.match(end.matchId, /^[a-f0-9]{32}$/);
|
||||
const rec = host.matchRecord(end.matchId);
|
||||
assert.equal(rec.engine, 'duel');
|
||||
assert.equal(rec.rated, true);
|
||||
assert.deepEqual(rec.tokens, [deckOf('alice'), deckOf('bob')]);
|
||||
assert.ok(!JSON.stringify(rec).includes('id-alice'), 'ID tokens are never stored');
|
||||
const board = host.leaderboard('duel-classic').entries;
|
||||
assert.equal(board.length, 2);
|
||||
const [hi, lo] = eloUpdate(ELO_START, ELO_START, 0);
|
||||
const ratings = board.map(e => e.rating).sort();
|
||||
assert.deepEqual(ratings, [Math.round(lo), Math.round(hi)].sort());
|
||||
assert.ok(board.every(e => e.ratedPlayed === 1));
|
||||
assert.equal(store.total, 1);
|
||||
});
|
||||
|
||||
test('host-pvp: forged, unowned, short and unconfirmed decks are rejected; guests need an account', async () => {
|
||||
const { host, own } = newHost();
|
||||
const status = async (p: Promise<unknown>) => { try { await p; return 0; } catch (e) { assert.ok(e instanceof GameError, String(e)); return e.status; } };
|
||||
// Guest (secret) seat in an owned-cards mode.
|
||||
assert.equal(await status(host.createLobby('duel-classic', { name: 'Al', secret: 'alice-secret-0123456789abcdef', deck: deckOf('alice') })), 401);
|
||||
// Bad login.
|
||||
assert.equal(await status(host.createLobby('duel-classic', { idToken: 'id-mallory', deck: deckOf('alice') })), 401);
|
||||
// Short deck, long deck, non-array, non-strings: rejected before ownership is asked.
|
||||
const before = own.calls.resolve;
|
||||
assert.equal(await status(host.createLobby('duel-classic', { idToken: 'id-alice', deck: deckOf('alice', DECK - 1) })), 400);
|
||||
assert.equal(await status(host.createLobby('duel-classic', { idToken: 'id-alice', deck: deckOf('alice', DECK + 1) })), 400);
|
||||
assert.equal(await status(host.createLobby('duel-classic', { idToken: 'id-alice', deck: 'alice-0' })), 400);
|
||||
assert.equal(await status(host.createLobby('duel-classic', { idToken: 'id-alice', deck: [1, 2, 3, 4, 5, 6] })), 400);
|
||||
assert.equal(own.calls.resolve, before);
|
||||
// Forged token id (not on the chain), someone else's card, duplicate card.
|
||||
assert.equal(await status(host.createLobby('duel-classic', { idToken: 'id-alice', deck: [...deckOf('alice', DECK - 1), 'forged-1'] })), 400);
|
||||
assert.equal(await status(host.createLobby('duel-classic', { idToken: 'id-alice', deck: [...deckOf('alice', DECK - 1), 'bob-0'] })), 403);
|
||||
assert.equal(await status(host.createLobby('duel-classic', { idToken: 'id-alice', deck: [...deckOf('alice', DECK - 1), 'alice-0'] })), 400);
|
||||
// Unconfirmed: a fresh mint below the mode's minConfirmations.
|
||||
own.ledger.set('alice-new', { sub: 'alice', confirmations: 0, pageId: 999 });
|
||||
assert.equal(await status(host.createLobby('duel-classic', { idToken: 'id-alice', deck: [...deckOf('alice', DECK - 1), 'alice-new'] })), 400);
|
||||
// Joiner with a bad deck does not kill the creator's lobby.
|
||||
const a = await host.createLobby('duel-classic', { idToken: 'id-alice', deck: deckOf('alice') });
|
||||
assert.equal(await status(host.join(a.lobbyId, { idToken: 'id-bob', deck: deckOf('alice') })), 403);
|
||||
assert.equal((host.view(a.lobbyId) as any).phase, 'waiting');
|
||||
// Same account on both seats.
|
||||
assert.equal(await status(host.join(a.lobbyId, { idToken: 'id-alice', deck: deckOf('alice') })), 409);
|
||||
});
|
||||
|
||||
test('host-pvp: cross-seat and cross-lobby tokens are rejected', async () => {
|
||||
const { host } = newHost();
|
||||
const a = await host.createLobby('duel-classic', { idToken: 'id-alice', deck: deckOf('alice') });
|
||||
const b = await host.join(a.lobbyId, { idToken: 'id-bob', deck: deckOf('bob') });
|
||||
const c = await host.createLobby('duel-classic', { idToken: 'id-carol2', deck: [] }).catch(() => null);
|
||||
assert.equal(c, null);
|
||||
const other = await host.createLobby('duel-classic', { idToken: 'id-alice', deck: deckOf('alice') });
|
||||
// Bob's token acts as Bob only: legal actions are per seat, so Alice's action from Bob's token is illegal.
|
||||
const aliceAction = (host.view(a.lobbyId, a.token) as any).legalActions[0];
|
||||
const bobView = host.view(a.lobbyId, b.token) as any;
|
||||
assert.equal(bobView.seat, 1);
|
||||
// A token from another lobby is not a seat here, and a spectator sees no private state.
|
||||
await assert.rejects(host.act(a.lobbyId, other.token, aliceAction), (e: GameError) => e.status === 403);
|
||||
assert.equal((host.view(a.lobbyId, other.token) as any).state, undefined);
|
||||
assert.equal((host.view(a.lobbyId, other.token) as any).seat, null);
|
||||
assert.throws(() => host.resign(a.lobbyId, 'x'.repeat(32)), (e: GameError) => e.status === 403);
|
||||
// Seat ids are account-derived, never the token.
|
||||
const ids = bobView.players.map((p: any) => p.id);
|
||||
assert.ok(ids.every((id: string) => /^[a-f0-9]{64}$/.test(id)));
|
||||
assert.ok(!ids.includes(a.token) && !ids.includes(b.token));
|
||||
});
|
||||
|
||||
test('host-pvp: creator cards that moved before the join expire the lobby', async () => {
|
||||
const { host, own } = newHost();
|
||||
const a = await host.createLobby('duel-classic', { idToken: 'id-alice', deck: deckOf('alice') });
|
||||
own.ledger.set('alice-3', { ...own.ledger.get('alice-3')!, sub: 'carol' }); // transferred away
|
||||
await assert.rejects(host.join(a.lobbyId, { idToken: 'id-bob', deck: deckOf('bob') }), /no longer valid/);
|
||||
assert.equal((host.view(a.lobbyId) as any).phase, 'expired');
|
||||
});
|
||||
|
||||
test('host-pvp: private lobbies are hidden and joined by invite code', async () => {
|
||||
const { host } = newHost();
|
||||
const pub = await host.createLobby('duel-classic', { idToken: 'id-alice', deck: deckOf('alice') });
|
||||
const priv = await host.createLobby('duel-classic', { idToken: 'id-alice', deck: deckOf('alice'), private: true });
|
||||
assert.match(priv.invite!, /^[A-Za-z0-9_-]{12}$/);
|
||||
assert.deepEqual(host.openLobbies('duel-classic').map(l => l.lobbyId), [pub.lobbyId]);
|
||||
const inv = host.invite(priv.invite!);
|
||||
assert.equal(inv.lobbyId, priv.lobbyId);
|
||||
assert.equal(inv.open, true);
|
||||
assert.equal(inv.accountRequired, true);
|
||||
assert.equal(inv.createdBy, 'Alice Example');
|
||||
assert.throws(() => host.invite('nope'), (e: GameError) => e.status === 404);
|
||||
// Quick match never lands in a private lobby.
|
||||
const q = await host.quickMatch('duel-classic', { idToken: 'id-bob', deck: deckOf('bob') });
|
||||
assert.equal(q.matched, true);
|
||||
assert.equal(q.lobbyId, pub.lobbyId);
|
||||
await host.join(inv.lobbyId, { idToken: 'id-bob', deck: deckOf('bob') });
|
||||
assert.equal(host.invite(priv.invite!).open, false);
|
||||
// Only the creator's view carries the invite code.
|
||||
assert.equal((host.view(priv.lobbyId, priv.token) as any).invite, priv.invite);
|
||||
assert.equal((host.view(priv.lobbyId) as any).invite, undefined);
|
||||
});
|
||||
|
||||
test('host-pvp: quick match pairs the oldest open lobby, never yourself', async () => {
|
||||
const { host } = newHost();
|
||||
const first = await host.quickMatch('duel-classic', { idToken: 'id-alice', deck: deckOf('alice') });
|
||||
assert.equal(first.matched, false);
|
||||
assert.equal(first.seat, 0);
|
||||
const again = await host.quickMatch('duel-classic', { idToken: 'id-alice', deck: deckOf('alice') });
|
||||
assert.equal(again.matched, false, 'does not match your own lobby');
|
||||
assert.notEqual(again.lobbyId, first.lobbyId);
|
||||
const bob = await host.quickMatch('duel-classic', { idToken: 'id-bob', deck: deckOf('bob') });
|
||||
assert.equal(bob.matched, true);
|
||||
assert.equal(bob.lobbyId, first.lobbyId, 'oldest first');
|
||||
assert.equal(bob.seat, 1);
|
||||
assert.equal((host.view(first.lobbyId, first.token) as any).phase, 'playing');
|
||||
});
|
||||
|
||||
test('host-pvp: state version; unchanged polls return null (204 over HTTP)', async () => {
|
||||
const { host } = newHost();
|
||||
const a = await host.createLobby('duel-classic', { idToken: 'id-alice', deck: deckOf('alice') });
|
||||
const v1 = (host.view(a.lobbyId, a.token) as any).version;
|
||||
assert.equal(host.view(a.lobbyId, a.token, v1), null);
|
||||
const b = await host.join(a.lobbyId, { idToken: 'id-bob', deck: deckOf('bob') });
|
||||
const v2 = (host.view(a.lobbyId, a.token, v1) as any).version;
|
||||
assert.ok(v2 > v1);
|
||||
assert.equal(host.view(a.lobbyId, b.token, v2), null);
|
||||
await host.act(a.lobbyId, a.token, (host.view(a.lobbyId, a.token) as any).legalActions[0]);
|
||||
assert.ok((host.view(a.lobbyId, b.token, v2) as any).version > v2);
|
||||
|
||||
// Over HTTP: 204 with no body, 200 with a newer version; Dex token accepted as a JWT bearer.
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use('/api/game', createGameRouter(host, new ModeDiscovery({ peers: [] })));
|
||||
const server = app.listen(0);
|
||||
try {
|
||||
const base = `http://127.0.0.1:${(server.address() as any).port}/api/game`;
|
||||
const cur = (await (await fetch(`${base}/lobbies/${a.lobbyId}`, { headers: { authorization: `Bearer ${a.token}` } })).json()).version;
|
||||
const same = await fetch(`${base}/lobbies/${a.lobbyId}?v=${cur}`, { headers: { authorization: `Bearer ${a.token}` } });
|
||||
assert.equal(same.status, 204);
|
||||
const stale = await fetch(`${base}/lobbies/${a.lobbyId}?v=${cur - 1}`);
|
||||
assert.equal(stale.status, 200);
|
||||
const ladder = await (await fetch(`${base}/modes/duel-classic/ladder`)).json();
|
||||
assert.ok(Array.isArray(ladder.entries));
|
||||
// JWT-shaped bearer on a seat-creating route reaches verifyAccount (rejected here: unknown login).
|
||||
const jwt = await fetch(`${base}/modes/duel-classic/quick`, { method: 'POST', headers: { 'content-type': 'application/json',
|
||||
authorization: 'Bearer aaa.bbb.ccc' }, body: JSON.stringify({ deck: deckOf('alice') }) });
|
||||
assert.equal(jwt.status, 401);
|
||||
const inv = await fetch(`${base}/invites/${a.invite}`);
|
||||
assert.equal(inv.status, 200);
|
||||
assert.equal((await inv.json()).open, false);
|
||||
} finally { server.close(); }
|
||||
});
|
||||
|
||||
test('host-pvp: collections draft pools both players cards; short collections are rejected', async () => {
|
||||
const mode = duelMode({ id: 'duel-draft', decks: { kind: 'draft', source: 'collections', poolSize: 2 * DECK, pickSeconds: 30 } });
|
||||
const { host } = newHost([mode]);
|
||||
const a = await host.createLobby('duel-draft', { idToken: 'id-alice' });
|
||||
await host.join(a.lobbyId, { idToken: 'id-bob' });
|
||||
const v = host.view(a.lobbyId, a.token) as any;
|
||||
assert.equal(v.phase, 'drafting');
|
||||
assert.equal(v.draft.pool.length, 2 * DECK);
|
||||
const owners = new Set(v.draft.pool.map((p: any) => String(p.card.id).split('-')[0]));
|
||||
assert.ok(owners.size >= 1 && [...owners].every(o => o === 'alice' || o === 'bob'));
|
||||
// Carol owns 3 < 6 cards: not eligible.
|
||||
const c = await host.createLobby('duel-draft', { idToken: 'id-carol' });
|
||||
await assert.rejects(host.join(c.lobbyId, { idToken: 'id-bob' }), /3 \/ 6 cards/);
|
||||
assert.equal((host.view(c.lobbyId) as any).phase, 'expired');
|
||||
});
|
||||
|
||||
test('host-pvp: duel modes reject loaner policies; Night 1 mode files are rejected cleanly', () => {
|
||||
const store = new MatchStore(null);
|
||||
assert.throws(() => new ModeHost({ identity, store, engines: { duel: duelStub }, modes: [duelMode({ decks: { kind: 'starter' } })] }), /owned cards only/);
|
||||
assert.throws(() => new ModeHost({ identity, store, engines: { duel: duelStub },
|
||||
modes: [duelMode({ decks: { kind: 'draft', source: 'preview', poolSize: 12 } })] }), /owned cards only/);
|
||||
assert.throws(() => new ModeHost({ identity, store, engines: { editwar: stubEngine }, modes: [duelMode()] }), /engine "duel" is not available/);
|
||||
assert.throws(() => parseMode({ schema: 'wikideck.mode/1', id: 'old', version: 1, name: 'Old', description: 'x' }), /Night 1.*wikideck\.mode\/2/);
|
||||
assert.throws(() => parseMode({ schema: MODE_SCHEMA_VERSION, id: 'no-engine', version: 1, name: 'x', description: 'x' }));
|
||||
});
|
||||
|
||||
test('host-pvp: Edit War guests still play, unrated, beside duel modes', async () => {
|
||||
const war = parseMode({ schema: MODE_SCHEMA_VERSION, engine: 'editwar', id: 'war', version: 1, name: 'War', description: 'x',
|
||||
decks: { kind: 'starter' }, limits: { rated: true } });
|
||||
const { host } = newHost([duelMode(), war]);
|
||||
const a = await host.createLobby('war', { name: 'Al', secret: 'alice-secret-0123456789abcdef' });
|
||||
const b = await host.join(a.lobbyId, { name: 'Bo', secret: 'bob-secret-0123456789abcdefgh' });
|
||||
const end = playOut(host, a.lobbyId, [a.token, b.token]);
|
||||
const rec = host.matchRecord(end.matchId);
|
||||
assert.equal(rec.rated, false, 'guests are never rated');
|
||||
assert.ok(host.leaderboard('war').entries.every(e => e.rating === null));
|
||||
});
|
||||
|
||||
test('host-pvp: Elo is recomputed identically from matches.jsonl on restart', async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'host-pvp-'));
|
||||
try {
|
||||
const { host } = newHost([duelMode()], new MatchStore(dir));
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const a = await host.createLobby('duel-classic', { idToken: 'id-alice', deck: deckOf('alice') });
|
||||
const b = await host.join(a.lobbyId, { idToken: 'id-bob', deck: deckOf('bob') });
|
||||
playOut(host, a.lobbyId, [a.token, b.token]);
|
||||
}
|
||||
const before = host.leaderboard('duel-classic').entries;
|
||||
const reloaded = new MatchStore(dir);
|
||||
assert.deepEqual(reloaded.leaderboard('duel-classic'), before);
|
||||
assert.ok(before.every(e => e.ratedPlayed === 3));
|
||||
} finally { rmSync(dir, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
test('host-pvp: live lobbies with account seats survive a snapshot/restore', async () => {
|
||||
const { host, own } = newHost();
|
||||
const a = await host.createLobby('duel-classic', { idToken: 'id-alice', deck: deckOf('alice') });
|
||||
const snap = host.snapshot();
|
||||
assert.ok(!snap.includes(a.token) && !snap.includes('id-alice'));
|
||||
const next = new ModeHost({ identity, modes: [duelMode()], engines: { duel: duelStub }, ownership: own.port, store: new MatchStore(null) });
|
||||
assert.equal(next.restore(snap), 1);
|
||||
const b = await next.join(a.lobbyId, { idToken: 'id-bob', deck: deckOf('bob') });
|
||||
assert.equal((next.view(a.lobbyId, b.token) as any).phase, 'playing');
|
||||
assert.equal((next.view(a.lobbyId, a.token) as any).seat, 0);
|
||||
});
|
||||
|
||||
test('host-pvp: seeded shuffle is deterministic and a permutation', () => {
|
||||
const xs = Array.from({ length: 50 }, (_, i) => i);
|
||||
assert.deepEqual(seededShuffle(xs, 's'), seededShuffle(xs, 's'));
|
||||
assert.notDeepEqual(seededShuffle(xs, 's'), seededShuffle(xs, 't'));
|
||||
assert.deepEqual([...seededShuffle(xs, 's')].sort((a, b) => a - b), xs);
|
||||
});
|
||||
+10
-10
@@ -145,7 +145,7 @@ test('modes api: the rule examples in HOSTING.md are valid modes', () => {
|
||||
{ deckSize: 16, maxCopiesPerPage: 2, maxLoaners: 16 },
|
||||
{ turns: 6, turnSeconds: 40 },
|
||||
]) {
|
||||
const m = parseMode({ schema: MODE_SCHEMA_VERSION, id: 'doc-example', version: 1, name: 'x', description: 'x', rules });
|
||||
const m = parseMode({ schema: MODE_SCHEMA_VERSION, engine: 'editwar', id: 'doc-example', version: 1, name: 'x', description: 'x', rules });
|
||||
assert.doesNotThrow(() => resolveRuleset(DEFAULT_RULESET, m.rules, parseRuleset), JSON.stringify(rules));
|
||||
}
|
||||
});
|
||||
@@ -154,7 +154,7 @@ test('modes api: mode rules that make starter decks illegal fail at startup; liv
|
||||
const { ModeHost } = await import('../server/game/host.ts');
|
||||
const { MatchStore } = await import('../server/game/store.ts');
|
||||
const { engineBinding } = await import('../server/game/engine-binding.ts');
|
||||
const big = parseMode({ schema: MODE_SCHEMA_VERSION, id: 'big', version: 1, name: 'Big', description: 'x',
|
||||
const big = parseMode({ schema: MODE_SCHEMA_VERSION, engine: 'editwar', id: 'big', version: 1, name: 'Big', description: 'x',
|
||||
decks: { kind: 'starter' }, rules: { deckSize: 16, maxLoaners: 16 } });
|
||||
assert.throws(() => new ModeHost({ identity: { origin: 'http://x.test', operator: 'X' }, modes: [big], engine: engineBinding,
|
||||
store: new MatchStore(null) }), /starter decks are illegal/);
|
||||
@@ -172,10 +172,10 @@ test('modes api: turn timer applies the engine timeout action; AFK forfeits are
|
||||
const { MatchStore } = await import('../server/game/store.ts');
|
||||
const { engineBinding } = await import('../server/game/engine-binding.ts');
|
||||
let now = 0;
|
||||
const classic = parseMode({ schema: MODE_SCHEMA_VERSION, id: 'classic', version: 1, name: 'C', description: 'x', decks: { kind: 'starter' } });
|
||||
const classic = parseMode({ schema: MODE_SCHEMA_VERSION, engine: 'editwar', id: 'classic', version: 1, name: 'C', description: 'x', decks: { kind: 'starter' } });
|
||||
const host = new ModeHost({ identity: { origin: 'http://x.test', operator: 'X' }, modes: [classic], engine: engineBinding,
|
||||
store: new MatchStore(null), now: () => now });
|
||||
const a = host.createLobby('classic', alice);
|
||||
const a = await host.createLobby('classic', alice);
|
||||
const b = await host.join(a.lobbyId, bob);
|
||||
// Bob plays normally; Alice never acts.
|
||||
for (let turn = 0; turn < 6; turn++) {
|
||||
@@ -219,21 +219,21 @@ test('modes api: live matches survive a node restart (snapshot on shutdown, rest
|
||||
const { join } = await import('node:path');
|
||||
const dir = mkdtempSync(join(tmpdir(), 'modes-live-'));
|
||||
try {
|
||||
const modes = [parseMode({ schema: MODE_SCHEMA_VERSION, id: 'classic', version: 1, name: 'C', description: 'x', decks: { kind: 'starter' } }),
|
||||
parseMode({ schema: MODE_SCHEMA_VERSION, id: 'draft', version: 1, name: 'D', description: 'x', decks: { kind: 'draft', poolSize: 30 }, rules: { deckSize: 10, openingHand: 4 } })];
|
||||
const modes = [parseMode({ schema: MODE_SCHEMA_VERSION, engine: 'editwar', id: 'classic', version: 1, name: 'C', description: 'x', decks: { kind: 'starter' } }),
|
||||
parseMode({ schema: MODE_SCHEMA_VERSION, engine: 'editwar', id: 'draft', version: 1, name: 'D', description: 'x', decks: { kind: 'draft', poolSize: 30 }, rules: { deckSize: 10, openingHand: 4 } })];
|
||||
const make = () => new ModeHost({ identity: { origin: 'http://x.test', operator: 'X' }, modes, engine: engineBinding, store: new MatchStore(dir) });
|
||||
const first = make();
|
||||
persistLive(first, dir, false);
|
||||
const a = first.createLobby('classic', alice);
|
||||
const a = await first.createLobby('classic', alice);
|
||||
const b = await first.join(a.lobbyId, bob);
|
||||
// Random seed: the opening hand may have nothing playable on turn 1, so fall back to commit.
|
||||
const legal = (first.view(a.lobbyId, a.token) as any).legalActions;
|
||||
await first.act(a.lobbyId, a.token, legal.find((x: any) => x.type === 'play') ?? legal.find((x: any) => x.type === 'commit'));
|
||||
const d = first.createLobby('draft', alice);
|
||||
const d = await first.createLobby('draft', alice);
|
||||
const e = await first.join(d.lobbyId, bob);
|
||||
const pick = (first.view(d.lobbyId, d.token) as any).draft;
|
||||
await first.pick(d.lobbyId, [d.token, e.token][pick.toPick]!, 0);
|
||||
const waiting = first.createLobby('classic', { name: 'Cy', secret: 'cy-secret-0123456789abcdefghij' });
|
||||
const waiting = await first.createLobby('classic', { name: 'Cy', secret: 'cy-secret-0123456789abcdefghij' });
|
||||
const before = first.view(a.lobbyId, b.token) as any;
|
||||
persistLive(first, dir, false).save();
|
||||
|
||||
@@ -262,7 +262,7 @@ test('modes api: live matches survive a node restart (snapshot on shutdown, rest
|
||||
assert.equal(replay(rec.rules as any, rec.decks as any, rec.seed, rec.actions.map(x => x.action) as any).result?.winner ?? null, rec.winner);
|
||||
// Rules changed under a mode → its lobbies are dropped, not run under different rules.
|
||||
const changed = new ModeHost({ identity: { origin: 'http://x.test', operator: 'X' }, engine: engineBinding, store: new MatchStore(null),
|
||||
modes: [parseMode({ schema: MODE_SCHEMA_VERSION, id: 'classic', version: 1, name: 'C', description: 'x', decks: { kind: 'starter' }, rules: { turns: 5 } })] });
|
||||
modes: [parseMode({ schema: MODE_SCHEMA_VERSION, engine: 'editwar', id: 'classic', version: 1, name: 'C', description: 'x', decks: { kind: 'starter' }, rules: { turns: 5 } })] });
|
||||
assert.equal(changed.restore(second.snapshot()), 0);
|
||||
} finally { rmSync(dir, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
+14
-14
@@ -9,7 +9,7 @@ import { MatchStore } from '../server/game/store.ts';
|
||||
import { ModeDiscovery } from '../server/game/discovery.ts';
|
||||
import { stubEngine } from './modes-stub-engine.ts';
|
||||
|
||||
const mode = (over: object = {}) => parseMode({ schema: MODE_SCHEMA_VERSION, id: 'stub', version: 1, name: 'Stub',
|
||||
const mode = (over: object = {}) => parseMode({ schema: MODE_SCHEMA_VERSION, engine: 'editwar', id: 'stub', version: 1, name: 'Stub',
|
||||
description: 'Stub mode.', decks: { kind: 'starter' }, ...over });
|
||||
const identity = { origin: 'http://node-a.test', operator: 'Alice' };
|
||||
const alice = { name: 'Alice', secret: 'alice-secret-0123456789abcdef' };
|
||||
@@ -31,7 +31,7 @@ test('modes host: lobby → match → record → leaderboard and host credit', a
|
||||
let now = 1_000_000;
|
||||
const store = new MatchStore(null);
|
||||
const host = new ModeHost({ identity, modes: [mode()], engine: stubEngine, store, now: () => now });
|
||||
const a = host.createLobby('stub', alice);
|
||||
const a = await host.createLobby('stub', alice);
|
||||
assert.equal(host.list().modes[0]!.stats.openLobbies, 1);
|
||||
assert.deepEqual(host.openLobbies('stub').map(l => l.host), ['Alice']);
|
||||
const b = await host.join(a.lobbyId, bob);
|
||||
@@ -55,7 +55,7 @@ test('modes host: lobby → match → record → leaderboard and host credit', a
|
||||
|
||||
test('modes host: actions must be legal and from the right seat', async () => {
|
||||
const host = new ModeHost({ identity, modes: [mode()], engine: stubEngine, store: new MatchStore(null) });
|
||||
const a = host.createLobby('stub', alice);
|
||||
const a = await host.createLobby('stub', alice);
|
||||
const b = await host.join(a.lobbyId, bob);
|
||||
await assert.rejects(host.act(a.lobbyId, a.token, { type: 'play', card: 99 }), /Illegal/);
|
||||
await assert.rejects(host.act(a.lobbyId, 'not-a-token-xxxxxxxxxxxx', { type: 'play', card: 0 }), /Not a player/);
|
||||
@@ -63,21 +63,21 @@ test('modes host: actions must be legal and from the right seat', async () => {
|
||||
await assert.rejects(host.act(a.lobbyId, a.token, { type: 'play', card: 0 }), /Illegal/, 'no double play');
|
||||
await host.act(a.lobbyId, b.token, { card: 1, type: 'play' }); // key order doesn't matter
|
||||
await assert.rejects(host.join(a.lobbyId, { name: 'Eve', secret: 'eve-secret-0123456789abcdefgh' }), /no longer open/);
|
||||
assert.throws(() => host.createLobby('stub', { name: '<script>', secret: alice.secret }), GameError);
|
||||
assert.throws(() => host.createLobby('stub', { name: 'Al', secret: 'short' }), GameError);
|
||||
assert.throws(() => host.createLobby('nope', alice), /not hosted/);
|
||||
await assert.rejects(async () => host.createLobby('stub', { name: '<script>', secret: alice.secret }), GameError);
|
||||
await assert.rejects(async () => host.createLobby('stub', { name: 'Al', secret: 'short' }), GameError);
|
||||
await assert.rejects(async () => host.createLobby('nope', alice), /not hosted/);
|
||||
});
|
||||
|
||||
test('modes host: limits, expiry and turn timeouts', async () => {
|
||||
let now = 0;
|
||||
const host = new ModeHost({ identity, modes: [mode({ limits: { maxConcurrentMatches: 2, turnSeconds: 10, lobbyMinutes: 1 } })],
|
||||
engine: stubEngine, store: new MatchStore(null), now: () => now });
|
||||
const l1 = host.createLobby('stub', alice);
|
||||
host.createLobby('stub', bob);
|
||||
assert.throws(() => host.createLobby('stub', { name: 'Cy', secret: 'cy-secret-0123456789abcdefghij' }), /match limit/);
|
||||
const l1 = await host.createLobby('stub', alice);
|
||||
await host.createLobby('stub', bob);
|
||||
await assert.rejects(async () => host.createLobby('stub', { name: 'Cy', secret: 'cy-secret-0123456789abcdefghij' }), /match limit/);
|
||||
now += 61_000; host.sweep();
|
||||
assert.equal((host.view(l1.lobbyId) as any).phase, 'expired');
|
||||
const l3 = host.createLobby('stub', alice);
|
||||
const l3 = await host.createLobby('stub', alice);
|
||||
const t3 = await host.join(l3.lobbyId, bob);
|
||||
await host.act(l3.lobbyId, l3.token, { type: 'play', card: 0 }); // Bob now owes a move
|
||||
now += 11_000; host.sweep();
|
||||
@@ -89,7 +89,7 @@ test('modes host: limits, expiry and turn timeouts', async () => {
|
||||
test('modes host: snake draft builds both decks from one pool', async () => {
|
||||
const host = new ModeHost({ identity, modes: [mode({ decks: { kind: 'draft', poolSize: 8, pickSeconds: 10 } })],
|
||||
engine: stubEngine, store: new MatchStore(null) });
|
||||
const a = host.createLobby('stub', alice);
|
||||
const a = await host.createLobby('stub', alice);
|
||||
const b = await host.join(a.lobbyId, bob);
|
||||
const tok = [a.token, b.token];
|
||||
const order: number[] = [];
|
||||
@@ -113,7 +113,7 @@ test('modes host: trending mapping adjusts power from live trends, once, bounded
|
||||
const host = new ModeHost({ identity, modes: [mode({ cards: { preset: 'trending', percentPerPoint: 10, maxBonus: 2 } })],
|
||||
engine: stubEngine, store: new MatchStore(null),
|
||||
liveData: async pageId => { seen.push(pageId); return { trendPercent: pageId % 2 ? 1000 : -1000 }; } });
|
||||
const a = host.createLobby('stub', alice);
|
||||
const a = await host.createLobby('stub', alice);
|
||||
const b = await host.join(a.lobbyId, bob);
|
||||
const base = stubEngine.starterDeck(stubEngine.defaultRuleset, 'x');
|
||||
const hand = (host.view(a.lobbyId, a.token) as any).state.hand;
|
||||
@@ -131,7 +131,7 @@ test('modes store: records persist and rebuild aggregates; torn lines are skippe
|
||||
const dir = mkdtempSync(join(tmpdir(), 'modes-store-'));
|
||||
try {
|
||||
const host = new ModeHost({ identity, modes: [mode()], engine: stubEngine, store: new MatchStore(dir) });
|
||||
const a = host.createLobby('stub', alice);
|
||||
const a = await host.createLobby('stub', alice);
|
||||
const b = await host.join(a.lobbyId, bob);
|
||||
playOut(host, a.lobbyId, [a.token, b.token]);
|
||||
const file = join(dir, 'matches.jsonl');
|
||||
@@ -189,7 +189,7 @@ test('modes host: two concurrent joins cannot both take the second seat', async
|
||||
const slow = { ...stubEngine };
|
||||
const host = new ModeHost({ identity, modes: [mode({ cards: { preset: 'trending' } })], engine: slow, store: new MatchStore(null),
|
||||
liveData: async () => { await new Promise(r => setTimeout(r, 20)); return { trendPercent: 0 }; } });
|
||||
const a = host.createLobby('stub', alice);
|
||||
const a = await host.createLobby('stub', alice);
|
||||
const results = await Promise.allSettled([host.join(a.lobbyId, bob), host.join(a.lobbyId, { name: 'Eve', secret: 'eve-secret-0123456789abcdefgh' })]);
|
||||
assert.equal(results.filter(r => r.status === 'fulfilled').length, 1);
|
||||
assert.equal((host.view(a.lobbyId) as any).players.length, 2);
|
||||
|
||||
@@ -8,7 +8,7 @@ import { parsePeerOrigins } from '../server/game/discovery.ts';
|
||||
import { stubEngine } from './modes-stub-engine.ts';
|
||||
import { engineBinding } from '../server/game/engine-binding.ts';
|
||||
|
||||
const base = { schema: MODE_SCHEMA_VERSION, id: 'my-mode', version: 1, name: 'My mode', description: 'A test mode.' };
|
||||
const base = { schema: MODE_SCHEMA_VERSION, engine: 'editwar', id: 'my-mode', version: 1, name: 'My mode', description: 'A test mode.' };
|
||||
|
||||
test('modes: minimal document gets safe defaults', () => {
|
||||
const m = parseMode(base);
|
||||
|
||||
Reference in New Issue
Block a user