Files
wikideck/shared/game/modes.ts
T

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; }