Night 2 (2026-11-17), from the `claude/wikideck` fork's `night/2026-11-17` branch. It follows Night 1 (#22).
## What's in it
- **Duel engine** (fork #72, #80): 40-card decks of cards you own, Notability/Citations, keywords, effects T1–T12, Connected, a hidden-information-safe `viewFor`/`logFor`, and replay. Balance v1 tuning (#84) gives the first player about 51%.
- **Card profiles** (#70, #82): Figure, Location, Event, Institution or Doctrine, plus stats, keywords and rules text, all derived from real article data. Templates only.
- **Design and story** (#66, #69, #83): DUEL_DESIGN.md, plus the match log and the encyclopedic "Battle of X (2026)" recap.
- **PvP** (#74, #77, #81, #76, #85):
- The server checks ownership, and 40-card eligibility is enforced.
- Modes: Classic (ranked), Draft and Trending.
- Invites, quick match, Elo, a ladder and recap pages. Online matches render on the duel board.
- **Duel board UI** (#79): MTG-style card faces and combat declaration, built for 360 px first.
- **Polite Wikimedia client** (#73, #75): throttled, cached and identified requests, the mint-path fix, and a prefetch pool.
- **Android mining** (#78): native RandomX, as a sideload build. The emulator mined a testnet block.
- **Testnet ops** (#67, #68).
PR numbers refer to `claude/wikideck`.
## Status
- **Tests:** 423, of which 422 pass, 0 fail and 1 is skipped. The build is OK (`node:24-alpine`, `--network none`).
- **Testnet:** running this commit (036489c) on r350.
- **Untouched:** no changes to `server/testnet/consensus.ts`, `randomx.ts`, `native/` or the mainnet compose.
- **Review:** night-review reviewed fork #66–#79. #80–#85 came from the agents' unfinished branches and were not reviewed.
- **Known gaps:**
- The PvP end-to-end test hasn't been run (it needs two eom.dev accounts).
- Bot matches aren't reachable from Play.
- Card identity pre-bake hasn't been done.
- The RandomX verifier latch (`server/testnet/randomx.ts:140`) is still open.
This PR is for Eric to merge.
🤖 Generated with [Claude Code](https://claude.com/claude-code)Reviewed-on: #23
Co-authored-by: Claude <claude@eom.dev>
268 lines
13 KiB
TypeScript
268 lines
13 KiB
TypeScript
/**
|
||
* Peer-hosted game modes: a mode is DATA, never code.
|
||
*
|
||
* A mode is a small JSON document: base-rule overrides (applied on top of the engine's
|
||
* default `Ruleset` and re-validated by the engine's own ruleset parser), a card-mapping
|
||
* preset chosen from a fixed list, a deck policy, limits, and display text.
|
||
* A peer never executes, evals or imports anything another peer sends; it only parses
|
||
* this schema with hard size limits. See docs/game/HOSTING.md.
|
||
*
|
||
* No I/O here: shared by the server (host + discovery) and the browser (lobby).
|
||
*/
|
||
import { z } from 'zod';
|
||
|
||
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). */
|
||
export const MAX_MODES_PER_NODE = 16;
|
||
/** Upper bound on the JSON size of a whole /api/game/modes response read from a peer. */
|
||
export const MAX_MODE_LIST_BYTES = 192 * 1024;
|
||
|
||
const slug = z.string().regex(/^[a-z0-9](?:[a-z0-9-]{1,38}[a-z0-9])$/, 'lowercase slug, 3-40 chars');
|
||
/** Plain display text: no control characters, no angle brackets (rendered as text anyway). */
|
||
const text = (max: number) => z.string().trim().min(1).max(max)
|
||
.refine(s => !/[\u0000-\u001f\u007f<>]/.test(s), 'plain text only');
|
||
|
||
/**
|
||
* Rule overrides: a shallow-ish, bounded JSON object of numbers, booleans, short strings and
|
||
* short arrays of those. Its *meaning* is decided by the engine's ruleset schema, which runs
|
||
* after the merge (see `resolveRuleset`). This schema only guarantees it is small and inert.
|
||
*/
|
||
const scalar = z.union([z.number().finite(), z.boolean(), z.string().max(64)]);
|
||
const leaf = z.union([scalar, z.array(scalar).max(32)]);
|
||
const level2 = z.record(z.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,39}$/), leaf)
|
||
.refine(o => Object.keys(o).length <= 32, 'too many keys');
|
||
export const RuleOverridesSchema = z.record(z.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,39}$/),
|
||
z.union([leaf, level2])).refine(o => Object.keys(o).length <= 48, 'too many rule overrides');
|
||
export type RuleOverrides = z.infer<typeof RuleOverridesSchema>;
|
||
|
||
/**
|
||
* How Wikipedia data becomes card numbers in this mode. A fixed list of presets implemented
|
||
* in this file; a mode only picks one and tunes bounded parameters.
|
||
* - `standard`: the engine's default mapping from the immutable at-mint snapshot.
|
||
* - `live`: the same mapping, but from live current values when available.
|
||
* - `trending`: standard, plus a power bonus/penalty from live `pageviews.trendPercent`.
|
||
*/
|
||
export const CardMappingSchema = z.discriminatedUnion('preset', [
|
||
z.object({ preset: z.literal('standard') }).strict(),
|
||
z.object({ preset: z.literal('live') }).strict(),
|
||
z.object({ preset: z.literal('trending'),
|
||
/** Trend percent per +1 power (e.g. 25 → +25% trend gives +1). */
|
||
percentPerPoint: z.number().int().min(5).max(500).default(25),
|
||
/** Clamp on the bonus, in either direction. */
|
||
maxBonus: z.number().int().min(0).max(5).default(3),
|
||
/** Whether falling trends reduce power (never below 0). */
|
||
penalise: z.boolean().default(true),
|
||
}).strict(),
|
||
]);
|
||
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 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. */
|
||
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(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(),
|
||
]);
|
||
export type DeckPolicy = z.infer<typeof DeckPolicySchema>;
|
||
|
||
export const ModeLimitsSchema = z.object({
|
||
/** Concurrent open lobbies + live matches this mode may hold on the host. */
|
||
maxConcurrentMatches: z.number().int().min(1).max(256).default(32),
|
||
/** Seconds a player may take for one action before forfeiting the turn/match. */
|
||
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>;
|
||
|
||
/** The mode document an operator writes (and peers publish). */
|
||
export const ModeSchema = z.object({
|
||
schema: z.literal(MODE_SCHEMA_VERSION),
|
||
id: slug,
|
||
/** Monotonic integer; bump when the rules change so old match records stay attributable. */
|
||
version: z.number().int().min(1).max(1_000_000),
|
||
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', 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>;
|
||
|
||
/**
|
||
* The host's identity, configured by the node operator (never taken from a mode file).
|
||
* Discovery overwrites `origin` with the URL it actually fetched, so a peer can't
|
||
* publish modes in another node's name.
|
||
*/
|
||
export const HostIdentitySchema = z.object({
|
||
origin: z.string().url().max(256),
|
||
operator: text(48),
|
||
/** Optional short note, e.g. "EU, best effort". */
|
||
note: text(120).optional(),
|
||
}).strict();
|
||
export type HostIdentity = z.infer<typeof HostIdentitySchema>;
|
||
|
||
export const ModeStatsSchema = z.object({
|
||
playersOnline: z.number().int().min(0).max(1_000_000),
|
||
openLobbies: z.number().int().min(0).max(1_000_000),
|
||
liveMatches: z.number().int().min(0).max(1_000_000),
|
||
matchesPlayed: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
|
||
distinctPlayers: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
|
||
}).strict();
|
||
export type ModeStats = z.infer<typeof ModeStatsSchema>;
|
||
|
||
/** One entry of GET /api/game/modes. */
|
||
export const PublishedModeSchema = z.object({ mode: ModeSchema, stats: ModeStatsSchema }).strict();
|
||
export type PublishedMode = z.infer<typeof PublishedModeSchema>;
|
||
|
||
/** Body of GET /api/game/modes. */
|
||
export const ModeListSchema = z.object({
|
||
schema: z.literal(MODE_SCHEMA_VERSION),
|
||
host: HostIdentitySchema,
|
||
/** Total matches this node has hosted, across all its modes and versions. */
|
||
matchesHosted: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
|
||
modes: z.array(PublishedModeSchema).max(MAX_MODES_PER_NODE),
|
||
}).strict();
|
||
export type ModeList = z.infer<typeof ModeListSchema>;
|
||
|
||
/** Parse untrusted mode JSON text with a byte limit before JSON.parse. */
|
||
export function parseModeJson(json: string): ModeDocument {
|
||
if (byteLength(json) > MAX_MODE_BYTES) throw new Error(`Mode document exceeds ${MAX_MODE_BYTES} bytes`);
|
||
return parseMode(JSON.parse(json));
|
||
}
|
||
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;
|
||
}
|
||
/** Parse an untrusted peer's mode list. Invalid individual modes are dropped, not fatal. */
|
||
export function parseModeList(json: string): { list: ModeList; rejected: number } {
|
||
if (byteLength(json) > MAX_MODE_LIST_BYTES) throw new Error('Mode list too large');
|
||
const raw = z.object({ modes: z.array(z.unknown()).max(MAX_MODES_PER_NODE) }).passthrough().parse(JSON.parse(json));
|
||
let rejected = 0;
|
||
const modes: PublishedMode[] = [];
|
||
for (const entry of raw.modes) {
|
||
const parsed = hasForbiddenKeys(entry) ? null : PublishedModeSchema.safeParse(entry);
|
||
if (parsed?.success && byteLength(JSON.stringify(parsed.data.mode)) <= MAX_MODE_BYTES) modes.push(parsed.data);
|
||
else rejected++;
|
||
}
|
||
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}`;
|
||
}
|
||
|
||
const BLOCKED_KEYS = new Set(['__proto__', 'prototype', 'constructor']);
|
||
/**
|
||
* Merge overrides onto the engine's base ruleset, then validate with the engine's parser.
|
||
* Objects merge one level deep; arrays and scalars replace. Unknown keys are left for the
|
||
* engine parser to reject (it is strict), so a mode can never smuggle in unchecked rules.
|
||
*/
|
||
export function resolveRuleset<R>(base: R, overrides: RuleOverrides, parse: (value: unknown) => R): R {
|
||
const merged: Record<string, unknown> = structuredClone(base) as Record<string, unknown>;
|
||
for (const [key, value] of Object.entries(overrides)) {
|
||
if (BLOCKED_KEYS.has(key)) throw new Error('Forbidden rule key');
|
||
const current = merged[key];
|
||
if (isPlainObject(value) && isPlainObject(current)) {
|
||
const inner: Record<string, unknown> = { ...current };
|
||
for (const [k, v] of Object.entries(value)) {
|
||
if (BLOCKED_KEYS.has(k)) throw new Error('Forbidden rule key');
|
||
inner[k] = v;
|
||
}
|
||
merged[key] = inner;
|
||
} else merged[key] = value;
|
||
}
|
||
return parse(merged);
|
||
}
|
||
|
||
/** Live Wikipedia trend data a card mapping may read (subset of PageEnrichment). */
|
||
export type LiveCardData = { trendPercent: number | null };
|
||
|
||
/**
|
||
* Apply the mode's card-mapping preset to a card's base power. Pure and bounded.
|
||
* `standard`/`live` differ only in which stats the caller fed the engine's card builder.
|
||
*/
|
||
export function mappedPower(basePower: number, mapping: CardMapping, live?: LiveCardData): number {
|
||
if (mapping.preset !== 'trending') return basePower;
|
||
return basePower + trendBonus(mapping, live?.trendPercent ?? null);
|
||
}
|
||
export function trendBonus(mapping: Extract<CardMapping, { preset: 'trending' }>, trendPercent: number | null): number {
|
||
if (trendPercent === null || !Number.isFinite(trendPercent)) return 0;
|
||
let bonus = Math.trunc(trendPercent / mapping.percentPerPoint);
|
||
if (!mapping.penalise) bonus = Math.max(0, bonus);
|
||
return Math.max(-mapping.maxBonus, Math.min(mapping.maxBonus, bonus));
|
||
}
|
||
|
||
/** Clamp a mapped power the same way regardless of preset: never negative. */
|
||
export function clampPower(power: number): number { return Math.max(0, Math.round(power)); }
|
||
|
||
/** Reject prototype-polluting keys anywhere (zod's record() does not check them reliably). */
|
||
function hasForbiddenKeys(value: unknown, depth = 0): boolean {
|
||
if (depth > 8 || typeof value !== 'object' || value === null) return depth > 8;
|
||
for (const key of Object.keys(value)) {
|
||
if (BLOCKED_KEYS.has(key)) return true;
|
||
if (hasForbiddenKeys((value as Record<string, unknown>)[key], depth + 1)) return true;
|
||
}
|
||
return false;
|
||
}
|
||
function assertInertKeys(value: unknown): void {
|
||
if (hasForbiddenKeys(value)) throw new Error('Forbidden key in mode document');
|
||
}
|
||
function isPlainObject(v: unknown): v is Record<string, unknown> {
|
||
return typeof v === 'object' && v !== null && !Array.isArray(v);
|
||
}
|
||
function byteLength(s: string): number { return new TextEncoder().encode(s).length; }
|