Files
wikideck/shared/game/modes.ts
T
claudeanderic 4f7a8a7c74 Night 1: Edit War card game, eom.dev accounts, peer-hosted modes, Android and iOS apps (#22)
Overnight build by 17 Claude agents (2026-11-16 22:45 → 01:30 EST), coordinated in [claude/wikideck milestone 63](https://gitea.eom.dev/claude/wikideck/milestone/63). **For Eric's review. Do not merge without it.** The full write-up is in `docs/night/REPORT.md`.

**What's in it** (38 reviewed PRs, squash-merged into `night/2026-11-16`):
- **Edit War:**
  - a 3-lane, 6-turn card game built on what WikiDeck cards actually hold
  - a pure, deterministic, off-chain rules engine (`shared/game/`, with the API in `docs/game/ENGINE_API.md`); rules are data and v1.1 is the default
  - a mobile-first Play UI with a lobby, deck builder, four loaner starter decks, a match against the AI, results and a tutorial
  - a landing page (fixes #3)
- **Design and balance:** `docs/game/DESIGN.md`, `CARD_DATA.md` (236 sampled articles) and `BALANCE.md` (bot simulations). Starter pairings went from 23–77% on v1 to roughly even on v1.1.
- **eom.dev accounts:** Dex OIDC with PKCE, plus off-chain wallet linking, where the client builds the message it signs (`server/account/`, `src/auth/`).
- **Peer-hosted game modes:** modes are JSON data, never code. Node API at `/api/game/*`, with host credit and leaderboards. Three example modes (`shared/game/modes.ts`, `server/game/`, `docs/game/HOSTING.md`).
- **Mobile:** Capacitor 7 Android app (a debug APK played a full match against the AI in the emulator), and an iOS project waiting on Xcode (`docs/night/ANDROID.md`, `docs/night/IOS.md`).
- **Testnet tooling:** `deploy/night/` (LAN-only, 3 nodes) and an optional `WIKIDECK_USER_AGENT` (the default is unchanged).

**Not touched:** consensus and protocol (`server/chain.ts`, `shared/protocol.ts`, `server/testnet/{consensus,ledger,…}.ts`, `native/`), the live deployment and mainnet. Matches run off-chain and never move or burn NFTs.

**Checks:** the final integration gate passed in `node:24-alpine`: `npm test` 241/242 with 0 fail (1 skipped), and `npm run build` passes. The repo needs Node 24, because Node 20 fails 12 tests falsely.

**Decisions for Eric** (see REPORT.md, Known issues and Next steps):
1. whether the live node should set `WIKIDECK_USER_AGENT`
2. the Xcode licence, which you should accept yourself
3. #49 in the fork, a bot change held after the freeze
4. on-chain host rewards (proposal only, in HOSTING.md)

🤖 Generated with [Claude Code](https://claude.com/claude-code)Reviewed-on: #22

Co-authored-by: Claude <claude@eom.dev>
2026-11-17 17:40:58 +00:00

231 lines
11 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 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/1' as const;
/** 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 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)`. */
z.object({ kind: z.literal('starter') }).strict(),
/** Snake draft from a host-seeded pool of non-NFT preview cards. */
z.object({ kind: z.literal('draft'),
/** 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),
/** 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),
}).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([]),
/** 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 }),
}).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 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 };
}
/** 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; }