forked from WikiDeck/wikideck
Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
83c98759ba | ||
|
|
feae445f5a | ||
|
|
e7e51aecdb | ||
|
|
6fb9a2e8b4 | ||
|
|
b2ec917af4 | ||
|
|
c1a1325564 | ||
|
|
2e7b05bdad | ||
|
|
53d30e5cae | ||
|
|
7390a17a91 | ||
|
|
f507b0eaed |
@@ -0,0 +1,18 @@
|
||||
# Night 1 private testnet (sim-testnet)
|
||||
|
||||
A 3-node **testnet-only** fixture on poweredge-r350. It is reachable on the LAN only, and uses the Docker project `wikideck-night`.
|
||||
|
||||
| node | URL |
|
||||
|---|---|
|
||||
| node-a | http://192.168.1.32:3101 |
|
||||
| node-b | http://192.168.1.32:3102 |
|
||||
| node-c | http://192.168.1.32:3103 |
|
||||
|
||||
- `compose.lan.yaml` overrides only the published ports (bound to `192.168.1.32`, never `0.0.0.0`) and `PUBLIC_ORIGIN`. It changes nothing in consensus or the image.
|
||||
- `mine.ts` is a multi-worker native RandomX miner. It runs inside the `wikideck:testnet` image, which ships the native engine, so the host needs no cmake.
|
||||
- It mines to 4 disposable wallets (alice, bob, carol, dave) and writes chain-bound encrypted browser backups to `$STATE_DIR/wallets/`.
|
||||
- It never changes consensus code. Speed comes from the protocol's own testnet parameters: the initial target accepts 1/16 of hashes, and each 10-block retarget at most quadruples the difficulty.
|
||||
- Each template costs several Wikipedia API calls, and Wikipedia rate-limits our egress IP. The miner therefore paces templates (`MIN_GAP`, default 45 s) and backs off exponentially on failure.
|
||||
- `testnet.sh` has `up`, `mine N [workers]`, `status` and `down`. Run it from the repo root on a checkout of the integration branch. `up` rebuilds the image from that checkout; the ledgers persist in the named volumes.
|
||||
|
||||
Never point this at mainnet or the live `wikideck` namespace.
|
||||
@@ -0,0 +1,28 @@
|
||||
# sim-testnet override: publish the fixture on r350's LAN address only (not 0.0.0.0).
|
||||
# WIKIDECK_USER_AGENT identifies the testnet to Wikimedia (UA policy; no personal contact info).
|
||||
# Game-mode env (modes team, #6) is inert until night/modes/hosting merges.
|
||||
services:
|
||||
node-a:
|
||||
ports: !override ["192.168.1.32:3101:3001"]
|
||||
environment:
|
||||
PUBLIC_ORIGIN: http://192.168.1.32:3101
|
||||
WIKIDECK_USER_AGENT: &ua WikiDeck-testnet/0.1 (https://gitea.eom.dev/claude/wikideck; private testnet)
|
||||
WIKIDECK_MODES: classic,trending
|
||||
WIKIDECK_GAME_OPERATOR: Testnet A
|
||||
WIKIDECK_GAME_PEERS: http://192.168.1.32:3102,http://192.168.1.32:3103
|
||||
node-b:
|
||||
ports: !override ["192.168.1.32:3102:3001"]
|
||||
environment:
|
||||
PUBLIC_ORIGIN: http://192.168.1.32:3102
|
||||
WIKIDECK_USER_AGENT: *ua
|
||||
WIKIDECK_MODES: draft
|
||||
WIKIDECK_GAME_OPERATOR: Testnet B
|
||||
WIKIDECK_GAME_PEERS: http://192.168.1.32:3101,http://192.168.1.32:3103
|
||||
node-c:
|
||||
ports: !override ["192.168.1.32:3103:3001"]
|
||||
environment:
|
||||
PUBLIC_ORIGIN: http://192.168.1.32:3103
|
||||
WIKIDECK_USER_AGENT: *ua
|
||||
WIKIDECK_MODES: classic,trending,draft
|
||||
WIKIDECK_GAME_OPERATOR: Testnet C
|
||||
WIKIDECK_GAME_PEERS: http://192.168.1.32:3101,http://192.168.1.32:3102
|
||||
@@ -0,0 +1,100 @@
|
||||
// sim-testnet: multi-worker native RandomX miner for the PRIVATE wikideck-night testnet.
|
||||
// Runs inside the wikideck:testnet image (which ships the native engine). Testnet only.
|
||||
// Usage: node --experimental-strip-types /night/mine.ts <blocks> <workers>
|
||||
import { mkdirSync, readFileSync, writeFileSync, existsSync, appendFileSync } from 'node:fs';
|
||||
import { randomInt, webcrypto } from 'node:crypto';
|
||||
import { RandomX } from '/app/server/testnet/randomx.ts';
|
||||
import { CHAIN_ID, sha256, miningBlob, mintId, blockSchema, address } from '/app/server/testnet/consensus.ts';
|
||||
import { blockClaimMessage, NETWORK, type MiningTemplate, type TestnetBlock } from '/app/shared/testnet.ts';
|
||||
import { encryptWallet } from '/app/shared/wallet-backup.ts';
|
||||
|
||||
if (!NETWORK.includes('testnet')) throw new Error('testnet only');
|
||||
const blocks = Number(process.argv[2] ?? 45), workers = Number(process.argv[3] ?? 4);
|
||||
if (!(workers >= 1 && workers <= 8)) throw new Error('1..8 workers');
|
||||
const NODES = ['http://node-a:3001', 'http://node-b:3001', 'http://node-c:3001'];
|
||||
const WALLET_NAMES = ['alice', 'bob', 'carol', 'dave'];
|
||||
// PUBLIC, TESTNET-ONLY password for the disposable wallets' browser backups (posted on #4). Never reuse.
|
||||
const PASSWORD = process.env.TESTNET_WALLET_PASSWORD ?? 'wikideck-night-testnet';
|
||||
const STATE = process.env.STATE_DIR ?? '/state';
|
||||
const dir = `${STATE}/wallets`;
|
||||
mkdirSync(dir, { recursive: true });
|
||||
const subtle = webcrypto.subtle;
|
||||
|
||||
type W = { name: string; address: string; publicKey: string; privateKey: CryptoKey };
|
||||
async function loadOrCreate(name: string): Promise<W> {
|
||||
const keyFile = `${dir}/${name}.jwk.json`;
|
||||
let jwk: JsonWebKey;
|
||||
if (existsSync(keyFile)) jwk = JSON.parse(readFileSync(keyFile, 'utf8'));
|
||||
else {
|
||||
const kp = await subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, ['sign', 'verify']) as CryptoKeyPair;
|
||||
jwk = await subtle.exportKey('jwk', kp.privateKey);
|
||||
writeFileSync(keyFile, JSON.stringify(jwk), { mode: 0o600 });
|
||||
}
|
||||
const privateKey = await subtle.importKey('jwk', jwk, { name: 'ECDSA', namedCurve: 'P-256' }, true, ['sign']);
|
||||
const pubJwk = { kty: jwk.kty, crv: jwk.crv, x: jwk.x, y: jwk.y };
|
||||
const pub = await subtle.importKey('jwk', pubJwk, { name: 'ECDSA', namedCurve: 'P-256' }, true, ['verify']);
|
||||
const publicKey = Buffer.from(await subtle.exportKey('spki', pub)).toString('base64');
|
||||
const w = { name, address: address(publicKey), publicKey, privateKey };
|
||||
const backupFile = `${dir}/${name}.backup.json`;
|
||||
if (!existsSync(backupFile)) writeFileSync(backupFile, JSON.stringify(await encryptWallet(privateKey, publicKey, PASSWORD), null, 2));
|
||||
return w;
|
||||
}
|
||||
const wallets = await Promise.all(WALLET_NAMES.map(loadOrCreate));
|
||||
writeFileSync(`${dir}/addresses.json`, JSON.stringify(Object.fromEntries(wallets.map(w => [w.name, w.address])), null, 2));
|
||||
console.log(`chain ${CHAIN_ID}; wallets: ${wallets.map(w => `${w.name}=${w.address.slice(0, 12)}`).join(' ')}`);
|
||||
|
||||
async function api(node: string, path: string, body?: unknown) {
|
||||
const r = await fetch(node + path, { method: body ? 'POST' : 'GET', redirect: 'error', signal: AbortSignal.timeout(60000),
|
||||
headers: body ? { 'Content-Type': 'application/json' } : {}, body: body ? JSON.stringify(body) : undefined });
|
||||
const data = await r.json();
|
||||
if (!r.ok) throw new Error(data.error ?? `HTTP ${r.status}`);
|
||||
return data;
|
||||
}
|
||||
const engines = Array.from({ length: workers }, () => new RandomX());
|
||||
const close = () => { for (const e of engines) e.close(); };
|
||||
process.once('SIGTERM', () => { close(); process.exit(0); });
|
||||
|
||||
let accepted = 0, round = 0, fails = 0;
|
||||
// Each template costs several Wikipedia API calls, and Wikipedia rate-limits this egress IP:
|
||||
// pace templates (>= MIN_GAP s apart) and back off exponentially on failure.
|
||||
const MIN_GAP = Number(process.env.MIN_GAP ?? 45), sleep = (s: number) => new Promise(r => setTimeout(r, s * 1000));
|
||||
let lastTemplate = 0;
|
||||
try {
|
||||
while (accepted < blocks) {
|
||||
const wait = lastTemplate + MIN_GAP * 1000 - Date.now(); if (wait > 0) await sleep(wait / 1000);
|
||||
lastTemplate = Date.now();
|
||||
const node = NODES[round % NODES.length], w = wallets[accepted % wallets.length]; round++;
|
||||
let template: MiningTemplate;
|
||||
try { template = await api(node, '/api/mining/template', { owner: w.address, publicKey: w.publicKey }); fails = 0; }
|
||||
catch (e) { fails++; const b = Math.min(60 * 2 ** (fails - 1), 600); console.error(`template ${node}: ${(e as Error).message} (fail ${fails}, backoff ${b}s)`); await sleep(b); continue; }
|
||||
const h = template.header; if (h.chainId !== CHAIN_ID) throw new Error('wrong chain');
|
||||
const started = Date.now(); let attempts = 0; let found: { hash: string; nonce: number } | null = null;
|
||||
let base = randomInt(0, 2 ** 40); const BATCH = 64;
|
||||
while (!found) {
|
||||
const results = await Promise.all(engines.map((e, i) => {
|
||||
const hdr = { ...h, nonce: base + i * BATCH };
|
||||
return e.mine(h.key, miningBlob(hdr), h.target, 32, BATCH);
|
||||
}));
|
||||
attempts += BATCH * workers; base += BATCH * workers;
|
||||
found = results.find(Boolean) ?? null;
|
||||
if (!found && Date.now() / 1000 - h.createdAt > 600) break; // stale template
|
||||
}
|
||||
if (!found) continue;
|
||||
h.nonce = found.nonce;
|
||||
const hash = sha256(miningBlob(h));
|
||||
const signature = Buffer.from(await subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, w.privateKey,
|
||||
new TextEncoder().encode(blockClaimMessage(hash)))).toString('base64');
|
||||
const block: TestnetBlock = { ...h, hash, tokenId: mintId(h), powHash: found.hash, signature, transactions: template.transactions };
|
||||
blockSchema.parse(block);
|
||||
try {
|
||||
const res = await api(node, '/api/blocks', block);
|
||||
if (!res.accepted) { console.error(`not accepted: ${JSON.stringify(res).slice(0, 200)}`); continue; }
|
||||
accepted++;
|
||||
const secs = (Date.now() - started) / 1000;
|
||||
const line = `#${h.height} ${w.name} "${h.article.title}" token=${block.tokenId} via=${node} ${attempts}H ${(attempts / secs).toFixed(0)}H/s`;
|
||||
console.log(`[${accepted}/${blocks}] ${line}`);
|
||||
appendFileSync(`${STATE}/mined.log`, `${new Date().toISOString()} ${line}\n`);
|
||||
} catch (e) { console.error(`submit: ${(e as Error).message}`); }
|
||||
}
|
||||
} finally { close(); }
|
||||
console.log('done');
|
||||
Executable
+32
@@ -0,0 +1,32 @@
|
||||
#!/bin/sh
|
||||
# sim-testnet: private 3-node testnet fixture for WikiDeck Night 1 (poweredge-r350, LAN only).
|
||||
# Usage (from the repo root):
|
||||
# deploy/night/testnet.sh up build the image from this checkout and (re)start the 3 nodes
|
||||
# deploy/night/testnet.sh mine N [W] mine N real RandomX blocks with W workers (default 4, max 8)
|
||||
# deploy/night/testnet.sh status tip/height of each node
|
||||
# deploy/night/testnet.sh down stop the nodes (volumes, i.e. the ledgers, are kept)
|
||||
# STATE_DIR (default ~/.local/share/wikideck-night) holds the disposable testnet wallets and mined.log.
|
||||
# It is outside the repo on purpose: never commit wallets.
|
||||
set -eu
|
||||
P=wikideck-night
|
||||
LAN_IP=${LAN_IP:-192.168.1.32}
|
||||
STATE_DIR=${STATE_DIR:-$HOME/.local/share/wikideck-night}
|
||||
DC="docker compose -p $P -f compose.testnet.yaml -f deploy/night/compose.lan.yaml"
|
||||
case "${1:-}" in
|
||||
up) $DC build node-a && $DC up -d --no-build ;;
|
||||
down) $DC down ;;
|
||||
mine)
|
||||
mkdir -p "$STATE_DIR"
|
||||
W=${3:-4}
|
||||
docker rm -f $P-miner >/dev/null 2>&1 || true
|
||||
docker run -d --name $P-miner --network ${P}_default --cpus "$W" --memory 1600m \
|
||||
--user "$(id -u):$(id -g)" -e WIKIDECK_NETWORK=testnet -e WIKIDECK_GENESIS_TIME=1792411200 \
|
||||
-e MIN_GAP="${MIN_GAP:-45}" -v "$STATE_DIR":/state -v "$PWD/deploy/night":/night:ro \
|
||||
wikideck:testnet node --experimental-strip-types /night/mine.ts "$2" "$W"
|
||||
echo "follow with: docker logs -f $P-miner" ;;
|
||||
status)
|
||||
for port in 3101 3102 3103; do
|
||||
docker run --rm --network host wikideck:testnet node -e "fetch('http://$LAN_IP:$port/p2p/status').then(r=>r.json()).then(s=>console.log($port,'blocks',s.size,'tip',s.tip.slice(0,16))).catch(e=>console.log($port,'DOWN',e.message))"
|
||||
done ;;
|
||||
*) sed -n 2,9p "$0"; exit 1 ;;
|
||||
esac
|
||||
@@ -0,0 +1,149 @@
|
||||
# Card data: real stat distributions (council-data)
|
||||
|
||||
Status: **final for tonight**, 236 fully enriched cards, generated 2026-11-16 23:20 EST. Sampling stopped early on night-lead's request because Wikimedia was rate-limiting (429) our shared egress IP. 330 cards were picked; the first 236 finished enrichment.
|
||||
|
||||
**Method:** `scripts/night/card_sample.py` draws random ns0 articles in batches of 20 and keeps those that pass the `server/wiki.ts` filter: a thumbnail from upload/thumb.wikimedia.org and an intro extract of at least 40 characters. About 44% of random pages pass. Each card is enriched with the same API parameters as `server/enrichment.ts`:
|
||||
- six completed months, Jun–Oct 2026; attention uses October
|
||||
- monthly views summed from the daily REST pageviews
|
||||
|
||||
On top of that it adds Wikidata P31 and a 30-day drift (views 10-17..11-15 vs 09-17..10-16).
|
||||
|
||||
**Politeness:** the sampler runs serially at 1 request a second or slower, honours Retry-After, and caches every response to disk. `scripts/night/card_analyze.py` produces everything below, plus the `percentiles` (99 cut points each, for DESIGN §1.1) in `card-sample.json`.
|
||||
|
||||
## Files
|
||||
- `card-sample.json`: `cards[]` with the `PageEnrichment` shape, plus `category` (legacy `category()`), `instanceOf` (P31), `faction` (the P31 rules below), `tiers` and `drift30`. Top level: `percentiles`, `tierBreakpoints`, `factionRules` and `note`.
|
||||
- `starter-cards.json`: the loaner **pool**, 20 real frozen snapshots (a `MintStatsSnapshot` in `snapshot`). It also holds `starterDeckPageIds`: the 48 DESIGN §2.1 starter titles with their real pageIds and `cardId`s.
|
||||
|
||||
## Headline findings (236 cards)
|
||||
1. **Raw scores are compressed.**
|
||||
|
||||
| score | median | p10–p90 | max |
|
||||
|---|---|---|---|
|
||||
| attention | 32 | 20–53 | 77 |
|
||||
| depth | 63 | 54–73 | 87 |
|
||||
| reach | 20 | 0–45 | 70 |
|
||||
|
||||
No honest card reaches 100. Use `percentiles` (§1.1) or the 1–10 tiers, never the raw 0–100 values.
|
||||
2. **Correlations (Spearman):**
|
||||
- attention and depth: 0.61, so these two double-count fame
|
||||
- reach is nearly independent of both (0.17 with attention, 0.02 with depth)
|
||||
3. **Reach has a hard floor:** 18% of cards (42) have 0 other languages, so reach is 0. Under the §1.1 counting, all of them get pct_reach of about 8.
|
||||
4. **Raw values are long-tailed:**
|
||||
|
||||
| value | median | p90 | max |
|
||||
|---|---|---|---|
|
||||
| monthly views | 82 | 1,576 | 42k |
|
||||
| pageBytes | 6.1 KB | 24 KB | |
|
||||
| languageCount | 3 | 22 | |
|
||||
5. **Trend is mostly down:**
|
||||
- 65% of cards have a negative trendPercent, 34% positive; median −9.5%
|
||||
- 16% swing by more than 50% either way
|
||||
- null: 1%
|
||||
6. **Live drift is small in score terms.** The 30-day median |pageview drift| is 22% (p90 60%). That moves attention by only **1.7 points** (p90 6.3), so at-mint and live values differ little unless someone inflates them.
|
||||
7. **The legacy `category()` split is very skewed:**
|
||||
|
||||
| category | share |
|
||||
|---|---|
|
||||
| Culture | 56% |
|
||||
| People | 26% |
|
||||
| Nature | 8% |
|
||||
| History | 8% |
|
||||
| Science | 1% |
|
||||
| Space | 0.4% |
|
||||
8. **Candidate factions from P31:**
|
||||
|
||||
| faction | share |
|
||||
|---|---|
|
||||
| People | 29% |
|
||||
| Places | 20% |
|
||||
| Nature | 8% |
|
||||
| Structures | 7% |
|
||||
| Works | 5% |
|
||||
| Events | 5% |
|
||||
| Organisations | 4% |
|
||||
| Ideas & Tech | 3% |
|
||||
| Sport | 3% |
|
||||
| unclassified | 14% |
|
||||
|
||||
Suggested 6 for v2: People, Places, Nature, Works & Culture (Works + Organisations + Sport), Structures, Events & Ideas, plus a neutral fallback.
|
||||
|
||||
## Full tables
|
||||
|
||||
Sample: **236 cards**; ~44% (149/340 logged during sampling) of random pages pass the illustrated filter. Pageviews available for 236.
|
||||
|
||||
| stat | n | min | p10 | p25 | median | p75 | p90 | max | mean | skew |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| attention | 236 | 13 | 20 | 25 | 32 | 41 | 53 | 77 | 35 | 0.78 |
|
||||
| depth | 236 | 48 | 54 | 58 | 63 | 68 | 73 | 87 | 64 | 0.42 |
|
||||
| reach | 236 | 0 | 0 | 10 | 20 | 33 | 45 | 70 | 23 | 0.36 |
|
||||
| pageBytes | 236 | 772 | 1847 | 3084 | 6110 | 12805 | 24412 | 168332 | 11691 | 4.61 |
|
||||
| languageCount | 236 | 0 | 0 | 1 | 3 | 9 | 22 | 124 | 8 | 4.14 |
|
||||
| monthlyViews | 236 | 5 | 16 | 30 | 82 | 300 | 1576 | 42025 | 812 | 9.82 |
|
||||
| dailyAverage | 236 | 0.2 | 0.5 | 1.0 | 2.6 | 9.7 | 50.8 | 1355.6 | 26.2 | 9.82 |
|
||||
| trendPercent | 234 | -86.6 | -49.3 | -26.3 | -9.5 | 5.3 | 31.2 | 388.9 | -3.6 | 4.11 |
|
||||
| drift30Percent | 235 | -94.7 | -58.2 | -33.8 | -12.9 | 1.0 | 27.7 | 2268.7 | -4.2 | 14.07 |
|
||||
|
||||
**Spearman rank correlations** (cards with pageviews):
|
||||
|
||||
| | attention | depth | reach | trendPercent | drift30Percent |
|
||||
|---|---|---|---|---|---|
|
||||
| attention | 1.00 | 0.61 | 0.17 | 0.35 | 0.33 |
|
||||
| depth | 0.61 | 1.00 | 0.02 | 0.15 | 0.14 |
|
||||
| reach | 0.17 | 0.02 | 1.00 | 0.00 | 0.09 |
|
||||
| trendPercent | 0.35 | 0.15 | 0.00 | 1.00 | 0.31 |
|
||||
| drift30Percent | 0.33 | 0.14 | 0.09 | 0.31 | 1.00 |
|
||||
|
||||
(n=234; attention~monthlyViews, depth~pageBytes, reach~languageCount are monotonic so their rank correlations are identical.)
|
||||
|
||||
**trendPercent sign:** positive 79 (34%), negative 153 (65%), zero 2; null (prior month 0 or no views) 2. |trend| > 50%: 38; > 100%: 7.
|
||||
|
||||
**30-day drift** (views 10-17..11-15 vs 09-17..10-16): median |drift| 22%, p90 |drift| 60%. Attention score change implied: median 1.7 points, p90 6.3 points.
|
||||
|
||||
**attention histogram (deciles 0-9,10-19..90-100):** 0 19 74 74 36 20 12 1 0 0
|
||||
**depth histogram (deciles 0-9,10-19..90-100):** 0 0 0 0 2 72 117 38 7 0
|
||||
**reach histogram (deciles 0-9,10-19..90-100):** 42 60 53 43 21 15 1 1 0 0
|
||||
|
||||
Reach = 0 (no other languages): 42; reach 100 (>=999 langs) impossible in practice, max langs 124. Attention null: 0; attention 0: 0.
|
||||
|
||||
**Sum of three stats:** min 73, p10 89, p25 102, median 116, p75 135, p90 156, max 222
|
||||
|
||||
**Legacy `category()` (server/wiki.ts):** Culture 133, People 62, Nature 19, History 18, Science 3, Space 1
|
||||
|
||||
**Top Wikidata P31 classes:** human 64, taxon 16, village 7, commune of France 6, river 5, human settlement 4, musical group 3, building 3, gene 3, village of Poland 2, civil parish 2, protest 2, legislative election 2, castle 2, events in a specific year or time period 2, township of Pennsylvania 2, film 2, company 2, island 2, rural municipality of Austria 1, municipality of Austria 1, municipality of Brazil 1, television film 1, nor'easter 1, rail company (Japan) 1, municipality 1, association football match 1, final 1, local government area of Victoria 1, plant disease 1, basketball team season 1, mosque 1, functional programming language 1, purely functional programming language 1, dependently typed programming language 1, programming language 1, free software 1, proof assistant 1, municipality of Croatia 1, municipality of Bangladesh 1
|
||||
|
||||
No Wikidata item: 0; no P31: 13
|
||||
|
||||
**Most frequent category words (cards containing):** stubs 81, births 55, people 50, from 50, century 46, living 33, geography 30, american 29, deaths 28, united 27, county 27, states 23, established 21, establishments 20, alumni 18, places 17, university 16, buildings 16, state 15, national 14, structures 14, male 13, players 12, district 11, villages 11, sportsmen 11, members 11, described 10, football 10, sports 10, city 10, film 10, british 9, companies 9, populated 9, sportspeople 9, biography 9, york 9, women 8, taxa 8, germany 8, politicians 8, television 7, writers 7, french 7, genera 7, based 7, communes 7, language 7, expatriate 7, named 7, olympics 7, completed 7, historic 7, register 7, faculty 6, pennsylvania 6, civil 6, history 6, california 6
|
||||
|
||||
|
||||
## Rank-normalised tiers (1–10)
|
||||
|
||||
Tier = 1 + number of breakpoints the score is **>=**. Breakpoints are the sample deciles p10..p90 of the 0–100 score. Ties make some tiers thin (scores are integers).
|
||||
|
||||
| stat | p10 | p20 | p30 | p40 | p50 | p60 | p70 | p80 | p90 |
|
||||
|---|---|---|---|---|---|---|---|---|---|
|
||||
| attention | 20 | 24 | 27 | 30 | 32 | 35 | 39 | 44 | 53 |
|
||||
| depth | 54 | 57 | 59 | 61 | 63 | 65 | 67 | 69 | 73 |
|
||||
| reach | 0 | 10 | 10 | 16 | 20 | 26 | 30 | 36 | 45 |
|
||||
|
||||
Resulting tier counts — attention: None:0 1:19 2:27 3:24 4:23 5:23 6:17 7:28 8:25 9:22 10:28
|
||||
; depth: 1:14 2:23 3:26 4:21 5:25 6:26 7:22 8:21 9:30 10:28
|
||||
; reach: 1:0 2:42 3:0 4:30 5:30 6:32 7:21 8:27 9:27 10:27
|
||||
|
||||
|
||||
## Candidate factions (Wikidata P31 rules)
|
||||
|
||||
| faction | n | share | median attention | median depth | median reach | example |
|
||||
|---|---|---|---|---|---|---|
|
||||
| People | 68 | 29% | 31 | 65 | 22 | Salahuddin of Aceh |
|
||||
| Places | 48 | 20% | 28 | 61 | 32 | St. Georgen am Längsee |
|
||||
| Other | 34 | 14% | 40 | 65 | 16 | Village (Pennsylvania) |
|
||||
| Nature | 20 | 8% | 30 | 56 | 29 | Dichromorpha viridis |
|
||||
| Structures | 17 | 7% | 26 | 57 | 10 | Pathrail Mosque |
|
||||
| Works | 12 | 5% | 36 | 63 | 13 | The Best of Men |
|
||||
| Events | 12 | 5% | 40 | 72 | 13 | April 2021 nor'easter |
|
||||
| Organisations | 10 | 4% | 48 | 68 | 10 | Hiroshima Electric Railway |
|
||||
| Ideas & Tech | 8 | 3% | 30 | 63 | 16 | Agda (programming language) |
|
||||
| Sport | 7 | 3% | 27 | 70 | 16 | 1912 Argentine Primera División final |
|
||||
|
||||
Unclassified P31 labels: typeface 1, annexation 1, position 1, family 1, historic site 1, automobile manufacturer 1, historical society 1, stock character 1, pigeon breed 1, shopping center 1, Wikimedia list article 1, clinical sign 1, tram route 1, rubber-tyred tram 1, oil refinery 1, waterfall 1, orisha 1, water deity 1, Loa 1, arch 1, award 1, sex scandal 1, military base 1, artillery battery 1
|
||||
@@ -0,0 +1,518 @@
|
||||
# WikiDeck: Edit War — game design v1 (draft)
|
||||
|
||||
**Status:** v1 DRAFT, freeze target 23:30 EST 2026-11-16.
|
||||
**Owners:** council-designer-a owns sections 0–9 (research, card derivation, rules). council-designer-b
|
||||
owns sections 10–12 (keywords, peer-hosted modes, worked example). council-critic reviews.
|
||||
Every number in **`code font`** is a rules-config key (see §9). Modes can override any of them.
|
||||
|
||||
A two-player lane game for 3–6 minute matches. Each player has a 12-card deck and there are 3
|
||||
**Topics** (lanes) with 3 slots per side. There are 6 turns, both players plan at the same time, and
|
||||
energy ramps from 1 to 6, with 1 unspent energy carried over. Reveals interleave one card at a time.
|
||||
Win 2 of the 3 Topics. Each Topic is judged on one Wikipedia stat (**Attention**, **Depth** or
|
||||
**Reach**), and a card is stronger in a Topic that matches its best stat. Fame (how high a card's
|
||||
stats are overall) sets its **cost**, not its efficiency, so famous cards are sidegrades. They are
|
||||
not upgrades.
|
||||
|
||||
---
|
||||
|
||||
## 0. Research summary (what we took, what we left)
|
||||
|
||||
| Game | Why it's fun | Taken | Left |
|
||||
|---|---|---|---|
|
||||
| Marvel Snap | 3-minute matches; simultaneous turns; 3 lanes, so the decision is *where*, not just *what* | lanes, about 6 turns, simultaneous planning, small deck | stakes betting (modes only); we deliberately diverge in lane size (3), energy carry-over, interleaved alternating reveals, stats visible from turn 1 with hidden Portals, and on-topic tie-breaks |
|
||||
| Hearthstone | mana curve; readable cards; tempo | energy = turn number, curve-shaped costs | 30-card decks and 15-minute matches; hero powers |
|
||||
| Magic: The Gathering | factions (colours) with distinct identities; deckbuilding depth | 6 factions with their own keyword flavour | land screw (resource variance); the stack; long text |
|
||||
| Balatro | huge "moment" when a combo goes off; simple base rules plus modifiers | lane modifiers (Portals) as the run-to-run variety | single-player scoring |
|
||||
| Slay the Spire | readable intents; every card is a choice | open information about lane state and power | roguelike runs (could be a mode) |
|
||||
| Gwent | rows; best 2 of 3; passing and bluffing | best 2 of 3 Topics; hidden commitments | multi-round card advantage (too long) |
|
||||
| Pokémon TCG | type advantage | on-topic bonus (card stat matches lane stat) | energy attachment; coin flips |
|
||||
| Top Trumps | instantly understood: "my number beats yours" | lanes judged on one stat | picking the stat is solved play (always pick your best) |
|
||||
| Dominion | deck building as play | — (too long for 3–6 min) | — |
|
||||
|
||||
**What is ours, not borrowed:**
|
||||
- (a) each Topic is judged on one Wikipedia stat (the Top Trumps twist)
|
||||
- (b) cost comes from an article's fame instead of being printed
|
||||
- (c) a trend arrow driven by live pageviews
|
||||
- (d) a total-power and consensus tie-break instead of stakes betting
|
||||
- smaller choices: 3 slots per lane, 1 carried-over energy, interleaved reveals, and stats visible
|
||||
from turn 1 with hidden Portals
|
||||
|
||||
The core loop is a lanes game in the style of Snap. The Top Trumps twist is that each lane asks for
|
||||
one Wikipedia stat. That makes every stat matter and gives each turn its main decision: play the card
|
||||
on-topic for the bonus, or put it where the fight is.
|
||||
|
||||
---
|
||||
|
||||
## 1. Card derivation (card data → game card)
|
||||
|
||||
The engine never reads raw 0–100 stats as power. Every game card is derived **deterministically** from a
|
||||
`CardInput` that the match host freezes at match start:
|
||||
|
||||
```
|
||||
CardInput = { cardId, pageId, title, category, rarity,
|
||||
snapshot: MintStatsSnapshot, // at mint, immutable
|
||||
live: { trendPercent: number | null, dailyAverage: number | null }, // frozen at match start
|
||||
check: 'verified' | 'unverified' | 'unchecked' | 'loaner' } // set by the host (§1.10)
|
||||
```
|
||||
|
||||
### 1.1 Percentiles (rank-normalisation)
|
||||
For each stat `s` in {attention, depth, reach}, `pct_s` = the percentile (0–100, integer) of the card's
|
||||
snapshot score in the reference table `percentiles.<s>`. That table holds 99 ascending cut points from
|
||||
council-data's `docs/game/card-sample.json`.
|
||||
`pct_s` = the number of cut points strictly below the score, plus half the number equal to it, rounded
|
||||
down. A `null` attention gives `pct_attention = null`.
|
||||
|
||||
### 1.2 Fame → Cost
|
||||
`fame` = the integer mean (rounded half up) of the non-null percentiles.
|
||||
`cost` = 1 + the number of thresholds in `costThresholds` (5 ascending values, default
|
||||
`[15, 35, 55, 75, 90]`) that are ≤ `fame`. So cost runs 1–6.
|
||||
The defaults aim at a pool cost spread of about 15/20/20/20/15/10 %. They are retuned from the
|
||||
sample's fame distribution.
|
||||
|
||||
### 1.3 Power
|
||||
`power` = `powerByCost[cost]`, default `[_, 1, 2, 4, 6, 8, 10]` (cost 1 → 1 … cost 6 → 10). The
|
||||
critic's sim showed that heavy decks were too weak with `[…5,7,9]`.
|
||||
Power depends **only on cost**. Two cards of the same cost have the same base power, whatever their
|
||||
fame. Inflating stats (forged snapshots, template shopping) only moves a card up the curve. It never
|
||||
makes a card more efficient.
|
||||
|
||||
### 1.4 Home stat
|
||||
`home` = the stat with the highest `pct_s`. Ties are broken in this order: depth, reach, attention.
|
||||
Depth and reach are the hardest to inflate. A `null` stat can never be home.
|
||||
When a card is in a Topic whose stat equals its `home`, it gets **+`onTopicBonus[cost]`** power
|
||||
(default `[0, 1, 1, 2, 2, 3, 3]`, i.e. ⌈cost/2⌉).
|
||||
On-topic efficiency is then about 2 power per energy at every cost (2.0 / 1.5 / 2.0 / 1.75 / 2.0 / 2.0).
|
||||
Off-topic, cheap cards are weaker (1.0) than expensive ones (1.5). Cheap cards want their Topic, and
|
||||
big cards are flexible.
|
||||
|
||||
### 1.5 Faction
|
||||
`faction` = the card's `category` (Space, Nature, People, Science, History, Culture), from
|
||||
`server/wiki.ts`. Culture is about half the pool, so faction keywords are written so that a
|
||||
mono-faction deck gains no consistency edge (§10: no v1 keyword scales with faction count).
|
||||
|
||||
### 1.6 Trend (live, small, capped)
|
||||
`trend` = +1 if `live.trendPercent ≥ trendUp` (default 25), −1 if `≤ trendDown` (default −25),
|
||||
otherwise 0. A `null` value gives 0. Trend also needs `live.dailyAverage ≥ trendMinDaily` (default
|
||||
**20**), because percentages on tiny articles are noise; otherwise trend is 0. The host computes it **once at match start**, and it is frozen for
|
||||
the match. It shows as an arrow (▲/▼), not a number. It adds to power in every Topic.
|
||||
|
||||
### 1.7 Rarity
|
||||
The hash-derived `rarity` (`shared/protocol.ts:38`) is **cosmetic in v1** (frame colour only). Mining luck must not
|
||||
become power or keyword choice.
|
||||
|
||||
### 1.8 Keyword
|
||||
Each card has at most **one** keyword: cost-1 cards are vanilla, and the others get their faction's keyword (§10.1).
|
||||
|
||||
### 1.9 Card face (phone)
|
||||
The card face shows **cost** (top-left), **power** (big, centre; the bonus shows as a "+N" badge on the home icon when the card is on-topic), a **home-stat icon**
|
||||
(📣 attention / 📚 depth / 🌐 reach), an optional trend arrow, and one keyword word. That is two
|
||||
numbers, plus the live lane power when the card is on the board.
|
||||
|
||||
### 1.10 Plausibility (anti-forgery, off-chain)
|
||||
When `verifyStats` is true (the default for hosted matches), the match host checks each owned card's
|
||||
snapshot before the match:
|
||||
`pageBytes` against that revision's byte size, `languageCount` ≤ the live count + 5, and views for the
|
||||
snapshot month within ±10 % of the pageviews API.
|
||||
A card that fails is played with its live values. The **host replaces `snapshot`** with a snapshot
|
||||
built from the live values (`deriveStats` on the live bytes, languages and views) **before** it builds
|
||||
the `CardInput`. The match log marks the card `unverified`.
|
||||
The engine does no I/O and only ever sees one version of each card.
|
||||
- **Caching:** results are cached per `(pageId, revisionId, snapshotMonth)`. They are immutable, so a
|
||||
cached pass or fail never expires. Live values for a failed card are cached for 24 h.
|
||||
- **Card can't be verified** (the pageId or revision doesn't exist, or the title or category doesn't
|
||||
match): the card is **rejected at deck validation**, and the player is asked to swap in a loaner.
|
||||
- **API failure:** if Wikipedia can't be reached and nothing is cached, the card plays from its snapshot
|
||||
with `check: 'unchecked'`. The engine then caps its cost at `uncheckedCostCap` (default **4**), and
|
||||
power follows the capped cost. Matches are never blocked.
|
||||
- The engine's only use of `check` is that cost cap. Loaner cards are `check: 'loaner'`.
|
||||
|
||||
---
|
||||
|
||||
## 2. Decks
|
||||
|
||||
- **Deck size:** exactly `deckSize` cards (default **12**).
|
||||
- **Copies:** at most `maxCopiesPerPage` cards with the same `pageId` (default **2**). Owned and loaner
|
||||
copies count **together**. Each copy keeps its own snapshot, so the two copies may differ in cost.
|
||||
- **Deck validation** (engine): the size is right, the copy limit holds, every card's `check` is
|
||||
valid, and there are no more loaners than `maxLoaners`. An invalid deck can't start a match.
|
||||
- **Owned cards:** any card the player's wallet owns at match start. Ownership is read off-chain. The
|
||||
match never moves, locks or burns a card.
|
||||
- **Loaner cards:** off-chain preview cards with a fixed `CardInput`, shipped with the game data
|
||||
(`docs/game/starter-cards.json`, picked by council-data: about 24 pageIds across all 6 categories,
|
||||
with frozen, hand-checked snapshot stats, including the 4 cards in `shared/catalog.ts`).
|
||||
Loaners follow the same derivation, so they are no weaker or stronger than owned cards.
|
||||
- **Starter decks:** `starterDecks` (default: 4 fixed 12-card loaner decks). Each one has two leading
|
||||
factions and an average cost of 3.0–3.3, and is **curve-shaped**: at least 3 cards of cost 4 or more,
|
||||
and at most 4 of cost 1. A new player picks one and can play at once.
|
||||
- **Mixed decks:** an owned deck may fill any slots with loaners, up to `maxLoaners` (default 12, which
|
||||
means no limit). Owning NFTs gives **variety**, not power: owned and loaner cards follow the same
|
||||
curve.
|
||||
|
||||
---
|
||||
|
||||
## 3. Board
|
||||
|
||||
- 3 **Topics** (lanes), numbered 1–3 from left to right (top to bottom in portrait).
|
||||
- Each Topic has a **stat** (attention, depth or reach) and an optional **Portal** modifier (§10.3).
|
||||
Topics have **no faction**. No v1 keyword counts factions: faction only picks the keyword.
|
||||
- Each player has at most `laneCapacity` cards per Topic (default **3**). That gives 9 slots per side,
|
||||
which caps cheap-card flooding and fits 3 cards across a 360 px phone.
|
||||
- **Topic pool:** `topicPool` is a list of Topics, each `{ id, name, stat, portal | null }`. The default
|
||||
pool has 9 Topics: 3 per stat, one plain and two with Portals. `pool_s` is the sub-list with stat
|
||||
`s`, in file order.
|
||||
- **Topic draw (exact):**
|
||||
- If `distinctStats` is true (the default): for each stat in the fixed order
|
||||
`[attention, depth, reach]`, pick `pool_s[floor(next() × len(pool_s))]`. That uses 3 `next()`
|
||||
calls. Then Fisher–Yates the 3 picks into lanes 1–3 (i = 2, 1; j = floor(next() × (i+1))), which
|
||||
uses 2 calls.
|
||||
- If `distinctStats` is false: Fisher–Yates the whole pool (i from n−1 down to 1) and take the first
|
||||
`topicCount` entries as lanes 1–3.
|
||||
- **Stats visible, Portals hidden:** every Topic's **stat** is face-up from turn 1. Its **Portal**
|
||||
modifier is face-down until the start of turn `portalReveal[i]` (default `[2, 3, 4]`). You always
|
||||
know where your card is on-topic, but not what twist a lane will get.
|
||||
|
||||
---
|
||||
|
||||
## 4. Match setup (deterministic)
|
||||
|
||||
1. The input is `{ seed: uint32, rules, players: [p0, p1] }`, and each player's input is
|
||||
`{ id, deck: CardInput[12] }`. Seat order is input order.
|
||||
2. RNG: **mulberry32(seed)**. Every random choice draws `next()` in this fixed order:
|
||||
1. shuffle p0's deck (Fisher–Yates, i from n−1 down to 1, j = floor(next() × (i+1)))
|
||||
2. shuffle p1's deck the same way
|
||||
3. draw and shuffle the Topics
|
||||
4. the initiative coin: p0 has initiative on odd turns if next() < 0.5, otherwise p1
|
||||
5. later random events (keywords only), in resolution order
|
||||
3. Each player draws `openingHand` cards (default **3**). There are no mulligans in v1
|
||||
(`mulligan: false`).
|
||||
4. **Seed fairness (hosted PvP):** commit–reveal. Each party *i* (host, p0, p1) sends
|
||||
`sha256(r_i)` for a random 32-byte `r_i`, then reveals `r_i` once all commits are in.
|
||||
`seed` = the first 4 bytes (big-endian uint32) of `sha256(r_host ‖ r_p0 ‖ r_p1)`.
|
||||
The host still relays the hidden plans, so hosted PvP trusts the host not to leak them.
|
||||
Local and bot matches use any seed.
|
||||
|
||||
---
|
||||
|
||||
## 5. Turn structure
|
||||
|
||||
The match lasts `turns` turns (default **6**, hard cap). Each turn has these phases:
|
||||
|
||||
1. **Start**
|
||||
- Reveal any Portal scheduled for turn *t* (resolve its "on reveal").
|
||||
- Each player's energy = `energyByTurn[t-1]` + carry + `bonusEnergy`. Carry is
|
||||
min(`energyCarryMax`, unspent energy from last turn), default max **1**. Saving one energy on
|
||||
turn 2 makes a turn-3 four-drop possible: a real tempo choice.
|
||||
- Each player draws 1 card if their deck isn't empty and their hand holds fewer than `handLimit`
|
||||
(default **7**) cards. Otherwise they don't draw. This includes turn 1, so the turn-1 hand is
|
||||
3 + 1 = 4 cards.
|
||||
- Order within Start: Portal reveal, then energy, then draw. The Underdog check (step 2) comes after
|
||||
all three.
|
||||
2. **Underdog check** (mode option, `underdog: false` by default, because it can be sandbagged). When
|
||||
it's on, from turn 2, a player who leads in 0 Topics while the opponent leads in ≥ 2 gets
|
||||
**+1 energy** this turn.
|
||||
3. **Plan** (simultaneous, hidden)
|
||||
- Each player queues an ordered list of plays `(handIndex, topic)`.
|
||||
- Total cost must be ≤ their energy, and each Topic needs room on that player's side.
|
||||
- Plays can be undone freely until **Commit**. Passing is an empty commit.
|
||||
- The turn timer is `turnSeconds` (default **25**). On timeout, whatever is queued is committed.
|
||||
4. **Reveal (interleaved)**
|
||||
- Plays reveal **one at a time, alternating**: the initiative player's 1st, the other player's
|
||||
1st, the initiative player's 2nd, and so on. When one player runs out, the rest of the other's
|
||||
reveal in order.
|
||||
- Each card enters its Topic and its "on reveal" effect resolves at once.
|
||||
- So the order in which you queue cards matters: lead with the card you want resolved first.
|
||||
- Energy is reserved when a card is queued. A queued play that is no longer legal at reveal (the
|
||||
lane is full, or a Portal rejects it) **fizzles**: the card stays in hand and its energy is lost.
|
||||
5. **End**
|
||||
- Recompute all Topic powers (§6).
|
||||
- End-of-turn effects resolve, the initiative player's first.
|
||||
- Initiative strictly **alternates** each turn (set by the coin in §4).
|
||||
- Plans are locked before anything reveals, so initiative gives away no information. It only
|
||||
decides the order of on-reveal effects. §10 includes keywords where that order matters.
|
||||
|
||||
A typical turn is: look at the lanes, tap a card, tap a Topic (×1–3), tap Commit. That is under 10
|
||||
seconds, done with one thumb, with no dragging.
|
||||
|
||||
---
|
||||
|
||||
## 6. Power and Topic control
|
||||
|
||||
- A card's **lane power** = `power` + (`onTopicBonus[cost]` if its home stat is the Topic's stat) + `trend`
|
||||
+ keyword and Portal modifiers. It is never below 0.
|
||||
- A player's **Topic power** = the sum of their cards' lane power in that Topic.
|
||||
- A player **leads** a Topic if their Topic power is strictly greater than the opponent's.
|
||||
- **Consensus tie-break:** if the powers are equal and > 0, the player with more **on-topic** cards
|
||||
there leads. If that is also equal, nobody leads. 0–0 has no leader.
|
||||
|
||||
---
|
||||
|
||||
## 7. Win conditions and tie-breaks
|
||||
|
||||
**Scoring** happens after the last turn's End phase (§5.5): every end-of-turn effect, including
|
||||
the last turn's, and every "at scoring" Portal resolves **before** Topics are judged. Then:
|
||||
1. The player who leads **more Topics** wins (2–1, 2–0, 1–0 and 3–0 all count).
|
||||
2. If they lead the same number of Topics: the higher **total power across all Topics** wins.
|
||||
3. If that is also equal: the match is a **draw**.
|
||||
|
||||
**Concede:** a player can concede at any time, and the opponent wins at once. A player who misses
|
||||
`afkTurns` timeouts in a row (default **2**) with nothing queued concedes.
|
||||
|
||||
---
|
||||
|
||||
## 8. Degenerate lines and why they fail (for the critic)
|
||||
|
||||
| Line | Why it isn't dominant |
|
||||
|---|---|
|
||||
| All-famous (all max-stat) deck | It becomes an all-cost-5/6 deck with dead early turns. Cheap cards are more efficient **per energy**, expensive cards **per card**. Only 9 cards are seen per match (3 + 6 draws), so both matter. The 1-energy carry-over lets a heavy deck bank energy for a turn-5 six-drop. **sim-balance target: heavy vs curve ≥ 40%.** |
|
||||
| All-cheap flood (cost 1–2) | Weak by design: only 9 slots and 9 cards seen. Critic's sim under these rules: swarm vs curve about 7–11%. Its home is Culture's wide-turn keyword (§10). |
|
||||
| All one faction | No v1 keyword scales with faction count. `factionSynergyCap` is reserved for modes. Culture, the largest pool, has the weakest keyword (viral). |
|
||||
| "Always play the highest-power card" | It ignores the on-topic bonus, lane capacity and the hidden Portals. Critic's sim: 18–21% against a smart bot (target < 55%). |
|
||||
| Stall or pass | Passing leaves lanes to any 1-power card. Two passing players draw. |
|
||||
| Mirror the AI | Hidden simultaneous commits: you only see the opponent's cards after you commit. |
|
||||
| Seat or initiative | Planning is simultaneous and initiative strictly alternates (each seat has it for 3 of the 6 turns). Target: each seat wins 48–52%. |
|
||||
| Forged or shopped stats | They only raise cost (§1.3), the host check falls back to live stats (§1.10), and trend is capped at ±1. |
|
||||
| Inflated live pageviews | Worth at most +1, frozen at match start, and only counts for articles with ≥ 20 views a day. |
|
||||
| Swinginess | No effect may change a lane by more than 6 power or move cards between lanes in v1 (a keyword-design rule for §10). |
|
||||
|
||||
---
|
||||
|
||||
## 9. Rules config (all defaults)
|
||||
|
||||
The engine takes a `RulesConfig` object. Peer-hosted modes override it (§11). Defaults:
|
||||
|
||||
```json
|
||||
{
|
||||
"version": "1.0",
|
||||
"deckSize": 12, "maxCopiesPerPage": 2, "maxLoaners": 12,
|
||||
"openingHand": 3, "handLimit": 7, "mulligan": false,
|
||||
"turns": 6, "turnSeconds": 25, "afkTurns": 2,
|
||||
"energyByTurn": [1, 2, 3, 4, 5, 6], "energyCarryMax": 1, "bonusEnergy": 0, "underdog": false,
|
||||
"topicCount": 3, "distinctStats": true, "portalReveal": [2, 3, 4], "laneCapacity": 3,
|
||||
"topicPool": [ /* inline Topic objects {id, name, stat, portal}; default = the 9 in §10.3 */ ],
|
||||
"keywordParams": { /* per-keyword numbers, keyed by keyword id (§10) */ },
|
||||
"portalParams": { /* per-Portal numbers, keyed by Topic id (§10.3) */ },
|
||||
"costThresholds": [15, 35, 55, 75, 90],
|
||||
"powerByCost": [0, 1, 2, 4, 6, 8, 10],
|
||||
"onTopicBonus": [0, 1, 1, 2, 2, 3, 3], "vanillaBonus": 1,
|
||||
"keywordsEnabled": ["viral","rising","local","encyclopedic","nostalgic","translated"], "ownedCards": true,
|
||||
"trendUp": 25, "trendDown": -25, "trendMinDaily": 20, "uncheckedCostCap": 4,
|
||||
"factionSynergyCap": 3,
|
||||
"verifyStats": true,
|
||||
"percentiles": "card-sample-2026-11-16",
|
||||
"starterDecks": "default"
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
**What modes may vary:** every key above, plus `topicPool` contents and the starter-deck lists.
|
||||
**Fixed for all modes:** matches are off-chain and never move or burn NFTs; the RNG and its draw order
|
||||
(§4); the shape of the derivation (§1: percentile → fame → cost → power); at most one keyword per card;
|
||||
the phases of a turn (§5).
|
||||
A mode must keep `turns × turnSeconds ≤ 240` so that matches stay within 3–6 minutes.
|
||||
|
||||
---
|
||||
|
||||
## 10. Keywords *(owner: council-designer-b)*
|
||||
|
||||
**The v1 keyword set is these six, one per faction.** The ids are the ones engine-b already uses on `night/engine/keywords`.
|
||||
Topics carry only a **stat**, never a faction. Every keyword below that mentions a Topic keys off stats or board state.
|
||||
|
||||
### 10.1 Which keyword a card gets
|
||||
First rule that matches:
|
||||
1. `cost == 1` → **no keyword** (vanilla). The card gets +`vanillaBonus` power (default **1**), so a cost-1 card is 2.
|
||||
2. `"edition"` is in `keywordsEnabled` (off by default) and the deck holds another card with the same `pageId` → **edition**.
|
||||
3. Otherwise → the card's **faction keyword** from 10.2, if it's in `keywordsEnabled`. If not, the card is vanilla, *without* `vanillaBonus`.
|
||||
|
||||
Rarity plays no part here (it's cosmetic, §1.7). Keywords don't lower power, and v1 has no per-keyword power deltas.
|
||||
If sim shows that a keyword is worth more than about 1 power on average, sim-balance sets `keywordParams.<id>.powerDelta` (default 0, range −3 to 0).
|
||||
|
||||
### 10.2 Keyword list (v1)
|
||||
|
||||
| Faction | id (card word) | Trigger | Reminder text | Cap | Order-sensitive? |
|
||||
|---|---|---|---|---|---|
|
||||
| Culture | **viral** | On reveal | +1 power for each other card you revealed earlier this turn. | +2 | yes: your queue order |
|
||||
| Nature | **rising** | End of turn | +1 power. | +2 total | no |
|
||||
| People | **local** | Ongoing | +1 power while on-topic (the Topic's stat is its home stat). | +1 | no |
|
||||
| Science | **encyclopedic** | On reveal | +2 power if there are no other cards here (either side). | +2 | **yes: interleaving** |
|
||||
| History | **nostalgic** | On reveal | +2 power if you are losing here. | +2 | **yes: interleaving** |
|
||||
| Space | **translated** | On reveal | +1 power to your most recently revealed card in each *other* Topic. | +2 | yes |
|
||||
|
||||
Why this set: every keyword is one line and one trigger, and only adds power. The largest swing is +2 on one card,
|
||||
so no lane moves by more than 2 from a keyword. Nothing scales with faction count, so a mono-Culture deck gets no
|
||||
consistency edge (`factionSynergyCap` is unused in v1). Viral is Culture's weakest keyword, and it rewards wide turns.
|
||||
Three keywords (encyclopedic, nostalgic, translated) react to the interleaved reveal (§5.4), so initiative and queue order matter.
|
||||
|
||||
Precise rules (for engine-b):
|
||||
- **On reveal** resolves the moment the card enters its Topic, and sees every card revealed before it (both players,
|
||||
including earlier reveals this turn). The bonuses it grants are permanent counters.
|
||||
- **Ongoing** is a condition, recalculated whenever power is read.
|
||||
- **End of turn** resolves in §5.5 order: the initiative player's cards first, then Topic 1→3, then reveal order.
|
||||
- **viral:** counts the owner's cards revealed earlier in *this* turn's Reveal phase, in any Topic. Cards that went back to hand don't count.
|
||||
- **rising:** stops after it has gained +2 in total.
|
||||
- **local:** "on-topic" is exactly the §1.4/§6 condition. It's simply an extra +1 on top of `onTopicBonus`.
|
||||
- **encyclopedic:** "no other cards here" means both sides of this Topic are empty, apart from this card, when it reveals.
|
||||
- **nostalgic:** "losing here" means the opponent's Topic power here is strictly greater than yours, counted just *before* this card is added.
|
||||
The consensus tie-break doesn't count: a tie is not losing.
|
||||
- **translated:** "most recently revealed" means the highest global reveal sequence number among your cards in that Topic. Topics where you have no card are skipped.
|
||||
- No v1 keyword uses the RNG. §4's "later random events" slot stays empty in v1.
|
||||
|
||||
**Already in code, disabled by default (`keywordsEnabled` excludes them; for modes only):**
|
||||
- **edition:** +2 for each other copy of this `pageId` on your side.
|
||||
- **obscure:** the opponent sees it face down until the end of the match.
|
||||
- **wildcard:** its home stat becomes the Topic's stat on reveal.
|
||||
|
||||
These are engine-b's existing implementations. The faction-based versions of `local` and `wildcard`, and the token version of `viral`, are
|
||||
**replaced** by the definitions above.
|
||||
|
||||
**`keywordParams` defaults** (keyed by keyword id; modes may change them within the §11 ranges):
|
||||
```json
|
||||
{ "viral": {"amount": 1, "cap": 2, "powerDelta": 0}, "rising": {"amount": 1, "cap": 2, "powerDelta": 0},
|
||||
"local": {"amount": 1, "powerDelta": 0}, "encyclopedic": {"amount": 2, "powerDelta": 0},
|
||||
"nostalgic": {"amount": 2, "powerDelta": 0}, "translated": {"amount": 1, "powerDelta": 0},
|
||||
"edition": {"amount": 2, "powerDelta": 0}, "obscure": {"powerDelta": 0}, "wildcard": {"powerDelta": 0} }
|
||||
```
|
||||
End-of-turn effects on the last turn resolve **before** scoring (§7).
|
||||
|
||||
### 10.3 Portals (Topic modifiers) and the default Topic pool
|
||||
Each Topic has `{ id, name, stat, portal | null }`. The default `topicPool` has 9 Topics, one plain and two with
|
||||
Portals for each stat. A Portal applies from the moment its Topic is revealed (§3), except where it says otherwise.
|
||||
|
||||
| Topic | Stat | Portal rule |
|
||||
|---|---|---|
|
||||
| Current Events | attention | – |
|
||||
| Main Page | attention | At scoring, each card here gets +1 power. |
|
||||
| Trending | attention | Trend arrows (§1.6) count double here (±2). |
|
||||
| Archive | depth | – |
|
||||
| Featured Article | depth | At end of the match, the player with the single highest-power card here gets +2 Topic power here. If the highest card power here is tied (between the two players), nobody gets the bonus. |
|
||||
| Stub | depth | Lane capacity here is 2 per player. |
|
||||
| Translations | reach | – |
|
||||
| Interwiki | reach | +1 Topic power here for a player who has at least one card in all 3 Topics. |
|
||||
| Disambiguation | reach | Every card here counts as on-topic, whatever its home stat. |
|
||||
|
||||
As data: `portal = { kind: "scoringCardBonus", amount: 1 } | { kind: "trendMultiplier", factor: 2 } |
|
||||
{ kind: "highestCardBonus", amount: 2 } | { kind: "laneCapacity", value: 2 } | { kind: "spreadBonus", amount: 1 } |
|
||||
{ kind: "allOnTopic" }`. Modes may add Topics with these kinds, using new numbers, but not new kinds (engine code).
|
||||
|
||||
**`portalParams` defaults** (keyed by Topic id): `{ "main-page": {"amount": 1}, "trending": {"factor": 2},
|
||||
"featured-article": {"amount": 2}, "stub": {"value": 2}, "interwiki": {"amount": 1} }`. Disambiguation has no numbers.
|
||||
Topic ids are the names in kebab-case: `current-events, main-page, trending, archive, featured-article, stub,
|
||||
translations, interwiki, disambiguation`. The UI shows each Portal's one-line rule **on the lane itself**, not behind a tap.
|
||||
|
||||
---
|
||||
|
||||
## 11. Peer-hosted modes *(owner: council-designer-b)*
|
||||
|
||||
A **mode** is data, published by a node operator and run by the match host:
|
||||
```json
|
||||
{
|
||||
"id": "blitz", // [a-z0-9-]{3,32}, unique per host
|
||||
"name": "Blitz", "description": "Four quick turns.", // ≤ 40 and ≤ 280 chars, plain text
|
||||
"rules": { "turns": 4, "energyByTurn": [2, 3, 4, 5], "portalReveal": [1, 1, 2], "deckSize": 10 },
|
||||
"topicPool": [ /* optional: Topic objects (10.3); default if omitted */ ],
|
||||
"starterDecks": [ /* optional: lists of loaner pageIds */ ]
|
||||
}
|
||||
```
|
||||
- `rules` is a **partial** `RulesConfig` (§9) merged over the defaults. Unknown keys are rejected.
|
||||
- **Validation** (modes owns the code; these are the limits). If any check fails, the mode is refused:
|
||||
|
||||
| Key | Allowed |
|
||||
|---|---|
|
||||
| `turns` | 3–8, and `turns × turnSeconds ≤ 240` |
|
||||
| `energyByTurn` | length = `turns`, each 0–10 |
|
||||
| `bonusEnergy` | 0–3 |
|
||||
| `portalReveal` | length = `topicCount`, each 1..`turns`, non-decreasing |
|
||||
| `topicCount` | 1–5; `distinctStats` only if ≤ 3 |
|
||||
| `laneCapacity` | 1–6 |
|
||||
| `deckSize` | 6–20; `maxCopiesPerPage` 1–4; `maxLoaners` 0..`deckSize` |
|
||||
| `openingHand` | 0–6; `handLimit` 1–10 |
|
||||
| `turnSeconds` | 10–60; `afkTurns` 1–5 |
|
||||
| `costThresholds` | 5 strictly ascending integers in 0–100 |
|
||||
| `powerByCost` | 7 integers in 0–20, non-decreasing from index 1 |
|
||||
| `onTopicBonus` (7 entries), `vanillaBonus` | 0–5 each |
|
||||
| `trendUp` / `trendDown` | 0–200 / −200–0 |
|
||||
| `factionSynergyCap` | 0–6 |
|
||||
| `keywordsEnabled` | any subset of the 9 implemented ids (the 6 v1 defaults + edition, obscure, wildcard); a card whose keyword is disabled is vanilla, *without* `vanillaBonus` |
|
||||
| `keywordParams`, `portalParams` | only the keys listed in §10 / §10.3; amounts and caps 0–6, `powerDelta` −3–0 |
|
||||
| `verifyStats` | the host may only turn this off for modes that use only loaners (`maxLoaners == deckSize` and owned cards banned) |
|
||||
| `topicPool` | 3–20 Topics, Portal kinds only from 10.3 |
|
||||
|
||||
- **Identity:** `modeHash` = SHA-256 of the canonical JSON (sorted keys, no whitespace) of the *merged* rules
|
||||
plus the topicPool. A match record holds `{ modeHash, seed, both decks' CardInputs, both players' commit lists }`,
|
||||
and that is enough to replay it exactly.
|
||||
- **What modes can't change** is the "Fixed for all modes" list in §9. Modes also can't add keywords or Portal kinds, or
|
||||
stake, move or burn NFTs.
|
||||
|
||||
Example modes (good defaults for operators to publish):
|
||||
| Mode | Overrides | Feel |
|
||||
|---|---|---|
|
||||
| **Blitz** | `turns 4`, `energyByTurn [2,3,4,5]`, `portalReveal [1,1,2]`, `deckSize 10`, `turnSeconds 20` | about 2 minutes |
|
||||
| **Deep Cuts** | `topicPool`: only the 3 depth Topics, `distinctStats false` | rewards long, obscure articles |
|
||||
| **Loaner League** | `maxLoaners 12` and owned cards banned (`"ownedCards": false`, a new boolean key, default true) | fully level, for tournaments |
|
||||
| **Big Board** | `topicCount 5`, `distinctStats false`, `portalReveal [1,2,3,4,5]`, `laneCapacity 3` | win 3 of 5; **tablet/desktop only** (5 × 3 slots won't fit a 360 px phone) |
|
||||
| **No Keywords** | `keywordsEnabled []`, `onTopicBonus [0,3,3,3,3,3,3]` | Top Trumps–style tutorial mode |
|
||||
|
||||
---
|
||||
|
||||
## 12. Worked example match *(owner: council-designer-b)*
|
||||
|
||||
These are the §1–9 rules as of this PR:
|
||||
- `powerByCost [0,1,2,4,6,8,10]`, `onTopicBonus [0,1,1,2,2,3,3]`, `vanillaBonus 1`
|
||||
- `laneCapacity 3`, `energyCarryMax 1`, interleaved reveals, alternating initiative, `portalReveal [2,3,4]`
|
||||
- `underdog false`, no trend arrows
|
||||
|
||||
The derived cards are given directly (the §1 output), so the test needs no percentile table.
|
||||
Topics: **T1 Archive (depth, plain)**, **T2 Main Page (attention; Portal revealed turn 3; at scoring, each card here gets +1)**,
|
||||
**T3 Translations (reach, plain; revealed turn 4)**. Ana (p0) has initiative on odd turns and Bo (p1) on even turns.
|
||||
|
||||
| Player | Card | Faction | Cost | Base | Home | Keyword |
|
||||
|---|---|---|---|---|---|---|
|
||||
| Ana | Octopus | Nature | 1 | 2 | depth | – (vanilla) |
|
||||
| Ana | Moon | Space | 2 | 2 | reach | translated |
|
||||
| Ana | Coral reef | Nature | 2 | 2 | depth | rising |
|
||||
| Ana | Albert Einstein | People | 4 | 6 | attention | local |
|
||||
| Ana | Ancient Rome | History | 5 | 8 | depth | nostalgic |
|
||||
| Ana | Library of Alexandria | History | 4 | 6 | depth | nostalgic |
|
||||
| Ana | Periodic table | Science | 3 | 4 | depth | encyclopedic |
|
||||
| Bo | Haiku | Culture | 1 | 2 | attention | – (vanilla) |
|
||||
| Bo | Mars | Space | 2 | 2 | reach | translated |
|
||||
| Bo | Jazz | Culture | 2 | 2 | attention | viral |
|
||||
| Bo | Pop music | Culture | 4 | 6 | attention | viral |
|
||||
| Bo | Jupiter | Space | 5 | 8 | reach | translated |
|
||||
| Bo | Fern | Nature | 3 | 4 | depth | rising |
|
||||
| Bo | Mona Lisa | Culture | 3 | 4 | attention | viral |
|
||||
|
||||
Topic power is written as **Ana–Bo** after End of turn. Energy is "available / spent".
|
||||
|
||||
| Turn | Init | Energy Ana / Bo | Reveals, in interleaved order | T1 | T2 | T3 |
|
||||
|---|---|---|---|---|---|---|
|
||||
| 1 | Ana | 1/1, 1/1 | Ana Octopus → T1: 2 +1 on-topic = **3**. Bo Haiku → T2: 2+1 = **3** | 3–0 | 0–3 | 0–0 |
|
||||
| 2 | Bo | 2/2, 2/0 | Bo passes (to carry 1). Ana Moon → T3: 2+1 = 3. translated: Octopus +1 → 4 | 4–0 | 0–3 | 3–0 |
|
||||
| 3 | Ana | 3/2, **4**/4 | Main Page Portal revealed. Ana Coral reef → T1: 2+1 = 3. Bo Mars → T3: 2+1 = 3, translated: Haiku +1 → 4. Bo Jazz → T2: 2+1 = 3, viral (Mars earlier) +1 → 4. End: rising Coral reef → 4 | 8–0 | 0–8 | 3–3 (tie; on-topic 1–1, so no leader) |
|
||||
| 4 | Bo | **5**/4, 4/4 | Bo Pop music → T3: 6 (off-topic), viral +0. Ana Einstein → T2: 6+2 on-topic, local +1 = **9**. End: rising Coral reef → 5 (cap reached) | 9–0 | 9–8 | 3–9 |
|
||||
| 5 | Ana | **6**/5, 5/5 | Ana Ancient Rome → T3: 8 (off-topic). nostalgic: losing 3–9, so +2 → **10**. Bo Jupiter → T1: 8 (off-topic). translated: Jazz → 5 (T2), Pop music → 7 (T3) | 9–8 | 9–9: **Bo leads** (consensus: on-topic 1 vs 2) | 13–10 |
|
||||
| 6 (last) | Bo | **7**/7, 6/6 | Bo Fern → T1: 4+2 = 6. Ana Library → T1: 6+2 = 8. nostalgic: losing 9–14, so +2 → **10**. Bo Mona Lisa → T2: 4+2 = 6, viral (Fern earlier) +1 → 7. Ana Periodic table → T2: 4 (off-topic), encyclopedic: no (cards here). End: rising Fern → 7. Scoring: Main Page +1 per card in T2 | **19–15** | **15–19** | **13–10** |
|
||||
|
||||
Final card values:
|
||||
- **T1:**
|
||||
- Ana: Octopus 4 + Coral reef 5 + Library 10 = 19.
|
||||
- Bo: Jupiter 8 + Fern 7 = 15.
|
||||
- **T2:** each card +1 from Main Page.
|
||||
- Ana: Einstein 10 + Periodic table 5 = 15.
|
||||
- Bo: Haiku 5 + Jazz 6 + Mona Lisa 8 = 19.
|
||||
- **T3:**
|
||||
- Ana: Moon 3 + Ancient Rome 10 = 13.
|
||||
- Bo: Mars 3 + Pop music 7 = 10.
|
||||
|
||||
**Ana wins 2–1.** Three moments show the v1 mechanics:
|
||||
- **Carry-over:** Bo passed on turn 2 to afford two plays on turn 3 (4 energy).
|
||||
- **Consensus:** T2 at 9–9 after turn 5 went to Bo, who had two on-topic attention cards to Ana's one.
|
||||
- **Interleaving decides the match:** on turn 6 Bo had initiative, so Fern revealed before Library. Ana was then losing T1 (9 vs 14) and nostalgic fired (+2).
|
||||
If Ana had revealed first, she'd have been ahead 9–8, nostalgic would not have fired, and T1 would have been 17–15. Ana still wins that lane, but by 2 instead of 4.
|
||||
|
||||
**Golden test for engine-b:**
|
||||
- **Inject:** the Topic order, the opening hands and the draw order directly, with each player's commit list per turn as in the table. The queue order within a turn is as listed.
|
||||
- **Expected final Topic powers:** `T1 19–15, T2 15–19, T3 13–10`. Winner: p0, by 2 Topics to 1.
|
||||
- **Also assert:**
|
||||
- after turn 5, T2 is a 9–9 tie with Bo leading by consensus
|
||||
- Ana's carried energy is 1 at the start of turns 4, 5 and 6
|
||||
- Bo's carried energy is 1 at the start of turn 3
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,53 @@
|
||||
# Night 1: module boundaries
|
||||
|
||||
Owner: `night-lead`. This file is the rule when two PRs touch the same path. If you need to edit a path you don't own, comment on the owner's issue (`[from <you>]`) or keep your change to the "shared hook" listed below.
|
||||
|
||||
## Who owns what
|
||||
|
||||
| Path | Owner | Issue |
|
||||
|---|---|---|
|
||||
| `docs/game/DESIGN.md` | council (designer-a, designer-b, critic) | #1 |
|
||||
| `docs/game/CARD_DATA.md`, `docs/game/card-sample.json` | council-data | #2 |
|
||||
| `shared/game/` (types, RNG, state machine, rules, keywords, `Ruleset`, `starterDeck`) | engine-a (core, API), engine-b (keywords, effects) | #3 |
|
||||
| `docs/game/ENGINE_API.md` | engine-a | #3 |
|
||||
| `shared/game/modes.ts` | modes | #6 |
|
||||
| `server/game*` (e.g. `server/game/`, `server/game-*.ts`) | modes | #6 |
|
||||
| `docs/game/HOSTING.md` | modes | #6 |
|
||||
| `src/game/` (screens, lobby, deck builder, match, tutorial) | ui-a | #5 |
|
||||
| `src/game/ai/` (browser bots, easy and normal) | ui-b | #5 |
|
||||
| beta-fix files outside `src/game/` (landing page, `Card.tsx`, etc.) | ui-b, one PR per upstream issue | #5 |
|
||||
| `shared/bots/`, `scripts/sim/` (bots and the simulation runner) | sim-balance | #4 |
|
||||
| `docs/game/BALANCE.md` | sim-balance | #4 |
|
||||
| `compose.testnet.yaml` overrides, `deploy/night/` (testnet config, per-node mode files) | sim-testnet | #4 |
|
||||
| `server/account*` (e.g. `server/account/`), `src/auth/` | sso | #7 |
|
||||
| `android/`, `capacitor.config.ts` | mobile-android | #8 |
|
||||
| `ios/`, `docs/night/IOS.md` | mobile-ios, macos-fetch | #9 |
|
||||
| `docs/night/` (except `IOS.md`), this file, `REPORT.md` | night-lead | #10 |
|
||||
|
||||
## Tests
|
||||
|
||||
`scripts/run-tests.mjs` only picks up **top-level** `tests/*.test.ts`. Name your files with your team as a prefix so they never collide:
|
||||
`tests/game-*.test.ts` (engine), `tests/modes-*.test.ts`, `tests/ui-*.test.ts`, `tests/bots-*.test.ts`, `tests/account-*.test.ts`.
|
||||
|
||||
## Shared hooks (the only places two teams touch the same file)
|
||||
|
||||
1. **`server/testnet/http.ts`**: modes and sso each export an Express `Router` from their own files and add **exactly one** `app.use(...)` mount line just **above** the `/api` 404 handler (`app.use(['/api','/p2p'],(_req,res)=>{res.status(404)...`). Nothing else in this file. If SSO needs a CSP change (`connect-src` for `https://dex.eom.dev`), keep it to the `helmet` directive and say so in the PR.
|
||||
2. **`src/App.tsx`**: ui-a owns it. Others get one import and one element each (sso: a login button or provider; mobile: hide the mining controls behind a `isNativeApp()` check from `src/game/` or `src/auth/`, never by deleting code).
|
||||
3. **`package.json` and `package-lock.json`**: additive changes only (new dependencies or scripts). Don't reformat or bump existing versions. Lockfile conflicts are resolved by night-lead regenerating the lockfile.
|
||||
4. **`shared/enrichment.ts`**: read-only for everyone tonight. Map card data into game stats inside `shared/game/`.
|
||||
|
||||
## Off limits (consensus and protocol; PRs touching these are rejected)
|
||||
|
||||
`server/chain.ts`, `shared/protocol.ts`, `shared/trade-offer.ts`, `shared/chain-identity.ts`, `shared/network.ts`, `server/testnet/consensus.ts`, `server/testnet/ledger.ts`, `server/testnet/canonical-index.ts`, `server/testnet/randomx.ts`, `server/testnet/miner.ts`, `server/testnet/peers.ts`, `native/`.
|
||||
|
||||
If you think you need a change there, write it up in your issue instead.
|
||||
|
||||
## Dependency direction
|
||||
|
||||
`shared/game/` imports nothing from `server/` or `src/` and does no I/O. `shared/game/modes.ts`, `shared/bots/`, `server/game*`, `src/game/` import from `shared/game/` through the API in `ENGINE_API.md`, not from its internals.
|
||||
|
||||
## Merging
|
||||
|
||||
- Branch `night/<team>/<topic>`, PR into `night/2026-11-16`, squash-merged by night-lead after night-review approves and `npm test` and `npm run build` pass.
|
||||
- Small PRs merge faster. Rebase on the integration branch before asking for review if it moved under you.
|
||||
- After 01:10 (code freeze), only fixes merge.
|
||||
@@ -56,6 +56,7 @@ Turn WikiDeck into a game:
|
||||
flock /tmp/night-heavy.lock <npm ci | npm run build | gradle ...>
|
||||
```
|
||||
- **imac** (8 threads, about 4 GB free) and **poweredge-r350** (16 threads, about 6 GB free): keep builds to one at a time.
|
||||
- **Avoid permission prompts.** Nobody answers them, and they auto-deny after about a minute. Don't chain `cd <dir> && <command that writes files>`; use absolute paths or `git -C <dir>` instead. Keep each shell command to one clear purpose.
|
||||
- **LocalAI** (`https://localai.eom.dev`) is shared production with slow single-GPU inference. Don't use it in loops.
|
||||
|
||||
## Timeline (EST)
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Summarise card-sample.json into markdown stats. Usage: python3 -I card_analyze.py sample.json > out.md"""
|
||||
import json, sys, math, statistics as st, collections, re
|
||||
d = json.load(open(sys.argv[1])); C = d['cards']
|
||||
def q(v):
|
||||
v = sorted(v); n = len(v)
|
||||
def p(x):
|
||||
k = (n - 1) * x; f = math.floor(k); c = min(f + 1, n - 1); return v[f] + (v[c] - v[f]) * (k - f)
|
||||
return [v[0], p(.1), p(.25), p(.5), p(.75), p(.9), v[-1]]
|
||||
def skew(v):
|
||||
m, s = st.mean(v), st.pstdev(v); return sum((x - m) ** 3 for x in v) / len(v) / s ** 3 if s else 0
|
||||
def rank(v):
|
||||
o = sorted(range(len(v)), key=lambda i: v[i]); r = [0] * len(v); i = 0
|
||||
while i < len(o):
|
||||
j = i
|
||||
while j + 1 < len(o) and v[o[j + 1]] == v[o[i]]: j += 1
|
||||
for k in range(i, j + 1): r[o[k]] = (i + j) / 2
|
||||
i = j + 1
|
||||
return r
|
||||
def pearson(a, b):
|
||||
ma, mb = st.mean(a), st.mean(b); sa = math.sqrt(sum((x - ma) ** 2 for x in a)); sb = math.sqrt(sum((y - mb) ** 2 for y in b))
|
||||
return sum((x - ma) * (y - mb) for x, y in zip(a, b)) / (sa * sb) if sa and sb else float('nan')
|
||||
pv = [c for c in C if c['pageviews']['status'] == 'available']
|
||||
F = {'attention': lambda c: c['stats']['attention'], 'depth': lambda c: c['stats']['depth'], 'reach': lambda c: c['stats']['reach'],
|
||||
'pageBytes': lambda c: c['pageBytes'], 'languageCount': lambda c: c['languageCount'],
|
||||
'monthlyViews': lambda c: c['pageviews']['months'][5]['views'] if c['pageviews']['status'] == 'available' else None,
|
||||
'dailyAverage': lambda c: c['pageviews']['dailyAverage'], 'trendPercent': lambda c: c['pageviews']['trendPercent'],
|
||||
'drift30Percent': lambda c: c['drift30']['pct']}
|
||||
out = []
|
||||
P = out.append
|
||||
rate = f"{len(C)/d['rawPagesSeen']*100:.0f}%" if d['rawPagesSeen'] else '~44% (149/340 logged during sampling)'
|
||||
P(f"Sample: **{len(C)} cards**; {rate} of random pages pass the illustrated filter. Pageviews available for {len(pv)}.\n")
|
||||
P('| stat | n | min | p10 | p25 | median | p75 | p90 | max | mean | skew |'); P('|---|---|---|---|---|---|---|---|---|---|---|')
|
||||
for k, f in F.items():
|
||||
v = [f(c) for c in C if f(c) is not None]
|
||||
qs = q(v); fmt = (lambda x: f'{x:.0f}') if k not in ('trendPercent', 'drift30Percent', 'dailyAverage') else (lambda x: f'{x:.1f}')
|
||||
P(f"| {k} | {len(v)} | " + ' | '.join(fmt(x) for x in qs) + f" | {fmt(st.mean(v))} | {skew(v):.2f} |")
|
||||
P('\n**Spearman rank correlations** (cards with pageviews):\n')
|
||||
keys = ['attention', 'depth', 'reach', 'trendPercent', 'drift30Percent']
|
||||
rows = [c for c in pv if c['pageviews']['trendPercent'] is not None and c['drift30']['pct'] is not None]
|
||||
R = {k: rank([F[k](c) for c in rows]) for k in keys}
|
||||
P('| | ' + ' | '.join(keys) + ' |'); P('|---' * (len(keys) + 1) + '|')
|
||||
for a in keys: P(f'| {a} | ' + ' | '.join(f'{pearson(R[a], R[b]):.2f}' for b in keys) + ' |')
|
||||
P(f'\n(n={len(rows)}; attention~monthlyViews, depth~pageBytes, reach~languageCount are monotonic so their rank correlations are identical.)\n')
|
||||
tp = [c['pageviews']['trendPercent'] for c in pv if c['pageviews']['trendPercent'] is not None]
|
||||
P(f"**trendPercent sign:** positive {sum(t>0 for t in tp)} ({sum(t>0 for t in tp)/len(tp)*100:.0f}%), negative {sum(t<0 for t in tp)} ({sum(t<0 for t in tp)/len(tp)*100:.0f}%), zero {sum(t==0 for t in tp)}; null (prior month 0 or no views) {len(C)-len(tp)}. "
|
||||
f"|trend| > 50%: {sum(abs(t)>50 for t in tp)}; > 100%: {sum(abs(t)>100 for t in tp)}.\n")
|
||||
dr = [c['drift30']['pct'] for c in C if c['drift30']['pct'] is not None]
|
||||
P(f"**30-day drift** (views 10-17..11-15 vs 09-17..10-16): median |drift| {st.median([abs(x) for x in dr]):.0f}%, "
|
||||
f"p90 |drift| {q([abs(x) for x in dr])[5]:.0f}%. Attention score change implied: "
|
||||
f"median {st.median([abs(100*math.log10((c['drift30']['last30']+1)/(c['drift30']['prev30']+1))/6) for c in C]):.1f} points, "
|
||||
f"p90 {q([abs(100*math.log10((c['drift30']['last30']+1)/(c['drift30']['prev30']+1))/6) for c in C])[5]:.1f} points.\n")
|
||||
for name, f in [('attention', F['attention']), ('depth', F['depth']), ('reach', F['reach'])]:
|
||||
v = [f(c) for c in C if f(c) is not None]; h = collections.Counter(min(x // 10, 9) for x in v)
|
||||
P(f"**{name} histogram (deciles 0-9,10-19..90-100):** " + ' '.join(str(h.get(i, 0)) for i in range(10)))
|
||||
P(f"\nReach = 0 (no other languages): {sum(c['languageCount']==0 for c in C)}; reach 100 (>=999 langs) impossible in practice, max langs {max(c['languageCount'] for c in C)}. "
|
||||
f"Attention null: {sum(c['stats']['attention'] is None for c in C)}; attention 0: {sum(c['stats']['attention']==0 for c in C)}.\n")
|
||||
s3 = [sum(F[k](c) or 0 for k in ('attention', 'depth', 'reach')) for c in C]
|
||||
P(f"**Sum of three stats:** " + ', '.join(f'{n} {x:.0f}' for n, x in zip(['min', 'p10', 'p25', 'median', 'p75', 'p90', 'max'], q(s3))) + '\n')
|
||||
P('**Legacy `category()` (server/wiki.ts):** ' + ', '.join(f'{k} {v}' for k, v in collections.Counter(c['legacyCategory'] for c in C).most_common()) + '\n')
|
||||
io = collections.Counter(x['label'] for c in C for x in c['instanceOf'])
|
||||
P('**Top Wikidata P31 classes:** ' + ', '.join(f'{k} {v}' for k, v in io.most_common(40)) + '\n')
|
||||
P(f"No Wikidata item: {sum(not c['wikidataId'] for c in C)}; no P31: {sum(not c['instanceOf'] for c in C)}\n")
|
||||
words = collections.Counter()
|
||||
for c in C:
|
||||
for cat in set(w for t in c['categories'] for w in re.findall(r'[a-z]+', t.lower()) if len(w) > 3): words[cat] += 1
|
||||
P('**Most frequent category words (cards containing):** ' + ', '.join(f'{k} {v}' for k, v in words.most_common(60)) + '\n')
|
||||
print('\n'.join(out))
|
||||
|
||||
# ---- rank normalisation table (critic request): score -> 1..10 tier by sample decile
|
||||
def tiers(name):
|
||||
v = sorted(F[name](c) for c in C if F[name](c) is not None)
|
||||
return [v[min(len(v) - 1, int(len(v) * k / 10))] for k in range(1, 10)]
|
||||
T = {k: tiers(k) for k in ('attention', 'depth', 'reach')}
|
||||
print('\n## Rank-normalised tiers (1–10)\n')
|
||||
print('Tier = 1 + number of breakpoints the score is **>=**. Breakpoints are the sample deciles p10..p90 of the 0–100 score. '
|
||||
'Ties make some tiers thin (scores are integers).\n')
|
||||
print('| stat | p10 | p20 | p30 | p40 | p50 | p60 | p70 | p80 | p90 |'); print('|---' * 10 + '|')
|
||||
for k, b in T.items(): print(f'| {k} | ' + ' | '.join(str(x) for x in b) + ' |')
|
||||
def tier(k, s): return None if s is None else 1 + sum(s >= x for x in T[k])
|
||||
for c in C: c['tiers'] = {k: tier(k, c['stats'][k]) for k in T}
|
||||
tc = collections.Counter(c['tiers']['attention'] for c in C)
|
||||
print('\nResulting tier counts — attention: ' + ' '.join(f'{t}:{tc.get(t,0)}' for t in [None] + list(range(1, 11))))
|
||||
for k in ('depth', 'reach'):
|
||||
tc = collections.Counter(c['tiers'][k] for c in C); print(f'; {k}: ' + ' '.join(f'{t}:{tc.get(t,0)}' for t in range(1, 11)))
|
||||
json.dump({'breakpoints': T, 'rule': 'tier = 1 + count(breakpoints <= score); attention null -> no tier'},
|
||||
open(sys.argv[2] if len(sys.argv) > 2 else '/dev/null', 'w'), indent=1)
|
||||
|
||||
# ---- starter loaner candidates: 4 per legacy category, spread over combined tier
|
||||
if len(sys.argv) > 3:
|
||||
pick = []
|
||||
for cat in ['Space', 'Nature', 'People', 'Science', 'History', 'Culture']:
|
||||
pool = sorted((c for c in C if c['legacyCategory'] == cat and c['stats']['attention'] is not None),
|
||||
key=lambda c: sum(c['tiers'].values()))
|
||||
if not pool: continue
|
||||
n = min(4, len(pool)); idx = sorted({round(i * (len(pool) - 1) / max(1, n - 1)) for i in range(n)})
|
||||
for i in idx:
|
||||
c = pool[i]
|
||||
pick.append({'pageId': c['pageId'], 'title': c['title'], 'category': cat, 'wikidataId': c['wikidataId'],
|
||||
'revisionId': c['revisionId'], 'pageBytes': c['pageBytes'], 'languageCount': c['languageCount'],
|
||||
'monthlyViews': c['pageviews']['months'][5]['views'], 'latestMonth': c['pageviews']['latestMonth'],
|
||||
'trendPercent': None if c['pageviews']['trendPercent'] is None else round(c['pageviews']['trendPercent'], 1),
|
||||
'stats': c['stats'], 'tiers': c['tiers']})
|
||||
json.dump({'frozenAt': d['generatedAt'][:10], 'note': 'Frozen loaner/starter stats from the council-data random sample. Do not fetch live.',
|
||||
'cards': pick}, open(sys.argv[3], 'w'), indent=1, ensure_ascii=False)
|
||||
print(f'\nStarter candidates: {len(pick)} written to {sys.argv[3]}: ' + collections.Counter(p['category'] for p in pick).__repr__())
|
||||
|
||||
# ---- candidate factions from Wikidata P31 (+ categories fallback)
|
||||
FAC = [
|
||||
('People', r'\bhuman\b|fictional character|person'),
|
||||
('Sport', r'season|sports team|football|match|tournament|championship|final\b|club|league|olympic|race\b'),
|
||||
('Nature', r'taxon|species|genus|plant|fungus|disease|epiphyte|mineral|bird|fish|insect'),
|
||||
('Places', r'village|town|city|commune|municipality|river|lake|mountain|county|district|parish|region|plateau|island|settlement|neighbo|locality|census|hamlet|valley|bay|area|province|state of|capital|suburb|stream|peak|unincorporated|human settlement|local government'),
|
||||
('Structures', r'building|castle|mosque|church|cathedral|temple|bridge|station|railway line|road|highway|museum|structure|stadium|dam|tower|house|school|hospital|airport|monument|fort|palace|lighthouse|park'),
|
||||
('Works', r'film|album|single|song|musical|television|book|novel|video game|painting|literary|composition|series|episode|magazine|newspaper|poem|opera|play\b|artwork|sculpture'),
|
||||
('Organisations', r'company|group|band|organi[sz]ation|university|college|party|business|enterprise|agency|institute|association|brand|union|ministry|military unit'),
|
||||
('Events', r'election|protest|battle|war\b|storm|nor.easter|cyclone|event|disaster|treaty|conflict|earthquake|incident|festival|referendum|conference|ceremony'),
|
||||
('Ideas & Tech', r'programming|software|language|chemical|compound|gene|protein|theorem|concept|technology|vehicle|aircraft|ship|weapon|class|model|device|algorithm|religion|discipline|theory|food|dish'),
|
||||
]
|
||||
def faction(c):
|
||||
text = ' | '.join(x['label'].lower() for x in c['instanceOf'])
|
||||
for name, rx in FAC:
|
||||
if text and re.search(rx, text): return name
|
||||
cats = ' | '.join(c['categories']).lower()
|
||||
if re.search(r'births|deaths|people', cats): return 'People'
|
||||
if re.search(r'populated|villages|towns|geography|rivers', cats): return 'Places'
|
||||
if re.search(r'films|albums|songs|novels|television|video games', cats): return 'Works'
|
||||
return 'Other'
|
||||
for c in C: c['faction'] = faction(c)
|
||||
print('\n## Candidate factions (Wikidata P31 rules)\n')
|
||||
print('| faction | n | share | median attention | median depth | median reach | example |'); print('|---|---|---|---|---|---|---|')
|
||||
by = collections.defaultdict(list)
|
||||
for c in C: by[c['faction']].append(c)
|
||||
for name, cs in sorted(by.items(), key=lambda kv: -len(kv[1])):
|
||||
med = lambda k: st.median([x['stats'][k] for x in cs if x['stats'][k] is not None] or [0])
|
||||
print(f"| {name} | {len(cs)} | {len(cs)/len(C)*100:.0f}% | {med('attention'):.0f} | {med('depth'):.0f} | {med('reach'):.0f} | {cs[0]['title']} |")
|
||||
other = collections.Counter(x['label'] for c in by.get('Other', []) for x in c['instanceOf'])
|
||||
print('\nUnclassified P31 labels: ' + ', '.join(f'{k} {v}' for k, v in other.most_common(25)))
|
||||
if len(sys.argv) > 4: json.dump({c['pageId']: c['faction'] for c in C}, open(sys.argv[4], 'w'))
|
||||
if len(sys.argv) > 3:
|
||||
s = json.load(open(sys.argv[3])); fmap = {c['pageId']: c['faction'] for c in C}
|
||||
for p in s['cards']: p['faction'] = fmap[p['pageId']]
|
||||
json.dump(s, open(sys.argv[3], 'w'), indent=1, ensure_ascii=False)
|
||||
if len(sys.argv) > 5:
|
||||
d['factionRules'] = [[n, rx] for n, rx in FAC]; d['tierBreakpoints'] = T
|
||||
def cuts(k):
|
||||
v = sorted(c['stats'][k] for c in C if c['stats'][k] is not None); n = len(v)
|
||||
return [v[max(0, math.ceil(i * n / 100) - 1)] for i in range(1, 100)]
|
||||
d['percentiles'] = {k: cuts(k) for k in ('attention', 'depth', 'reach')}
|
||||
d['percentilesMethod'] = 'cut point i (1..99) = nearest-rank i-th percentile of the sample snapshot score (sorted ascending, index ceil(i*n/100)-1). Use with DESIGN.md §1.1 counting.'
|
||||
if not d['rawPagesSeen']:
|
||||
d['randomBatches'], d['rawPagesSeen'] = 17, 340
|
||||
d['randomBatchesNote'] = 'Sampling was resumed from a saved state, so full batch counts were lost. These are the counts logged at batch 17 (149 illustrated of 340 raw pages, 44% pass rate). The 330 picked cards came from about 38 batches; this sample holds the first N of those that finished enrichment before sampling stopped (Wikimedia 429s).'
|
||||
d['note'] = 'docs/game/starter-cards.json is the loaner POOL (real frozen snapshots of random articles), used by the sim and the deck builder to fill slots. The default starter decks are defined in DESIGN.md §2.1; their real pageIds are in starter-cards.json under starterDeckPageIds.'
|
||||
for c in d['cards']: c['category'] = c['legacyCategory']
|
||||
json.dump(d, open(sys.argv[5], 'w'), indent=1, ensure_ascii=False)
|
||||
@@ -0,0 +1,158 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Sample random illustrated en.wikipedia articles the way server/wiki.ts selects them and
|
||||
enrich them the way server/enrichment.ts does. Polite: ~4 req/s, sequential, disk cache.
|
||||
Usage: python3 -I card_sample.py <cache_dir> <out.json> [target=320]"""
|
||||
import hashlib, json, os, re, sys, time, urllib.parse, urllib.request, calendar, datetime as dt
|
||||
|
||||
UA = 'WikiDeckCardDataSampler/0.1 (experimental card-game stat research; python-urllib)'
|
||||
CACHE, OUT = sys.argv[1], sys.argv[2]
|
||||
TARGET = int(sys.argv[3]) if len(sys.argv) > 3 else 320
|
||||
os.makedirs(CACHE, exist_ok=True)
|
||||
_last = [0.0]
|
||||
|
||||
def get(url, cache=True):
|
||||
key = os.path.join(CACHE, hashlib.sha1(url.encode()).hexdigest() + '.json')
|
||||
if cache and os.path.exists(key):
|
||||
return json.load(open(key))
|
||||
if os.environ.get('CACHE_ONLY') and 'wikidata.org' not in url:
|
||||
return {'__missing': True}
|
||||
for attempt in range(6):
|
||||
wait = 1.0 - (time.time() - _last[0])
|
||||
if wait > 0: time.sleep(wait)
|
||||
_last[0] = time.time()
|
||||
req = urllib.request.Request(url, headers={'User-Agent': UA, 'Accept': 'application/json'})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=20) as r:
|
||||
data = json.loads(r.read().decode())
|
||||
break
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code == 404: data = {'__404': True}; break
|
||||
if e.code == 429 or e.code >= 500:
|
||||
ra = e.headers.get('retry-after'); w = int(ra) + 1 if ra and ra.isdigit() else 5 * (attempt + 1)
|
||||
print('http', e.code, 'sleep', w, file=sys.stderr); time.sleep(min(w, 60)); continue
|
||||
raise
|
||||
except Exception as e:
|
||||
print('retry', attempt, type(e).__name__, e, file=sys.stderr); time.sleep(2 * (attempt + 1))
|
||||
else:
|
||||
raise RuntimeError('failed ' + url)
|
||||
if cache: json.dump(data, open(key, 'w'))
|
||||
return data
|
||||
|
||||
def api(params, cache=True):
|
||||
return get('https://en.wikipedia.org/w/api.php?' + urllib.parse.urlencode({'format': 'json', 'formatversion': '2', **params}), cache)
|
||||
|
||||
def legacy_category(title, cats):
|
||||
t = (title + ' ' + ' '.join(cats)).lower()
|
||||
if re.search(r'astronom|planet|space|galax|moon|star\b', t): return 'Space'
|
||||
if re.search(r'animal|plant|species|ocean|biolog|mollusc', t): return 'Nature'
|
||||
if re.search(r'births|deaths|people|scientist', t): return 'People'
|
||||
if re.search(r'physic|chem|math|science|technolog', t): return 'Science'
|
||||
if re.search(r'histor|ancient|archaeolog|empire', t): return 'History'
|
||||
return 'Culture'
|
||||
|
||||
def score(v, scale):
|
||||
import math
|
||||
return min(100, round(math.log10(v + 1) / scale * 100))
|
||||
|
||||
# 1. random illustrated articles (same filter as wiki.ts: thumbnail + extract >= 40 chars)
|
||||
picked, seen, batches, raw_pages = [], set(), 0, 0
|
||||
state_file = os.path.join(CACHE, '_random_state.json')
|
||||
if os.path.exists(state_file):
|
||||
picked = json.load(open(state_file)); seen = {p['pageId'] for p in picked}
|
||||
while len(picked) < TARGET:
|
||||
try: d = api({'action': 'query', 'generator': 'random', 'grnnamespace': '0', 'grnlimit': '20',
|
||||
'prop': 'extracts|pageimages|info|categories', 'exintro': '1', 'explaintext': '1', 'exchars': '900',
|
||||
'exlimit': '20', 'piprop': 'thumbnail', 'pithumbsize': '800', 'cllimit': '500'}, cache=False)
|
||||
except RuntimeError as e: print(e, file=sys.stderr); time.sleep(5); continue
|
||||
batches += 1
|
||||
for p in d.get('query', {}).get('pages', []):
|
||||
raw_pages += 1
|
||||
thumb = (p.get('thumbnail') or {}).get('source', '')
|
||||
ext = (p.get('extract') or '').strip()
|
||||
if not re.match(r'https://(upload|thumb)\.wikimedia\.org/', thumb) or len(ext) < 40 or p['pageid'] in seen: continue
|
||||
seen.add(p['pageid'])
|
||||
picked.append({'pageId': p['pageid'], 'title': p['title'],
|
||||
'legacyCategory': legacy_category(p['title'], [c['title'] for c in p.get('categories', [])])})
|
||||
json.dump(picked, open(state_file, 'w'))
|
||||
print(f'random batch {batches}: {len(picked)} illustrated / {raw_pages} raw', file=sys.stderr)
|
||||
picked = picked[:TARGET]
|
||||
|
||||
# 2. enrichment per article (same params as enrichment.ts) + daily views for drift
|
||||
now = dt.datetime(2026, 11, 16, tzinfo=dt.timezone.utc)
|
||||
months = []
|
||||
for i in range(6):
|
||||
m = now.month - 6 + i; y = now.year + (m - 1) // 12; m = (m - 1) % 12 + 1
|
||||
months.append(f'{y:04d}-{m:02d}')
|
||||
# batched metadata (same props as enrichment.ts; per-page cllimit 50 is emulated by truncating)
|
||||
meta = {}
|
||||
ids = [p['pageId'] for p in picked]
|
||||
for i in range(0, len(ids), 50):
|
||||
chunk = ids[i:i + 50]; cont = {}; pages = {}
|
||||
while True:
|
||||
md = api({'action': 'query', 'pageids': '|'.join(map(str, chunk)), 'prop': 'info|categories|pageprops|description|langlinks',
|
||||
'clshow': '!hidden', 'cllimit': '500', 'lllimit': '500', 'ppprop': 'wikibase_item', **cont})
|
||||
for pg in md['query']['pages']:
|
||||
cur = pages.setdefault(pg['pageid'], {**pg, 'categories': [], 'langlinks': []})
|
||||
cur['categories'] += pg.get('categories', []); cur['langlinks'] += pg.get('langlinks', [])
|
||||
if 'continue' not in md: break
|
||||
cont = md['continue']
|
||||
meta.update(pages)
|
||||
print(f'metadata {len(meta)}/{len(ids)}', file=sys.stderr)
|
||||
cards = []
|
||||
for n, pk in enumerate(picked):
|
||||
page = meta[pk['pageId']]
|
||||
cont = {'clcontinue': 1} if len(page['categories']) > 50 else {}
|
||||
page['categories'] = page['categories'][:50]
|
||||
langs = len(page.get('langlinks', []))
|
||||
t = urllib.parse.quote(page['title'].replace(' ', '_'), safe='')
|
||||
daily = get(f'https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia.org/all-access/user/{t}/daily/{months[0].replace("-", "")}01/20261115')
|
||||
if daily.get('__missing'): continue
|
||||
dmap = {it['timestamp'][:8]: it['views'] for it in daily.get('items', [])}
|
||||
pv = {'status': 'unavailable', 'months': [], 'latestMonth': months[5], 'total': None, 'dailyAverage': None, 'trendPercent': None}
|
||||
if dmap:
|
||||
ordered = []
|
||||
for m in months:
|
||||
y, mo = map(int, m.split('-')); nd = calendar.monthrange(y, mo)[1]
|
||||
ordered.append({'month': m, 'views': sum(dmap.get(f'{y:04d}{mo:02d}{d:02d}', 0) for d in range(1, nd + 1))})
|
||||
latest, prior = ordered[5]['views'], ordered[4]['views']
|
||||
nd = calendar.monthrange(*map(int, months[5].split('-')))[1]
|
||||
pv = {'status': 'available', 'months': ordered, 'latestMonth': months[5], 'total': sum(o['views'] for o in ordered),
|
||||
'dailyAverage': latest / nd, 'trendPercent': (latest - prior) / prior * 100 if prior > 0 else None}
|
||||
# 30-day drift: views 2026-10-17..11-15 vs 2026-09-17..10-16
|
||||
def window(start, days):
|
||||
s = dt.date.fromisoformat(start)
|
||||
return sum(dmap.get((s + dt.timedelta(d)).strftime('%Y%m%d'), 0) for d in range(days))
|
||||
last30, prev30 = window('2026-10-17', 30), window('2026-09-17', 30)
|
||||
pb = page['length']
|
||||
cards.append({'pageId': page['pageid'], 'title': page['title'], 'description': page.get('description'),
|
||||
'wikidataId': (page.get('pageprops') or {}).get('wikibase_item'), 'revisionId': page['lastrevid'], 'pageBytes': pb,
|
||||
'languageCount': langs, 'languagesTruncated': 'llcontinue' in cont,
|
||||
'categories': [c['title'].removeprefix('Category:') for c in page.get('categories', [])],
|
||||
'categoriesTruncated': 'clcontinue' in cont, 'fetchedAt': now.isoformat(), 'pageviews': pv,
|
||||
'stats': {'attention': score(pv['months'][5]['views'], 6) if pv['status'] == 'available' else None,
|
||||
'depth': score(pb, 6), 'reach': score(langs, 3)},
|
||||
'legacyCategory': pk['legacyCategory'],
|
||||
'drift30': {'last30': last30, 'prev30': prev30, 'pct': (last30 - prev30) / prev30 * 100 if prev30 else None}})
|
||||
if n % 25 == 0: print(f'enriched {n + 1}/{len(picked)}', file=sys.stderr)
|
||||
|
||||
# 3. Wikidata P31 (instance of) + labels
|
||||
qids = [c['wikidataId'] for c in cards if c['wikidataId']]
|
||||
p31 = {}
|
||||
for i in range(0, len(qids), 50):
|
||||
d = get('https://www.wikidata.org/w/api.php?' + urllib.parse.urlencode({'action': 'wbgetentities', 'format': 'json',
|
||||
'ids': '|'.join(qids[i:i + 50]), 'props': 'claims'}))
|
||||
for q, ent in d.get('entities', {}).items():
|
||||
p31[q] = [c['mainsnak']['datavalue']['value']['id'] for c in ent.get('claims', {}).get('P31', [])
|
||||
if c['mainsnak'].get('datavalue')]
|
||||
classes = sorted({c for v in p31.values() for c in v})
|
||||
labels = {}
|
||||
for i in range(0, len(classes), 50):
|
||||
d = get('https://www.wikidata.org/w/api.php?' + urllib.parse.urlencode({'action': 'wbgetentities', 'format': 'json',
|
||||
'ids': '|'.join(classes[i:i + 50]), 'props': 'labels', 'languages': 'en'}))
|
||||
for q, ent in d.get('entities', {}).items():
|
||||
labels[q] = ent.get('labels', {}).get('en', {}).get('value', q)
|
||||
for c in cards:
|
||||
c['instanceOf'] = [{'id': q, 'label': labels.get(q, q)} for q in p31.get(c['wikidataId'], [])]
|
||||
json.dump({'generatedAt': dt.datetime.now(dt.timezone.utc).isoformat(), 'method': 'random ns0 batches of 20, filter as server/wiki.ts (thumbnail + extract>=40); enrichment as server/enrichment.ts; monthly views summed from daily REST pageviews; P31 from Wikidata',
|
||||
'randomBatches': batches, 'rawPagesSeen': raw_pages, 'cards': cards}, open(OUT, 'w'), indent=1, ensure_ascii=False)
|
||||
print('done', len(cards), file=sys.stderr)
|
||||
@@ -0,0 +1,60 @@
|
||||
# eom.dev accounts (Dex SSO) and wallet linking
|
||||
|
||||
Off-chain only. Nothing here changes blocks, transfers, trades or validation.
|
||||
|
||||
## Flow
|
||||
1. **Browser** (`src/auth/session.ts`):
|
||||
- `GET /api/account/config`
|
||||
- build the PKCE S256 authorize URL (with `state` and `nonce`)
|
||||
- navigate to `https://dex.eom.dev/auth`
|
||||
2. Dex redirects to `/auth/callback`. On native, it uses `dev.eom.wikideck:/oauth/callback`.
|
||||
3. **Browser** sends `POST /api/account/token {code, codeVerifier, redirectUri, nonce}`. The **node** then:
|
||||
- exchanges the code as the public client `wikideck` (no secret)
|
||||
- verifies the ID token against the JWKS
|
||||
- returns `{idToken, expiresAt, account}`
|
||||
|
||||
The exchange runs on the node because Dex sends no CORS headers.
|
||||
4. The browser keeps the ID token in **sessionStorage** and sends it as `Authorization: Bearer`.
|
||||
5. **Linking a wallet:**
|
||||
- `POST challenge {address}` → `{nonce, message, expiresAt}`
|
||||
- the **client builds the message itself** (`shared/account-link.ts` `clientLinkMessage`). It validates the nonce and expiry, refuses if the node's `message` differs, and signs locally with `src/wallet.ts` `sign`. The wallet never signs node-supplied text.
|
||||
- `POST link {nonce, address, publicKey, signature}`
|
||||
|
||||
Nonces are single use, expire after 5 minutes, and are bound to (sub, address). There are at most 5 pending per account. One wallet belongs to one account.
|
||||
|
||||
## Endpoints (`/api/account/...`)
|
||||
| Method | Path | Auth | Purpose |
|
||||
|---|---|---|---|
|
||||
| GET | `config` | none | issuer, clientId, scopes, authorization endpoint, allowed redirect URIs |
|
||||
| POST | `token` | none | code exchange → ID token + account |
|
||||
| GET | `me` | Bearer | account + linked wallets |
|
||||
| POST | `challenge` | Bearer | one-time link challenge |
|
||||
| POST | `link` | Bearer | prove wallet ownership, store mapping |
|
||||
| DELETE | `link/:address` | Bearer | unlink |
|
||||
| GET | `names?addresses=a,b` | none | leaderboard display names (`preferred_username`, else `name`; never email) |
|
||||
|
||||
Signed link message (off-chain, domain-tagged):
|
||||
`["wikideck:account-link:v1", NETWORK, issuer, sub, address, nonce, expiresAt]`
|
||||
|
||||
## Node configuration
|
||||
- **`PUBLIC_ORIGIN`** must be the node's UI origin, for example `http://192.168.1.32:3101`. Otherwise the existing POST origin check returns 403.
|
||||
- **Outbound HTTPS** to `https://dex.eom.dev` is required.
|
||||
- **Optional overrides:**
|
||||
- `WIKIDECK_OIDC_ISSUER` (default `https://dex.eom.dev/`)
|
||||
- `WIKIDECK_OIDC_CLIENT_ID` (default `wikideck`)
|
||||
- `WIKIDECK_OIDC_REDIRECT_URIS` (comma-separated; must match the Dex registration)
|
||||
- **Storage:** `$WIKIDECK_DATA_DIR/accounts.sqlite`.
|
||||
|
||||
## Capacitor
|
||||
- The UI is bundled locally, so set `globalThis.WIKIDECK_NODE_URL = 'http://192.168.1.32:3101'` before using `src/auth`. That node's POST origin check must allow the app's WebView origin.
|
||||
- Register the URL scheme `dev.eom.wikideck`.
|
||||
- Install `@capacitor/browser` and `@capacitor/app`.
|
||||
- Add the listener:
|
||||
```ts
|
||||
App.addListener('appUrlOpen', ({ url }) => { if (isCallback(url)) void completeLogin(url); });
|
||||
```
|
||||
|
||||
## Known limits
|
||||
- **Logout is local.** Dex publishes no `end_session_endpoint`, so its SSO cookie remains.
|
||||
- **ID tokens aren't refreshed.** The default Dex lifetime is 24 h; after that, log in again.
|
||||
- **Challenges live in memory.** A node restart drops pending challenges, so the client just asks again.
|
||||
@@ -0,0 +1,141 @@
|
||||
import { createPublicKey, verify, type JsonWebKey, type KeyObject } from 'node:crypto';
|
||||
|
||||
// eom.dev accounts through Dex. WikiDeck is a *public* OIDC client (PKCE, no secret).
|
||||
// The node performs the code exchange because Dex sends no CORS headers; it then
|
||||
// verifies the ID token against Dex's JWKS. No Dex credentials live on the node.
|
||||
export type OidcConfig = {
|
||||
issuer: string;
|
||||
clientId: string;
|
||||
scopes: string;
|
||||
/** Exact redirect URIs the node will pass to Dex (Dex enforces its own allowlist too). */
|
||||
redirectUris: string[];
|
||||
/** Allowed clock skew, seconds. */
|
||||
skew: number;
|
||||
};
|
||||
|
||||
export function oidcConfig(env: NodeJS.ProcessEnv = process.env): OidcConfig {
|
||||
const issuer = env.WIKIDECK_OIDC_ISSUER ?? 'https://dex.eom.dev/';
|
||||
const redirectUris = (env.WIKIDECK_OIDC_REDIRECT_URIS ??
|
||||
'http://192.168.1.32:3101/auth/callback,http://192.168.1.32:3102/auth/callback,' +
|
||||
'http://192.168.1.32:3103/auth/callback,dev.eom.wikideck:/oauth/callback')
|
||||
.split(',').map(s => s.trim()).filter(Boolean);
|
||||
return { issuer, clientId: env.WIKIDECK_OIDC_CLIENT_ID ?? 'wikideck',
|
||||
scopes: 'openid profile email groups', redirectUris, skew: 60 };
|
||||
}
|
||||
|
||||
export type Discovery = { issuer: string; authorization_endpoint: string; token_endpoint: string; jwks_uri: string };
|
||||
export type IdClaims = {
|
||||
iss: string; sub: string; aud: string | string[]; exp: number; iat: number; nbf?: number;
|
||||
azp?: string; nonce?: string; name?: string; preferred_username?: string; email?: string;
|
||||
email_verified?: boolean; groups?: string[];
|
||||
};
|
||||
|
||||
export class TokenError extends Error { readonly status = 401; }
|
||||
|
||||
const b64url = (s: string) => Buffer.from(s, 'base64url');
|
||||
function decodeJson(part: string): Record<string, unknown> {
|
||||
if (!/^[A-Za-z0-9_-]+$/.test(part)) throw new TokenError('Malformed token');
|
||||
const value = JSON.parse(b64url(part).toString('utf8'));
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TokenError('Malformed token');
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** Fetches and caches the discovery document and JWKS; refreshes keys on an unknown kid (rotation). */
|
||||
export class DexKeys {
|
||||
private discovery?: Promise<Discovery>;
|
||||
private keys = new Map<string, KeyObject>();
|
||||
private fetchedAt = 0;
|
||||
readonly config: OidcConfig;
|
||||
private readonly fetcher: typeof fetch;
|
||||
private readonly now: () => number;
|
||||
constructor(config: OidcConfig, fetcher: typeof fetch = fetch, now: () => number = Date.now) {
|
||||
this.config = config; this.fetcher = fetcher; this.now = now;
|
||||
}
|
||||
|
||||
async meta(): Promise<Discovery> {
|
||||
this.discovery ??= (async () => {
|
||||
const url = new URL('.well-known/openid-configuration', this.config.issuer.endsWith('/') ? this.config.issuer : this.config.issuer + '/');
|
||||
const res = await this.fetcher(url, { signal: AbortSignal.timeout(8000) });
|
||||
if (!res.ok) throw new Error('OIDC discovery failed');
|
||||
const doc = await res.json() as Discovery;
|
||||
// Issuer in discovery must match exactly (OIDC Discovery §4.3).
|
||||
if (doc.issuer !== this.config.issuer) throw new Error('OIDC discovery issuer mismatch');
|
||||
return doc;
|
||||
})().catch(e => { this.discovery = undefined; throw e; });
|
||||
return this.discovery;
|
||||
}
|
||||
|
||||
async key(kid: string): Promise<KeyObject | undefined> {
|
||||
const cached = this.keys.get(kid);
|
||||
if (cached) return cached;
|
||||
// Rate-limit refetches so random kids can't hammer Dex.
|
||||
if (this.now() - this.fetchedAt < 30_000 && this.keys.size) return undefined;
|
||||
await this.refresh();
|
||||
return this.keys.get(kid);
|
||||
}
|
||||
|
||||
async refresh(): Promise<void> {
|
||||
const { jwks_uri } = await this.meta();
|
||||
const res = await this.fetcher(jwks_uri, { signal: AbortSignal.timeout(8000) });
|
||||
if (!res.ok) throw new Error('JWKS fetch failed');
|
||||
const { keys } = await res.json() as { keys: (JsonWebKey & { kid?: string; use?: string; alg?: string })[] };
|
||||
const next = new Map<string, KeyObject>();
|
||||
for (const jwk of keys ?? []) {
|
||||
if (!jwk.kid || jwk.kty !== 'RSA' || (jwk.use && jwk.use !== 'sig') || (jwk.alg && jwk.alg !== 'RS256')) continue;
|
||||
try { next.set(jwk.kid, createPublicKey({ key: jwk, format: 'jwk' })); } catch { /* skip bad key */ }
|
||||
}
|
||||
this.keys = next; this.fetchedAt = this.now();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies a compact JWS ID token: RS256 only, signature against JWKS, exact issuer,
|
||||
* audience contains our client (azp must be us when there are several), exp/nbf/iat with skew,
|
||||
* and the nonce when one is expected.
|
||||
*/
|
||||
export async function verifyIdToken(token: string, keys: Pick<DexKeys, 'key'>, config: OidcConfig,
|
||||
opts: { now?: number; nonce?: string } = {}): Promise<IdClaims> {
|
||||
if (typeof token !== 'string' || token.length > 8192) throw new TokenError('Malformed token');
|
||||
const parts = token.split('.');
|
||||
if (parts.length !== 3) throw new TokenError('Malformed token');
|
||||
let header: Record<string, unknown>, claims: Record<string, unknown>;
|
||||
try { header = decodeJson(parts[0]); claims = decodeJson(parts[1]); }
|
||||
catch (e) { throw e instanceof TokenError ? e : new TokenError('Malformed token'); }
|
||||
if (header.alg !== 'RS256') throw new TokenError('Unsupported token algorithm');
|
||||
if (typeof header.kid !== 'string') throw new TokenError('Token key id missing');
|
||||
const key = await keys.key(header.kid);
|
||||
if (!key) throw new TokenError('Unknown token signing key');
|
||||
if (!/^[A-Za-z0-9_-]+$/.test(parts[2]) ||
|
||||
!verify('sha256', Buffer.from(`${parts[0]}.${parts[1]}`), key, b64url(parts[2])))
|
||||
throw new TokenError('Invalid token signature');
|
||||
const now = Math.floor((opts.now ?? Date.now()) / 1000);
|
||||
if (claims.iss !== config.issuer) throw new TokenError('Wrong token issuer');
|
||||
const aud = Array.isArray(claims.aud) ? claims.aud : [claims.aud];
|
||||
if (!aud.includes(config.clientId)) throw new TokenError('Wrong token audience');
|
||||
if (aud.length > 1 && claims.azp !== config.clientId) throw new TokenError('Wrong token authorized party');
|
||||
if (typeof claims.sub !== 'string' || !claims.sub || claims.sub.length > 512) throw new TokenError('Token subject missing');
|
||||
if (typeof claims.exp !== 'number' || now - config.skew >= claims.exp) throw new TokenError('Token expired');
|
||||
if (typeof claims.iat !== 'number' || claims.iat > now + config.skew) throw new TokenError('Token issued in the future');
|
||||
if (typeof claims.nbf === 'number' && claims.nbf > now + config.skew) throw new TokenError('Token not yet valid');
|
||||
if (opts.nonce !== undefined && claims.nonce !== opts.nonce) throw new TokenError('Token nonce mismatch');
|
||||
return claims as unknown as IdClaims;
|
||||
}
|
||||
|
||||
/** Authorization-code exchange as a public client (no secret), with the PKCE verifier. */
|
||||
export async function exchangeCode(keys: DexKeys, input: { code: string; codeVerifier: string; redirectUri: string },
|
||||
fetcher: typeof fetch = fetch): Promise<{ idToken: string }> {
|
||||
const { token_endpoint } = await keys.meta();
|
||||
const res = await fetcher(token_endpoint, { method: 'POST', signal: AbortSignal.timeout(10000),
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
|
||||
body: new URLSearchParams({ grant_type: 'authorization_code', client_id: keys.config.clientId,
|
||||
code: input.code, code_verifier: input.codeVerifier, redirect_uri: input.redirectUri }) });
|
||||
const body = await res.json().catch(() => ({})) as { id_token?: string; error?: string };
|
||||
if (!res.ok || typeof body.id_token !== 'string') throw new TokenError(`Login failed${body.error ? `: ${String(body.error).slice(0, 60)}` : ''}`);
|
||||
return { idToken: body.id_token };
|
||||
}
|
||||
|
||||
/** Display name used on leaderboards: the eom.dev username, else name; never the email address. */
|
||||
export function displayName(claims: Pick<IdClaims, 'name' | 'preferred_username' | 'sub'>): string {
|
||||
const raw = (claims.preferred_username || claims.name || `player-${claims.sub.slice(0, 6)}`).normalize('NFKC');
|
||||
return raw.replace(/[\u0000-\u001f\u007f]/g, '').trim().slice(0, 48) || 'player';
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { Router, type Request, type Response, type NextFunction } from 'express';
|
||||
import { resolve } from 'node:path';
|
||||
import { z } from 'zod';
|
||||
import { DexKeys, TokenError, displayName, exchangeCode, oidcConfig, verifyIdToken, type OidcConfig } from './oidc.ts';
|
||||
import { AccountStore, LinkError, type Account } from './store.ts';
|
||||
|
||||
// Mounted at /api/account by server/testnet/http.ts. Body parsing, the POST origin check,
|
||||
// rate limits and no-store caching come from the /api middleware there.
|
||||
export type AccountDeps = { config?: OidcConfig; keys?: DexKeys; store?: AccountStore; dataDir?: string;
|
||||
fetcher?: typeof fetch; now?: () => number };
|
||||
|
||||
type Authed = Request & { account?: Account };
|
||||
const hex64 = z.string().regex(/^[a-f0-9]{64}$/);
|
||||
|
||||
export function createAccountRouter(deps: AccountDeps = {}): Router {
|
||||
const config = deps.config ?? oidcConfig();
|
||||
const now = deps.now ?? Date.now;
|
||||
const keys = deps.keys ?? new DexKeys(config, deps.fetcher, now);
|
||||
const store = deps.store ?? new AccountStore(resolve(deps.dataDir ?? 'data', 'accounts.sqlite'), now);
|
||||
const router = Router();
|
||||
|
||||
const toAccount = (claims: Awaited<ReturnType<typeof verifyIdToken>>): Account =>
|
||||
({ sub: claims.sub, issuer: claims.iss, name: displayName(claims), username: claims.preferred_username ?? '' });
|
||||
|
||||
const auth = async (req: Authed, _res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const m = /^Bearer ([A-Za-z0-9_.-]+)$/.exec(req.get('authorization') ?? '');
|
||||
if (!m) throw new TokenError('Log in with your eom.dev account');
|
||||
req.account = toAccount(await verifyIdToken(m[1], keys, config, { now: now() }));
|
||||
store.upsert(req.account);
|
||||
next();
|
||||
} catch (e) { next(e); }
|
||||
};
|
||||
|
||||
// Public, so the browser builds the authorize URL without fetching Dex (no CSP/CORS change).
|
||||
router.get('/config', async (_req, res, next) => {
|
||||
try {
|
||||
const meta = await keys.meta();
|
||||
res.json({ issuer: config.issuer, clientId: config.clientId, scopes: config.scopes,
|
||||
authorizationEndpoint: meta.authorization_endpoint, redirectUris: config.redirectUris });
|
||||
} catch (e) { next(e); }
|
||||
});
|
||||
|
||||
router.post('/token', async (req, res, next) => {
|
||||
try {
|
||||
const body = z.object({ code: z.string().min(1).max(512), codeVerifier: z.string().regex(/^[A-Za-z0-9._~-]{43,128}$/),
|
||||
redirectUri: z.string().max(256), nonce: z.string().min(16).max(128) }).strict().parse(req.body);
|
||||
if (!config.redirectUris.includes(body.redirectUri)) throw new LinkError('Redirect URI not allowed');
|
||||
const { idToken } = await exchangeCode(keys, body, deps.fetcher);
|
||||
const claims = await verifyIdToken(idToken, keys, config, { now: now(), nonce: body.nonce });
|
||||
const account = toAccount(claims);
|
||||
store.upsert(account);
|
||||
res.json({ idToken, expiresAt: claims.exp * 1000, account: { ...account, wallets: store.wallets(account.sub) } });
|
||||
} catch (e) { next(e); }
|
||||
});
|
||||
|
||||
router.get('/me', auth, (req: Authed, res) => {
|
||||
const a = req.account!;
|
||||
res.json({ ...a, wallets: store.wallets(a.sub) });
|
||||
});
|
||||
|
||||
router.post('/challenge', auth, (req: Authed, res, next) => {
|
||||
try {
|
||||
const { address } = z.object({ address: hex64 }).strict().parse(req.body);
|
||||
res.json(store.challenge(req.account!, address));
|
||||
} catch (e) { next(e); }
|
||||
});
|
||||
|
||||
// Wallet keys never leave the client: only the public key and a signature arrive here.
|
||||
router.post('/link', auth, (req: Authed, res, next) => {
|
||||
try {
|
||||
const body = z.object({ nonce: z.string().regex(/^[A-Za-z0-9_-]{16,64}$/), address: hex64,
|
||||
publicKey: z.string().max(256), signature: z.string().max(256) }).strict().parse(req.body);
|
||||
res.status(201).json(store.link(req.account!, body));
|
||||
} catch (e) { next(e); }
|
||||
});
|
||||
|
||||
router.delete('/link/:address', auth, (req: Authed, res) => {
|
||||
const address = String(req.params.address);
|
||||
if (!/^[a-f0-9]{64}$/.test(address)) { res.status(400).json({ error: 'Invalid wallet address' }); return; }
|
||||
res.json({ removed: store.unlink(req.account!.sub, address) });
|
||||
});
|
||||
|
||||
// Leaderboards: GET /api/account/names?addresses=a,b,c → { [address]: displayName }
|
||||
router.get('/names', (req, res) => {
|
||||
const list = String(req.query.addresses ?? '').split(',').filter(Boolean);
|
||||
if (list.length > 100 || !list.every(a => /^[a-f0-9]{64}$/.test(a))) { res.status(400).json({ error: 'Invalid addresses' }); return; }
|
||||
res.json({ names: store.names(list) });
|
||||
});
|
||||
|
||||
router.use((err: Error & { status?: number }, _req: Request, res: Response, _next: NextFunction) => {
|
||||
if (err instanceof TokenError || err instanceof LinkError) { res.status(err.status).json({ error: err.message }); return; }
|
||||
if (err instanceof z.ZodError) { res.status(400).json({ error: 'Invalid request' }); return; }
|
||||
if (/OIDC|JWKS/.test(err.message) || err.name === 'TimeoutError' || err.message === 'fetch failed') { res.status(503).json({ error: 'eom.dev login is temporarily unavailable' }); return; }
|
||||
res.status(err.status === 413 ? 413 : 400).json({ error: 'Account request failed' });
|
||||
});
|
||||
return router;
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { address as walletAddress, verifySignature } from '../testnet/consensus.ts';
|
||||
import { linkMessage } from '../../shared/account-link.ts';
|
||||
|
||||
export { linkMessage };
|
||||
|
||||
// Off-chain account <-> wallet mapping. Nothing here touches the chain or consensus.
|
||||
export type Account = { sub: string; issuer: string; name: string; username: string };
|
||||
export type LinkedWallet = { address: string; linkedAt: number };
|
||||
|
||||
export const CHALLENGE_TTL_MS = 5 * 60_000;
|
||||
export const MAX_PENDING_PER_ACCOUNT = 5;
|
||||
|
||||
export class LinkError extends Error {
|
||||
readonly status: number;
|
||||
constructor(message: string, status = 400) { super(message); this.status = status; }
|
||||
}
|
||||
|
||||
export class AccountStore {
|
||||
private readonly db: DatabaseSync;
|
||||
private readonly challenges = new Map<string, { sub: string; address: string; expiresAt: number }>();
|
||||
private readonly now: () => number;
|
||||
constructor(file: string, now: () => number = Date.now) {
|
||||
this.now = now;
|
||||
this.db = new DatabaseSync(file);
|
||||
this.db.exec(`PRAGMA journal_mode=WAL;
|
||||
CREATE TABLE IF NOT EXISTS accounts(sub TEXT PRIMARY KEY, issuer TEXT NOT NULL, name TEXT NOT NULL,
|
||||
username TEXT NOT NULL, updated_at INTEGER NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS wallets(address TEXT PRIMARY KEY, sub TEXT NOT NULL REFERENCES accounts(sub),
|
||||
public_key TEXT NOT NULL, linked_at INTEGER NOT NULL);
|
||||
CREATE INDEX IF NOT EXISTS wallets_sub ON wallets(sub);`);
|
||||
}
|
||||
close() { this.db.close(); }
|
||||
|
||||
upsert(a: Account): void {
|
||||
this.db.prepare(`INSERT INTO accounts(sub,issuer,name,username,updated_at) VALUES(?,?,?,?,?)
|
||||
ON CONFLICT(sub) DO UPDATE SET name=excluded.name, username=excluded.username, updated_at=excluded.updated_at`)
|
||||
.run(a.sub, a.issuer, a.name, a.username, this.now());
|
||||
}
|
||||
|
||||
wallets(sub: string): LinkedWallet[] {
|
||||
return (this.db.prepare('SELECT address, linked_at FROM wallets WHERE sub=? ORDER BY linked_at').all(sub) as
|
||||
{ address: string; linked_at: number }[]).map(r => ({ address: r.address, linkedAt: r.linked_at }));
|
||||
}
|
||||
|
||||
/** Public leaderboard lookup: display names only, for linked wallets. */
|
||||
names(addresses: string[]): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
const q = this.db.prepare('SELECT a.name FROM wallets w JOIN accounts a ON a.sub=w.sub WHERE w.address=?');
|
||||
for (const addr of addresses) { const row = q.get(addr) as { name: string } | undefined; if (row) out[addr] = row.name; }
|
||||
return out;
|
||||
}
|
||||
|
||||
challenge(account: Account, address: string): { nonce: string; expiresAt: number; message: string } {
|
||||
if (!/^[a-f0-9]{64}$/.test(address)) throw new LinkError('Invalid wallet address');
|
||||
const now = this.now();
|
||||
for (const [k, v] of this.challenges) if (v.expiresAt <= now) this.challenges.delete(k);
|
||||
if (this.challenges.size > 10_000) throw new LinkError('Too many pending link challenges', 503);
|
||||
let mine = 0; for (const v of this.challenges.values()) if (v.sub === account.sub) mine++;
|
||||
if (mine >= MAX_PENDING_PER_ACCOUNT) throw new LinkError('Too many pending link challenges for this account; wait a few minutes', 429);
|
||||
const nonce = randomBytes(24).toString('base64url');
|
||||
const expiresAt = now + CHALLENGE_TTL_MS;
|
||||
this.challenges.set(nonce, { sub: account.sub, address, expiresAt });
|
||||
return { nonce, expiresAt, message: linkMessage({ issuer: account.issuer, sub: account.sub, address, nonce, expiresAt }) };
|
||||
}
|
||||
|
||||
/** Verifies the wallet signature over the challenge; each nonce is single use. */
|
||||
link(account: Account, input: { nonce: string; address: string; publicKey: string; signature: string }): LinkedWallet {
|
||||
const pending = this.challenges.get(input.nonce);
|
||||
// Consume before verifying: a failed attempt also burns the nonce (no oracle, no replay).
|
||||
this.challenges.delete(input.nonce);
|
||||
if (!pending || pending.expiresAt <= this.now()) throw new LinkError('Link challenge expired or already used', 409);
|
||||
if (pending.sub !== account.sub || pending.address !== input.address) throw new LinkError('Link challenge does not match this account and wallet', 409);
|
||||
if (walletAddress(input.publicKey) !== input.address) throw new LinkError('Public key does not match the wallet address');
|
||||
const message = linkMessage({ issuer: account.issuer, sub: account.sub, address: input.address, nonce: input.nonce, expiresAt: pending.expiresAt });
|
||||
if (!verifySignature(input.publicKey, input.address, message, input.signature)) throw new LinkError('Invalid wallet signature', 401);
|
||||
const owner = this.db.prepare('SELECT sub FROM wallets WHERE address=?').get(input.address) as { sub: string } | undefined;
|
||||
if (owner && owner.sub !== account.sub) throw new LinkError('This wallet is already linked to another account', 409);
|
||||
const linkedAt = this.now();
|
||||
this.db.prepare('INSERT INTO wallets(address,sub,public_key,linked_at) VALUES(?,?,?,?) ON CONFLICT(address) DO NOTHING')
|
||||
.run(input.address, account.sub, input.publicKey, linkedAt);
|
||||
return this.wallets(account.sub).find(w => w.address === input.address)!;
|
||||
}
|
||||
|
||||
unlink(sub: string, address: string): boolean {
|
||||
return Number(this.db.prepare('DELETE FROM wallets WHERE sub=? AND address=?').run(sub, address).changes) > 0;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from 'zod';
|
||||
import { ENRICHMENT_USER_AGENT, wikimediaUserAgent } from './wikimedia-user-agent.ts';
|
||||
import { deriveStats, type PageEnrichment } from '../shared/enrichment.ts';
|
||||
|
||||
const MAX_BYTES = 1024 * 1024;
|
||||
@@ -101,7 +102,7 @@ export class WikipediaEnrichment {
|
||||
private async json(url: URL): Promise<unknown> {
|
||||
const signal = AbortSignal.timeout(6000);
|
||||
const response = await this.fetcher(url, { signal, redirect: 'error',
|
||||
headers: { Accept: 'application/json', 'User-Agent': 'Wikideck/0.1 (Wikipedia off-chain page enrichment)' } });
|
||||
headers: { Accept: 'application/json', 'User-Agent': wikimediaUserAgent(ENRICHMENT_USER_AGENT) } });
|
||||
const length = response.headers.get('content-length');
|
||||
if (!response.ok || response.redirected ||
|
||||
!/^application\/json(?:\s*;|\s*$)/i.test(response.headers.get('content-type') ?? '') ||
|
||||
|
||||
@@ -17,6 +17,7 @@ import { IS_MAINNET, PROFILE } from '../../shared/network.ts';
|
||||
import { assertLaunchAllowed, launchManifest } from '../launch.ts';
|
||||
import { resourceConfig, RpcBudget, RpcError } from '../resources.ts';
|
||||
import { trustedProxies, operationsPort, startOperations } from '../operations.ts';
|
||||
import { createAccountRouter } from '../account/router.ts';
|
||||
|
||||
const root = fileURLToPath(new URL('../../', import.meta.url));
|
||||
assertLaunchAllowed();
|
||||
@@ -149,6 +150,7 @@ app.post('/p2p/transaction',workLimit,async(req,res)=>{
|
||||
const id=await ledger.submitTransaction(transaction);
|
||||
res.status(202).json({id,status:'pending'});
|
||||
});
|
||||
app.use('/api/account',createAccountRouter({dataDir}));
|
||||
app.use(['/api','/p2p'],(_req,res)=>{res.status(404).json({error:'Unknown testnet endpoint'});});
|
||||
app.use(express.static(resolve(root,'dist')));
|
||||
app.get('/{*path}',(_req,res)=>res.sendFile(resolve(root,'dist/index.html')));
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
import { z } from 'zod';
|
||||
import type { Article } from '../shared/protocol.ts';
|
||||
import { ARTICLE_USER_AGENT, wikimediaUserAgent } from './wikimedia-user-agent.ts';
|
||||
|
||||
const pageSchema = z.object({
|
||||
pageid: z.number().int().positive().max(Number.MAX_SAFE_INTEGER), ns: z.literal(0),
|
||||
@@ -74,7 +75,7 @@ export class WikipediaArticleSource {
|
||||
generator: 'random', grnnamespace: '0', grnlimit: '10', prop: 'extracts|pageimages|info|categories',
|
||||
exintro: '1', explaintext: '1', exchars: '900', piprop: 'thumbnail', pithumbsize: '800', cllimit: '20' }).toString();
|
||||
const response = await this.fetcher(url, { signal: AbortSignal.timeout(3500), redirect: 'error',
|
||||
headers: { 'User-Agent': 'Wikideck/0.1 (experimental Wikipedia article cards)', Accept: 'application/json' } });
|
||||
headers: { 'User-Agent': wikimediaUserAgent(ARTICLE_USER_AGENT), Accept: 'application/json' } });
|
||||
const data = responseSchema.parse(await readJson(response));
|
||||
for (const rawPage of data.query.pages) {
|
||||
const parsedPage = pageSchema.safeParse(rawPage);
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
// User-Agent for Wikimedia API requests. Wikimedia asks automated clients to identify
|
||||
// themselves with contact information; operators can opt in with WIKIDECK_USER_AGENT.
|
||||
// Unset (or blank), each caller keeps its historical default string unchanged.
|
||||
export const ARTICLE_USER_AGENT = 'Wikideck/0.1 (experimental Wikipedia article cards)';
|
||||
export const ENRICHMENT_USER_AGENT = 'Wikideck/0.1 (Wikipedia off-chain page enrichment)';
|
||||
const MAX_LENGTH = 256;
|
||||
|
||||
export function wikimediaUserAgent(fallback: string, env: Record<string, string | undefined> = process.env): string {
|
||||
const configured = env.WIKIDECK_USER_AGENT?.trim();
|
||||
// Reject header-injection/control characters and oversized values; fall back to the default.
|
||||
if (!configured || configured.length > MAX_LENGTH || !/^[\x20-\x7e]+$/.test(configured)) return fallback;
|
||||
return configured;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { NETWORK } from './testnet.ts';
|
||||
|
||||
// Off-chain wallet <-> eom.dev account proof. Pure, shared by node and client so the
|
||||
// client builds the exact text it signs and never signs server-chosen text.
|
||||
export type LinkChallenge = { nonce: string; expiresAt: number };
|
||||
export const LINK_NONCE = /^[A-Za-z0-9_-]{16,64}$/;
|
||||
export const LINK_CHALLENGE_MAX_MS = 10 * 60_000;
|
||||
|
||||
export function linkMessage(c: { issuer: string; sub: string; address: string; nonce: string; expiresAt: number }): string {
|
||||
return JSON.stringify(['wikideck:account-link:v1', NETWORK, c.issuer, c.sub, c.address, c.nonce, c.expiresAt]);
|
||||
}
|
||||
|
||||
/** Client side: validate a node challenge and build the message locally. Throws on anything unexpected. */
|
||||
export function clientLinkMessage(account: { issuer: string; sub: string }, address: string,
|
||||
challenge: { nonce?: unknown; expiresAt?: unknown; message?: unknown }, now = Date.now()): string {
|
||||
const { nonce, expiresAt } = challenge;
|
||||
if (typeof nonce !== 'string' || !LINK_NONCE.test(nonce)) throw new Error('The node sent an invalid link challenge.');
|
||||
if (typeof expiresAt !== 'number' || !Number.isSafeInteger(expiresAt) || expiresAt <= now || expiresAt > now + LINK_CHALLENGE_MAX_MS)
|
||||
throw new Error('The node sent an invalid link challenge.');
|
||||
if (!/^[a-f0-9]{64}$/.test(address)) throw new Error('Invalid wallet address.');
|
||||
const message = linkMessage({ issuer: account.issuer, sub: account.sub, address, nonce, expiresAt });
|
||||
if (challenge.message !== undefined && challenge.message !== message)
|
||||
throw new Error('The node asked the wallet to sign something other than an account link. Nothing was signed.');
|
||||
return message;
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
/**
|
||||
* Turning WikiDeck data into GameCards, and starter decks for players with no NFTs.
|
||||
* PLACEHOLDER numbers until docs/game/DESIGN.md v1; engine-b tunes the mapping.
|
||||
* Starter cards are offline preview cards: not NFTs, never minted or moved.
|
||||
*/
|
||||
import { Rng } from './rng.ts';
|
||||
import { DEFAULT_RULESET } from './ruleset.ts';
|
||||
import type { Category, GameCard, Ruleset } from './types.ts';
|
||||
|
||||
type StarterSpec = [pageId: number, name: string, category: Category, cost: number, power: number, keyword: string | null];
|
||||
|
||||
/** 24 curated preview cards, 4 per cost 1–6. pageIds outside shared/catalog.ts are unverified (display only). */
|
||||
export const STARTER_POOL: readonly StarterSpec[] = [
|
||||
[22780, 'Octopus', 'Nature', 1, 2, null],
|
||||
[19331, 'Moon', 'Space', 1, 1, 'anchor'],
|
||||
[23053, 'Periodic table', 'Science', 1, 2, null],
|
||||
[3383, 'Bronze Age', 'History', 1, 1, 'rally'],
|
||||
[5843419, 'Chess', 'Culture', 2, 3, null],
|
||||
[9228, 'Earth', 'Space', 2, 2, 'rally'],
|
||||
[2008, 'Ada Lovelace', 'People', 2, 4, null],
|
||||
[21830, 'Honey bee', 'Nature', 2, 3, 'anchor'],
|
||||
[736, 'Albert Einstein', 'People', 3, 5, null],
|
||||
[10979, 'Fungus', 'Nature', 3, 4, 'rally'],
|
||||
[26903, 'Solar System', 'Space', 3, 6, null],
|
||||
[30758, 'Roman Empire', 'History', 3, 4, 'anchor'],
|
||||
[9649, 'Evolution', 'Science', 4, 7, null],
|
||||
[8424, 'Jazz', 'Culture', 4, 6, 'rally'],
|
||||
[12898, 'Marie Curie', 'People', 4, 8, null],
|
||||
[14533, 'Silk Road', 'History', 4, 6, 'anchor'],
|
||||
[19468, 'Mount Everest', 'Nature', 5, 9, null],
|
||||
[22936, 'Photosynthesis', 'Science', 5, 8, 'rally'],
|
||||
[18110, 'Leonardo da Vinci', 'People', 5, 10, null],
|
||||
[14627, 'Ancient Egypt', 'History', 5, 8, 'anchor'],
|
||||
[4177, 'Black hole', 'Space', 6, 12, null],
|
||||
[25443, 'Quantum mechanics', 'Science', 6, 11, 'rally'],
|
||||
[17867, 'Library of Alexandria', 'History', 6, 11, 'anchor'],
|
||||
[20217, 'Music', 'Culture', 6, 12, null],
|
||||
];
|
||||
|
||||
export function starterCard(spec: StarterSpec, copy = 0): GameCard {
|
||||
const [pageId, name, category, cost, power, keyword] = spec;
|
||||
return { id: `starter:${pageId}:${copy}`, name, pageId, category, cost, power, keyword, source: 'starter' };
|
||||
}
|
||||
|
||||
/**
|
||||
* A deterministic starter deck: 2 cards of each cost 1–6 (for a 12-card deck),
|
||||
* drawn from STARTER_POOL by `seed`. Cards whose keyword the ruleset doesn't
|
||||
* enable still play (as vanilla). Fills to ruleset.deck.min.
|
||||
*/
|
||||
export function starterDeck(seed: string, rules: Ruleset = DEFAULT_RULESET): GameCard[] {
|
||||
const rng = Rng.fromSeed(`starter:${seed}`);
|
||||
const byCost = new Map<number, StarterSpec[]>();
|
||||
for (const spec of STARTER_POOL) byCost.set(spec[3], [...(byCost.get(spec[3]) ?? []), spec]);
|
||||
const picks: StarterSpec[] = [];
|
||||
const costs = [...byCost.keys()].sort((a, b) => a - b);
|
||||
for (const cost of costs) picks.push(...rng.shuffle(byCost.get(cost)!).slice(0, 2));
|
||||
const deck = rng.shuffle(picks).slice(0, rules.deck.max).map(spec => starterCard(spec));
|
||||
// Pad for modes with bigger decks, respecting maxCopiesPerPage.
|
||||
let copy = 1;
|
||||
while (deck.length < rules.deck.min && copy < rules.deck.maxCopiesPerPage) {
|
||||
for (const spec of rng.shuffle(STARTER_POOL)) {
|
||||
if (deck.length >= rules.deck.min) break;
|
||||
deck.push(starterCard(spec, copy));
|
||||
}
|
||||
copy++;
|
||||
}
|
||||
return deck;
|
||||
}
|
||||
|
||||
/** Input for an owned card; matches PageEnrichment / MintStatsSnapshot fields (shared/enrichment.ts). */
|
||||
export interface CardSource {
|
||||
id: string;
|
||||
title: string;
|
||||
pageId: number;
|
||||
category: Category;
|
||||
stats: { attention: number | null; depth: number; reach: number };
|
||||
}
|
||||
|
||||
/**
|
||||
* PLACEHOLDER stat → card mapping (DESIGN.md will replace it). Famous cards cost
|
||||
* more (sidegrade): cost from the mean score, power = 2·cost (+1 if no keyword).
|
||||
*/
|
||||
export function cardFromStats(source: CardSource): GameCard {
|
||||
const { attention, depth, reach } = source.stats;
|
||||
const mean = ((attention ?? 0) + depth + reach) / 3;
|
||||
const cost = Math.max(1, Math.min(6, Math.ceil(mean / (100 / 6))));
|
||||
const keyword = depth >= reach && depth >= (attention ?? 0) ? 'anchor' : reach >= (attention ?? 0) ? 'rally' : null;
|
||||
return {
|
||||
id: source.id, name: source.title, pageId: source.pageId, category: source.category,
|
||||
cost, power: 2 * cost + (keyword ? 0 : 1), keyword, source: 'owned',
|
||||
};
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
/**
|
||||
* Card derivation (DESIGN.md §1): a frozen CardInput becomes a GameCard.
|
||||
* Pure and deterministic. The engine never reads raw 0–100 stats as power.
|
||||
*/
|
||||
export type Stat = 'attention' | 'depth' | 'reach';
|
||||
export type Faction = 'Space' | 'Nature' | 'People' | 'Science' | 'History' | 'Culture';
|
||||
export type Rarity = 'Legendary' | 'Epic' | 'Rare' | 'Common';
|
||||
|
||||
export const STATS: readonly Stat[] = ['attention', 'depth', 'reach'];
|
||||
export const FACTIONS: readonly Faction[] = ['Space', 'Nature', 'People', 'Science', 'History', 'Culture'];
|
||||
/** §1.4 tie-break order: depth and reach are the hardest to inflate. */
|
||||
export const HOME_TIE_ORDER: readonly Stat[] = ['depth', 'reach', 'attention'];
|
||||
|
||||
export interface CardInput {
|
||||
cardId: string;
|
||||
pageId: number;
|
||||
title: string;
|
||||
category: Faction;
|
||||
rarity: Rarity;
|
||||
snapshot: { stats: { attention: number | null; depth: number; reach: number } };
|
||||
/** Frozen by the host at match start. */
|
||||
live: { trendPercent: number | null };
|
||||
}
|
||||
|
||||
export interface GameCard {
|
||||
cardId: string;
|
||||
pageId: number;
|
||||
title: string;
|
||||
faction: Faction;
|
||||
rarity: Rarity;
|
||||
cost: number;
|
||||
power: number;
|
||||
home: Stat;
|
||||
trend: -1 | 0 | 1;
|
||||
keyword: string | null;
|
||||
}
|
||||
|
||||
/** 99 ascending cut points per stat (§1.1). */
|
||||
export type PercentileTable = Record<Stat, readonly number[]>;
|
||||
|
||||
/** The subset of the rules config that card derivation reads. */
|
||||
export interface DerivationRules {
|
||||
costThresholds: readonly number[];
|
||||
powerByCost: readonly number[];
|
||||
trendUp: number;
|
||||
trendDown: number;
|
||||
}
|
||||
|
||||
export type KeywordPicker = (card: Omit<GameCard, 'keyword'>) => string | null;
|
||||
|
||||
/** §1.1: cut points strictly below, plus half of those equal, rounded down. */
|
||||
export function percentile(score: number, cuts: readonly number[]): number {
|
||||
let below = 0, equal = 0;
|
||||
for (const cut of cuts) {
|
||||
if (cut < score) below++;
|
||||
else if (cut === score) equal++;
|
||||
}
|
||||
return Math.floor(below + equal / 2);
|
||||
}
|
||||
|
||||
export function percentiles(stats: CardInput['snapshot']['stats'], table: PercentileTable): Record<Stat, number | null> {
|
||||
return {
|
||||
attention: stats.attention === null ? null : percentile(stats.attention, table.attention),
|
||||
depth: percentile(stats.depth, table.depth),
|
||||
reach: percentile(stats.reach, table.reach),
|
||||
};
|
||||
}
|
||||
|
||||
/** §1.2: integer mean of the non-null percentiles, rounded half up. */
|
||||
export function fame(pct: Record<Stat, number | null>): number {
|
||||
const values = STATS.map(stat => pct[stat]).filter((value): value is number => value !== null);
|
||||
const sum = values.reduce((total, value) => total + value, 0);
|
||||
return Math.floor(sum / values.length + 0.5);
|
||||
}
|
||||
|
||||
/** §1.2: 1 + the number of thresholds ≤ fame. */
|
||||
export function costFor(fameValue: number, thresholds: readonly number[]): number {
|
||||
return 1 + thresholds.filter(threshold => threshold <= fameValue).length;
|
||||
}
|
||||
|
||||
/** §1.4: highest percentile, ties by depth > reach > attention; null never wins. */
|
||||
export function homeStat(pct: Record<Stat, number | null>): Stat {
|
||||
let best: Stat = HOME_TIE_ORDER[0];
|
||||
for (const stat of HOME_TIE_ORDER) {
|
||||
const value = pct[stat];
|
||||
const current = pct[best];
|
||||
if (value !== null && (current === null || value > current)) best = stat;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/** §1.6: ±1 past the thresholds, null → 0. */
|
||||
export function trendFor(trendPercent: number | null, rules: Pick<DerivationRules, 'trendUp' | 'trendDown'>): -1 | 0 | 1 {
|
||||
if (trendPercent === null || !Number.isFinite(trendPercent)) return 0;
|
||||
if (trendPercent >= rules.trendUp) return 1;
|
||||
if (trendPercent <= rules.trendDown) return -1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
export function deriveCard(input: CardInput, rules: DerivationRules, table: PercentileTable,
|
||||
pickKeyword: KeywordPicker = () => null): GameCard {
|
||||
const pct = percentiles(input.snapshot.stats, table);
|
||||
const cost = costFor(fame(pct), rules.costThresholds);
|
||||
const power = rules.powerByCost[cost];
|
||||
if (power === undefined) throw new RangeError(`powerByCost has no entry for cost ${cost}`);
|
||||
const base = {
|
||||
cardId: input.cardId, pageId: input.pageId, title: input.title,
|
||||
faction: input.category, rarity: input.rarity,
|
||||
cost, power, home: homeStat(pct), trend: trendFor(input.live.trendPercent, rules),
|
||||
};
|
||||
return { ...base, keyword: pickKeyword(base) };
|
||||
}
|
||||
@@ -1,324 +0,0 @@
|
||||
/**
|
||||
* WikiDeck game engine core: pure, deterministic, off-chain.
|
||||
* Every exported function treats its inputs as immutable and returns new data.
|
||||
* All randomness comes from the match seed via state.rng.
|
||||
* Contract: docs/game/ENGINE_API.md.
|
||||
*/
|
||||
import { KEYWORDS, LANE_MODIFIERS, type EffectContext } from './keywords.ts';
|
||||
import { Rng, seedRng } from './rng.ts';
|
||||
import { energyForTurn, parseRuleset } from './ruleset.ts';
|
||||
import {
|
||||
IllegalActionError, PLAYERS,
|
||||
type Action, type CardInPlay, type GameCard, type MatchResult, type MatchState,
|
||||
type PlayerId, type PlayerState, type PlayerView, type Ruleset,
|
||||
} from './types.ts';
|
||||
|
||||
export const ENGINE_VERSION = 1;
|
||||
|
||||
const other = (player: PlayerId): PlayerId => (player === 0 ? 1 : 0);
|
||||
const clone = <T>(value: T): T => structuredClone(value);
|
||||
|
||||
// ---------- validation ----------
|
||||
|
||||
export function validateDeck(rules: Ruleset, deck: readonly GameCard[]): string[] {
|
||||
const problems: string[] = [];
|
||||
if (deck.length < rules.deck.min || deck.length > rules.deck.max)
|
||||
problems.push(`Deck must have ${rules.deck.min === rules.deck.max ? rules.deck.min : `${rules.deck.min}–${rules.deck.max}`} cards (has ${deck.length})`);
|
||||
const ids = new Set<string>();
|
||||
const copies = new Map<number, number>();
|
||||
for (const card of deck) {
|
||||
if (typeof card?.id !== 'string' || !card.id || card.id.length > 128) { problems.push('Card id must be a non-empty string'); continue; }
|
||||
if (ids.has(card.id)) problems.push(`Duplicate card id ${card.id}`);
|
||||
ids.add(card.id);
|
||||
if (!Number.isInteger(card.cost) || card.cost < 0 || card.cost > 20) problems.push(`Card ${card.id}: bad cost`);
|
||||
if (!Number.isInteger(card.power) || card.power < -100 || card.power > 100) problems.push(`Card ${card.id}: bad power`);
|
||||
if (card.pageId !== null) {
|
||||
const n = (copies.get(card.pageId) ?? 0) + 1;
|
||||
copies.set(card.pageId, n);
|
||||
if (n === rules.deck.maxCopiesPerPage + 1) problems.push(`More than ${rules.deck.maxCopiesPerPage} copies of page ${card.pageId}`);
|
||||
}
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
// ---------- match setup ----------
|
||||
|
||||
/**
|
||||
* Start a match. `decks[0]` belongs to player 0. Throws IllegalActionError for an
|
||||
* invalid deck and ZodError for an invalid ruleset.
|
||||
*/
|
||||
export function createMatch(ruleset: Ruleset, decks: readonly [readonly GameCard[], readonly GameCard[]], seed: string): MatchState {
|
||||
const rules = parseRuleset(clone(ruleset));
|
||||
if (typeof seed !== 'string' || !seed) throw new IllegalActionError('Seed must be a non-empty string');
|
||||
for (const player of PLAYERS) {
|
||||
const problems = validateDeck(rules, decks[player] ?? []);
|
||||
if (problems.length) throw new IllegalActionError(`Player ${player} deck: ${problems.join('; ')}`);
|
||||
}
|
||||
const rng = new Rng(seedRng(seed));
|
||||
const modifiers = rules.laneModifiers.pool.length ? rng.shuffle(rules.laneModifiers.pool).slice(0, rules.lanes) : [];
|
||||
const newPlayer = (player: PlayerId): PlayerState => ({
|
||||
deck: rng.shuffle(clone(decks[player])), hand: [], energy: 0, staged: [], ended: false, discard: [],
|
||||
});
|
||||
const players: [PlayerState, PlayerState] = [newPlayer(0), newPlayer(1)];
|
||||
const state: MatchState = {
|
||||
schema: 'wikideck-match/1', ruleset: rules, seed, rng: rng.state, turn: 0, phase: 'planning',
|
||||
firstToReveal: rng.int(2) as PlayerId, players,
|
||||
lanes: Array.from({ length: rules.lanes }, (_, lane) => ({ modifier: modifiers[lane] ?? null, cards: [[], []] as [CardInPlay[], CardInPlay[]] })),
|
||||
log: [], actions: [], result: null,
|
||||
};
|
||||
for (const player of PLAYERS) for (let i = 0; i < rules.hand.start; i++) draw(state, player);
|
||||
startTurn(state, rng);
|
||||
state.rng = rng.state;
|
||||
return state;
|
||||
}
|
||||
|
||||
function draw(state: MatchState, player: PlayerId): void {
|
||||
const p = state.players[player];
|
||||
if (!p.deck.length || p.hand.length >= state.ruleset.hand.max) return;
|
||||
const card = p.deck.shift()!;
|
||||
p.hand.push(card);
|
||||
state.log.push({ t: 'draw', player, cardId: card.id });
|
||||
}
|
||||
|
||||
function startTurn(state: MatchState, rng: Rng): void {
|
||||
state.turn += 1;
|
||||
const energy = energyForTurn(state.ruleset, state.turn);
|
||||
if (state.turn > 1) state.firstToReveal = leader(state, rng);
|
||||
for (const player of PLAYERS) Object.assign(state.players[player], { energy, staged: [], ended: false });
|
||||
state.log.push({ t: 'turnStart', turn: state.turn, energy: [energy, energy] });
|
||||
state.ruleset.laneModifiers.revealTurns.forEach((turn, lane) => {
|
||||
if (turn === state.turn) state.log.push({ t: 'laneRevealed', lane, modifier: state.lanes[lane].modifier });
|
||||
});
|
||||
for (const player of PLAYERS) for (let i = 0; i < state.ruleset.hand.drawPerTurn; i++) draw(state, player);
|
||||
}
|
||||
|
||||
/** Player winning more lanes reveals first; then higher total power; then a seeded coin flip. */
|
||||
function leader(state: MatchState, rng: Rng): PlayerId {
|
||||
const { lanesWon, totalPower } = score(state);
|
||||
if (lanesWon[0] !== lanesWon[1]) return lanesWon[0] > lanesWon[1] ? 0 : 1;
|
||||
if (totalPower[0] !== totalPower[1]) return totalPower[0] > totalPower[1] ? 0 : 1;
|
||||
return rng.int(2) as PlayerId;
|
||||
}
|
||||
|
||||
// ---------- power ----------
|
||||
|
||||
export function modifierActive(state: MatchState, lane: number): boolean {
|
||||
const revealTurn = state.ruleset.laneModifiers.revealTurns[lane] ?? 1;
|
||||
return state.lanes[lane]?.modifier != null && state.turn >= revealTurn;
|
||||
}
|
||||
|
||||
function context(state: MatchState, rng: Rng, params: Record<string, number> | undefined, lane: number, source: string, player: PlayerId): EffectContext {
|
||||
return { state, rng, params: params ?? {}, lane, log: text => state.log.push({ t: 'effect', source, player, text }) };
|
||||
}
|
||||
|
||||
function keywordOf(state: MatchState, card: GameCard) {
|
||||
return card.keyword && Object.hasOwn(state.ruleset.keywords, card.keyword) ? KEYWORDS[card.keyword] : undefined;
|
||||
}
|
||||
|
||||
/** Current power of one card in play, including ongoing keyword and lane effects. */
|
||||
export function cardPower(state: MatchState, target: CardInPlay): number {
|
||||
const scratch = new Rng(state.rng); // ongoing effects must not consume real randomness
|
||||
let power = target.card.power + target.bonus;
|
||||
for (const lane of state.lanes) for (const side of lane.cards) for (const source of side) {
|
||||
const keyword = keywordOf(state, source.card);
|
||||
if (keyword?.ongoing) power += keyword.ongoing(context(state, scratch, state.ruleset.keywords[keyword.id], source.lane, keyword.id, source.owner), source, target);
|
||||
}
|
||||
const lane = state.lanes[target.lane];
|
||||
if (modifierActive(state, target.lane)) {
|
||||
const modifier = LANE_MODIFIERS[lane.modifier!];
|
||||
if (modifier?.ongoing) power += modifier.ongoing(context(state, scratch, state.ruleset.laneModifiers.params[modifier.id], target.lane, modifier.id, target.owner), target);
|
||||
}
|
||||
return power;
|
||||
}
|
||||
|
||||
export function lanePower(state: MatchState, lane: number): [number, number] {
|
||||
return PLAYERS.map(player => state.lanes[lane].cards[player].reduce((sum, card) => sum + cardPower(state, card), 0)) as [number, number];
|
||||
}
|
||||
|
||||
function score(state: MatchState): Omit<MatchResult, 'winner' | 'reason' | 'turns'> {
|
||||
const powers = state.lanes.map((_, lane) => lanePower(state, lane));
|
||||
const lanesWon: [number, number] = [0, 0];
|
||||
const totalPower: [number, number] = [0, 0];
|
||||
for (const [a, b] of powers) {
|
||||
if (a > b) lanesWon[0]++; else if (b > a) lanesWon[1]++;
|
||||
totalPower[0] += a; totalPower[1] += b;
|
||||
}
|
||||
return { lanesWon, lanePower: powers, totalPower };
|
||||
}
|
||||
|
||||
// ---------- actions ----------
|
||||
|
||||
function stagedInLane(p: PlayerState, lane: number): number {
|
||||
return p.staged.filter(play => play.lane === lane).length;
|
||||
}
|
||||
|
||||
function playProblem(state: MatchState, action: Extract<Action, { type: 'play' }>): string | null {
|
||||
const p = state.players[action.player];
|
||||
if (p.ended) return 'You already ended your turn';
|
||||
const card = p.hand.find(c => c.id === action.cardId);
|
||||
if (!card) return 'Card is not in your hand';
|
||||
if (p.staged.some(play => play.cardId === action.cardId)) return 'Card is already staged';
|
||||
if (!Number.isInteger(action.lane) || action.lane < 0 || action.lane >= state.lanes.length) return 'No such lane';
|
||||
if (card.cost > p.energy) return 'Not enough energy';
|
||||
if (state.lanes[action.lane].cards[action.player].length + stagedInLane(p, action.lane) >= state.ruleset.laneCapacity) return 'Lane is full';
|
||||
if (modifierActive(state, action.lane)) {
|
||||
const modifier = LANE_MODIFIERS[state.lanes[action.lane].modifier!];
|
||||
const ctx = context(state, new Rng(state.rng), state.ruleset.laneModifiers.params[modifier?.id ?? ''], action.lane, modifier?.id ?? '', action.player);
|
||||
if (modifier?.canPlay && !modifier.canPlay(ctx, card, action.player)) return `${modifier.name} lane rejects this card`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Why `action` is illegal in `state`, or null if it is legal. */
|
||||
export function actionProblem(state: MatchState, action: Action): string | null {
|
||||
if (state.phase === 'over') return 'Match is over';
|
||||
if (!action || (action.player !== 0 && action.player !== 1)) return 'Unknown player';
|
||||
switch (action.type) {
|
||||
case 'play': return playProblem(state, action);
|
||||
case 'unstage': {
|
||||
const p = state.players[action.player];
|
||||
if (p.ended) return 'You already ended your turn';
|
||||
return p.staged.some(play => play.cardId === action.cardId) ? null : 'Card is not staged';
|
||||
}
|
||||
case 'endTurn': return state.players[action.player].ended ? 'You already ended your turn' : null;
|
||||
case 'concede': return null;
|
||||
default: return 'Unknown action';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Every legal action for `player` except `concede` (always legal while the match
|
||||
* is running). `endTurn` is always included while the player hasn't ended.
|
||||
*/
|
||||
export function legalActions(state: MatchState, player: PlayerId): Action[] {
|
||||
if (state.phase === 'over') return [];
|
||||
const p = state.players[player];
|
||||
if (p.ended) return [];
|
||||
const actions: Action[] = [];
|
||||
for (const card of p.hand) {
|
||||
if (p.staged.some(play => play.cardId === card.id)) continue;
|
||||
for (let lane = 0; lane < state.lanes.length; lane++) {
|
||||
const action: Action = { type: 'play', player, cardId: card.id, lane };
|
||||
if (!playProblem(state, action)) actions.push(action);
|
||||
}
|
||||
}
|
||||
for (const play of p.staged) actions.push({ type: 'unstage', player, cardId: play.cardId });
|
||||
actions.push({ type: 'endTurn', player });
|
||||
return actions;
|
||||
}
|
||||
|
||||
/** Apply one action and return the new state. Throws IllegalActionError if illegal. */
|
||||
export function applyAction(state: MatchState, action: Action): MatchState {
|
||||
const problem = actionProblem(state, action);
|
||||
if (problem) throw new IllegalActionError(problem);
|
||||
const next = clone(state);
|
||||
next.actions.push(clone(action));
|
||||
const p = next.players[action.player];
|
||||
const rng = new Rng(next.rng);
|
||||
switch (action.type) {
|
||||
case 'play': {
|
||||
p.staged.push({ cardId: action.cardId, lane: action.lane });
|
||||
p.energy -= p.hand.find(c => c.id === action.cardId)!.cost;
|
||||
break;
|
||||
}
|
||||
case 'unstage': {
|
||||
const index = p.staged.findIndex(play => play.cardId === action.cardId);
|
||||
p.staged.splice(index, 1);
|
||||
p.energy += p.hand.find(c => c.id === action.cardId)!.cost;
|
||||
break;
|
||||
}
|
||||
case 'endTurn': {
|
||||
p.ended = true;
|
||||
if (next.players.every(player => player.ended)) resolveTurn(next, rng);
|
||||
break;
|
||||
}
|
||||
case 'concede': {
|
||||
next.log.push({ t: 'concede', player: action.player });
|
||||
finish(next, other(action.player), 'concede');
|
||||
break;
|
||||
}
|
||||
}
|
||||
next.rng = rng.state;
|
||||
return next;
|
||||
}
|
||||
|
||||
function resolveTurn(state: MatchState, rng: Rng): void {
|
||||
for (const player of [state.firstToReveal, other(state.firstToReveal)]) {
|
||||
const p = state.players[player];
|
||||
for (const play of p.staged) {
|
||||
const index = p.hand.findIndex(c => c.id === play.cardId);
|
||||
const [card] = p.hand.splice(index, 1);
|
||||
const inPlay: CardInPlay = { card, owner: player, lane: play.lane, turn: state.turn, bonus: 0 };
|
||||
state.lanes[play.lane].cards[player].push(inPlay);
|
||||
state.log.push({ t: 'reveal', player, cardId: card.id, lane: play.lane });
|
||||
const keyword = keywordOf(state, card);
|
||||
keyword?.onReveal?.(context(state, rng, state.ruleset.keywords[keyword.id], play.lane, keyword.id, player), inPlay);
|
||||
if (modifierActive(state, play.lane)) {
|
||||
const modifier = LANE_MODIFIERS[state.lanes[play.lane].modifier!];
|
||||
modifier?.onReveal?.(context(state, rng, state.ruleset.laneModifiers.params[modifier.id], play.lane, modifier.id, player), inPlay);
|
||||
}
|
||||
}
|
||||
p.staged = [];
|
||||
}
|
||||
if (state.turn >= state.ruleset.maxTurns) finish(state, null, 'lanes');
|
||||
else startTurn(state, rng);
|
||||
}
|
||||
|
||||
function finish(state: MatchState, concedeWinner: PlayerId | null, reason: 'lanes' | 'concede'): void {
|
||||
const s = score(state);
|
||||
let winner: PlayerId | null = concedeWinner;
|
||||
let why: MatchResult['reason'] = reason;
|
||||
if (reason !== 'concede') {
|
||||
if (s.lanesWon[0] !== s.lanesWon[1]) winner = s.lanesWon[0] > s.lanesWon[1] ? 0 : 1;
|
||||
else if (state.ruleset.tieBreak === 'totalPower' && s.totalPower[0] !== s.totalPower[1]) {
|
||||
winner = s.totalPower[0] > s.totalPower[1] ? 0 : 1; why = 'totalPower';
|
||||
} else why = 'draw';
|
||||
}
|
||||
state.result = { winner, reason: why, ...s, turns: state.turn };
|
||||
state.phase = 'over';
|
||||
state.log.push({ t: 'matchOver', result: state.result });
|
||||
}
|
||||
|
||||
// ---------- queries ----------
|
||||
|
||||
export function isOver(state: MatchState): boolean { return state.phase === 'over'; }
|
||||
|
||||
/** The final result, or null while the match is running. */
|
||||
export function result(state: MatchState): MatchResult | null { return state.result; }
|
||||
|
||||
/** Hidden-information view for one player. UI and AI should only ever read this. */
|
||||
export function viewFor(state: MatchState, you: PlayerId): PlayerView {
|
||||
const them = other(you);
|
||||
const me = state.players[you], opp = state.players[them];
|
||||
return clone({
|
||||
you, ruleset: state.ruleset, turn: state.turn, phase: state.phase, firstToReveal: state.firstToReveal,
|
||||
energy: me.energy, hand: me.hand, staged: me.staged, ended: me.ended, deckCount: me.deck.length,
|
||||
opponent: { handCount: opp.hand.length - opp.staged.length, deckCount: opp.deck.length, stagedCount: opp.staged.length, ended: opp.ended },
|
||||
lanes: state.lanes.map((lane, index) => {
|
||||
const revealed = modifierActive(state, index);
|
||||
const power = lanePower(state, index);
|
||||
return {
|
||||
modifier: revealed ? lane.modifier : null, modifierRevealed: revealed,
|
||||
cards: [lane.cards[you], lane.cards[them]] as [CardInPlay[], CardInPlay[]],
|
||||
power: [power[you], power[them]] as [number, number],
|
||||
};
|
||||
}),
|
||||
result: state.result,
|
||||
});
|
||||
}
|
||||
|
||||
// ---------- serialisation / replay ----------
|
||||
|
||||
export function serialize(state: MatchState): string { return JSON.stringify(state); }
|
||||
|
||||
export function deserialize(json: string): MatchState {
|
||||
const state = JSON.parse(json) as MatchState;
|
||||
if (state?.schema !== 'wikideck-match/1') throw new Error('Not a wikideck-match/1 state');
|
||||
state.ruleset = parseRuleset(state.ruleset);
|
||||
return state;
|
||||
}
|
||||
|
||||
/** Rebuild a match from its inputs; a host can verify a reported result this way. */
|
||||
export function replay(ruleset: Ruleset, decks: readonly [readonly GameCard[], readonly GameCard[]], seed: string, actions: readonly Action[]): MatchState {
|
||||
return actions.reduce(applyAction, createMatch(ruleset, decks, seed));
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
/** Public entry point of the WikiDeck game engine. See docs/game/ENGINE_API.md. */
|
||||
export * from './types.ts';
|
||||
export { Rng, seedRng, type RngState } from './rng.ts';
|
||||
export { DEFAULT_RULESET, RulesetSchema, parseRuleset, energyForTurn } from './ruleset.ts';
|
||||
export {
|
||||
ENGINE_VERSION, createMatch, legalActions, applyAction, actionProblem, isOver, result, viewFor,
|
||||
serialize, deserialize, replay, validateDeck, cardPower, lanePower, modifierActive,
|
||||
} from './engine.ts';
|
||||
export { KEYWORDS, LANE_MODIFIERS, CATEGORY_ORDER, MENTION_TOKEN_PREFIX, hiddenFrom, laneFaction, type KeywordDef, type LaneModifierDef, type EffectContext } from './keywords.ts';
|
||||
export { STARTER_POOL, starterCard, starterDeck, cardFromStats, type CardSource } from './cards.ts';
|
||||
@@ -1,208 +0,0 @@
|
||||
/**
|
||||
* Keyword and lane-modifier registry. Effects are code here, but which ones a
|
||||
* mode uses and their numbers are data (Ruleset.keywords / laneModifiers.params).
|
||||
* Owner: engine-b (claude/wikideck#3). engine-a owns the hook contract below.
|
||||
*
|
||||
* Hook contract:
|
||||
* - onReveal: runs once when the card is revealed, after it is placed in its lane.
|
||||
* May mutate ctx.state (e.g. add `bonus` to cards, draw cards) but must use ctx.rng
|
||||
* for any randomness and must not throw.
|
||||
* - ongoing: pure; returns a power delta for `target` while `source` is in play.
|
||||
* Called for every (source, target) pair in play, including source === target.
|
||||
* - Lane modifiers have the same shape; `source` is null and `lane` is the modifier's lane.
|
||||
* canPlay lets a lane reject a card (checked when staging).
|
||||
*/
|
||||
import type { Rng } from './rng.ts';
|
||||
import type { CardInPlay, Category, GameCard, MatchState, PlayerId } from './types.ts';
|
||||
|
||||
export interface EffectContext {
|
||||
state: MatchState;
|
||||
rng: Rng;
|
||||
/** Tunable numbers for this keyword/modifier from the ruleset. */
|
||||
params: Record<string, number>;
|
||||
lane: number;
|
||||
log(text: string): void;
|
||||
/** Current power of a card in play (engine's cardPower). Optional so tests can build contexts by hand. */
|
||||
power?(card: CardInPlay): number;
|
||||
}
|
||||
|
||||
export interface KeywordDef {
|
||||
id: string;
|
||||
name: string;
|
||||
/** Short rules text with {param} placeholders, for card faces/tooltips. */
|
||||
text: string;
|
||||
onReveal?(ctx: EffectContext, self: CardInPlay): void;
|
||||
ongoing?(ctx: EffectContext, self: CardInPlay, target: CardInPlay): number;
|
||||
/** Runs at the end of each turn while in play (after all reveals). May mutate ctx.state. */
|
||||
endOfTurn?(ctx: EffectContext, self: CardInPlay): void;
|
||||
}
|
||||
|
||||
export interface LaneModifierDef {
|
||||
id: string;
|
||||
name: string;
|
||||
text: string;
|
||||
/** Runs when any card is revealed in this lane (after its own onReveal). */
|
||||
onReveal?(ctx: EffectContext, card: CardInPlay): void;
|
||||
ongoing?(ctx: EffectContext, target: CardInPlay): number;
|
||||
canPlay?(ctx: EffectContext, card: GameCard, player: PlayerId): boolean;
|
||||
}
|
||||
|
||||
/** Cards on the same side of the same lane, excluding `self`. */
|
||||
export function allies(state: MatchState, self: CardInPlay): CardInPlay[] {
|
||||
return state.lanes[self.lane].cards[self.owner].filter(card => card !== self);
|
||||
}
|
||||
|
||||
/** Faction of a lane (its Topic), or null. v1: an active `portal` lane modifier names one. */
|
||||
export function laneFaction(state: MatchState, lane: number): Category | null {
|
||||
const l = state.lanes[lane];
|
||||
if (!l || l.modifier !== 'portal') return null;
|
||||
const revealTurn = state.ruleset.laneModifiers.revealTurns[lane] ?? 1;
|
||||
if (state.turn < revealTurn) return null;
|
||||
return CATEGORY_ORDER[state.ruleset.laneModifiers.params.portal?.categoryIndex ?? 0] ?? null;
|
||||
}
|
||||
|
||||
/** Ongoing power of a card, excluding effects that need the full engine (base + bonus + ongoing keywords here). */
|
||||
function sidePower(ctx: EffectContext, lane: number, owner: PlayerId, exclude?: CardInPlay): number {
|
||||
return ctx.state.lanes[lane].cards[owner].filter(card => card !== exclude)
|
||||
.reduce((sum, card) => sum + (ctx.power ? ctx.power(card) : card.card.power + card.bonus), 0);
|
||||
}
|
||||
|
||||
/** True when `card` should be shown face down to `viewer` (Obscure). viewFor uses this. */
|
||||
export function hiddenFrom(state: MatchState, card: CardInPlay, viewer: PlayerId): boolean {
|
||||
return card.owner !== viewer && state.phase !== 'over' && card.card.keyword === 'obscure'
|
||||
&& Object.hasOwn(state.ruleset.keywords, 'obscure');
|
||||
}
|
||||
|
||||
export const MENTION_TOKEN_PREFIX = 'token:mention:';
|
||||
|
||||
export const KEYWORDS: Record<string, KeywordDef> = {
|
||||
// engine-a's original examples, kept for the placeholder starter pool and modes.
|
||||
rally: {
|
||||
id: 'rally', name: 'Rally', text: 'On reveal: +{amount} power to your other cards here.',
|
||||
onReveal(ctx, self) {
|
||||
const amount = ctx.params.amount ?? 1;
|
||||
for (const ally of allies(ctx.state, self)) ally.bonus += amount;
|
||||
ctx.log(`Rally +${amount}`);
|
||||
},
|
||||
},
|
||||
anchor: {
|
||||
id: 'anchor', name: 'Anchor', text: 'Ongoing: +{amount} power if this is your only card here.',
|
||||
ongoing(ctx, self, target) {
|
||||
return target === self && allies(ctx.state, self).length === 0 ? ctx.params.amount ?? 2 : 0;
|
||||
},
|
||||
},
|
||||
|
||||
// DESIGN.md (designer-b draft) §7.
|
||||
edition: {
|
||||
id: 'edition', name: 'Edition', text: 'Ongoing: +{amount} power for each other copy of this article on your side.',
|
||||
ongoing(ctx, self, target) {
|
||||
if (target !== self || self.card.pageId === null) return 0;
|
||||
let copies = 0;
|
||||
for (const lane of ctx.state.lanes) for (const card of lane.cards[self.owner])
|
||||
if (card !== self && card.card.pageId === self.card.pageId) copies++;
|
||||
return copies * (ctx.params.amount ?? 2);
|
||||
},
|
||||
},
|
||||
translated: {
|
||||
id: 'translated', name: 'Translated', text: 'On reveal: +{amount} power to your first card in each other Topic.',
|
||||
onReveal(ctx, self) {
|
||||
const amount = ctx.params.amount ?? 1;
|
||||
ctx.state.lanes.forEach((lane, index) => {
|
||||
const first = lane.cards[self.owner][0];
|
||||
if (index !== self.lane && first) {
|
||||
first.bonus += amount;
|
||||
ctx.log(`Translated +${amount} to ${first.card.name}`);
|
||||
}
|
||||
});
|
||||
},
|
||||
},
|
||||
viral: {
|
||||
id: 'viral', name: 'Viral', text: 'On reveal: add a {amount}-power Mention to a random other Topic with space.',
|
||||
onReveal(ctx, self) {
|
||||
const cap = ctx.state.ruleset.laneCapacity;
|
||||
const open = ctx.state.lanes.map((lane, index) => ({ lane, index }))
|
||||
.filter(({ lane, index }) => index !== self.lane && lane.cards[self.owner].length < cap)
|
||||
.map(({ index }) => index);
|
||||
if (!open.length) return;
|
||||
const lane = open[ctx.rng.int(open.length)];
|
||||
const token: GameCard = {
|
||||
id: `${MENTION_TOKEN_PREFIX}${self.card.id}:${ctx.state.turn}`, name: 'Mention', pageId: null,
|
||||
category: self.card.category, cost: 0, power: ctx.params.amount ?? 1, keyword: null, source: 'loaner',
|
||||
meta: { token: true },
|
||||
};
|
||||
ctx.state.lanes[lane].cards[self.owner].push({ card: token, owner: self.owner, lane, turn: ctx.state.turn, bonus: 0 });
|
||||
ctx.log(`Viral: Mention in lane ${lane + 1}`);
|
||||
},
|
||||
},
|
||||
rising: {
|
||||
id: 'rising', name: 'Rising', text: 'End of turn: +{amount} power (up to +{max}).',
|
||||
endOfTurn(ctx, self) {
|
||||
const amount = ctx.params.amount ?? 1, max = ctx.params.max ?? 3;
|
||||
const risen = Number(self.card.meta?.risen ?? 0);
|
||||
const gain = Math.max(0, Math.min(amount, max - risen));
|
||||
if (!gain) return;
|
||||
self.bonus += gain;
|
||||
self.card.meta = { ...self.card.meta, risen: risen + gain };
|
||||
ctx.log(`Rising +${gain}`);
|
||||
},
|
||||
},
|
||||
nostalgic: {
|
||||
id: 'nostalgic', name: 'Nostalgic', text: "On reveal: if you're losing here, +{amount} power.",
|
||||
onReveal(ctx, self) {
|
||||
const mine = sidePower(ctx, self.lane, self.owner, self);
|
||||
const theirs = sidePower(ctx, self.lane, self.owner === 0 ? 1 : 0);
|
||||
if (mine < theirs) {
|
||||
self.bonus += ctx.params.amount ?? 3;
|
||||
ctx.log(`Nostalgic +${ctx.params.amount ?? 3}`);
|
||||
}
|
||||
},
|
||||
},
|
||||
encyclopedic: {
|
||||
id: 'encyclopedic', name: 'Encyclopedic', text: "Can't have its power reduced. On reveal: if it's your only card here, +{amount} power.",
|
||||
onReveal(ctx, self) {
|
||||
if (allies(ctx.state, self).length === 0) {
|
||||
self.bonus += ctx.params.amount ?? 2;
|
||||
ctx.log(`Encyclopedic +${ctx.params.amount ?? 2}`);
|
||||
}
|
||||
},
|
||||
// Floor: cancel any negative bonus on itself (v1 has no negative effects; kept for modes).
|
||||
ongoing(_ctx, self, target) { return target === self && self.bonus < 0 ? -self.bonus : 0; },
|
||||
},
|
||||
obscure: {
|
||||
id: 'obscure', name: 'Obscure', text: 'The opponent sees this card face down until the match ends.',
|
||||
},
|
||||
local: {
|
||||
id: 'local', name: 'Local', text: "Ongoing: +{amount} power in a Topic of this card's faction.",
|
||||
ongoing(ctx, self, target) {
|
||||
return target === self && laneFaction(ctx.state, self.lane) === self.card.category ? ctx.params.amount ?? 2 : 0;
|
||||
},
|
||||
},
|
||||
wildcard: {
|
||||
id: 'wildcard', name: 'Wildcard', text: "On reveal: this card's faction becomes its Topic's faction.",
|
||||
onReveal(ctx, self) {
|
||||
const faction = laneFaction(ctx.state, self.lane);
|
||||
if (faction && faction !== self.card.category) {
|
||||
self.card.category = faction;
|
||||
ctx.log(`Wildcard becomes ${faction}`);
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export const LANE_MODIFIERS: Record<string, LaneModifierDef> = {
|
||||
plain: { id: 'plain', name: 'Plain', text: 'No effect.' },
|
||||
portal: {
|
||||
id: 'portal', name: 'Portal', text: 'Cards of category {category} get +{amount} power here.',
|
||||
// params.categoryIndex picks from CATEGORY_ORDER so params stay numeric.
|
||||
ongoing(ctx, target) {
|
||||
const category = CATEGORY_ORDER[ctx.params.categoryIndex ?? 0];
|
||||
return target.card.category === category ? ctx.params.amount ?? 2 : 0;
|
||||
},
|
||||
},
|
||||
narrow: {
|
||||
id: 'narrow', name: 'Narrow', text: 'Only cards costing {maxCost} or less can be played here.',
|
||||
canPlay(ctx, card) { return card.cost <= (ctx.params.maxCost ?? 3); },
|
||||
},
|
||||
};
|
||||
|
||||
export const CATEGORY_ORDER = ['Space', 'Nature', 'People', 'Science', 'History', 'Culture'] as const;
|
||||
@@ -1,73 +0,0 @@
|
||||
/**
|
||||
* Seeded, serialisable PRNG for the game engine (off-chain only).
|
||||
* sfc32 seeded by cyrb128 of a string. The state is four uint32 numbers so it
|
||||
* round-trips through JSON and a match can be resumed or replayed exactly.
|
||||
*/
|
||||
export type RngState = [number, number, number, number];
|
||||
|
||||
function cyrb128(text: string): RngState {
|
||||
let h1 = 1779033703, h2 = 3144134277, h3 = 1013904242, h4 = 2773480762;
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const k = text.charCodeAt(i);
|
||||
h1 = h2 ^ Math.imul(h1 ^ k, 597399067);
|
||||
h2 = h3 ^ Math.imul(h2 ^ k, 2869860233);
|
||||
h3 = h4 ^ Math.imul(h3 ^ k, 951274213);
|
||||
h4 = h1 ^ Math.imul(h4 ^ k, 2716044179);
|
||||
}
|
||||
h1 = Math.imul(h3 ^ (h1 >>> 18), 597399067);
|
||||
h2 = Math.imul(h4 ^ (h2 >>> 22), 2869860233);
|
||||
h3 = Math.imul(h1 ^ (h3 >>> 17), 951274213);
|
||||
h4 = Math.imul(h2 ^ (h4 >>> 19), 2716044179);
|
||||
h1 ^= h2 ^ h3 ^ h4; h2 ^= h1; h3 ^= h1; h4 ^= h1;
|
||||
return [h1 >>> 0, h2 >>> 0, h3 >>> 0, h4 >>> 0];
|
||||
}
|
||||
|
||||
export function seedRng(seed: string): RngState {
|
||||
const state = cyrb128(seed);
|
||||
// Warm up so similar seeds diverge.
|
||||
const rng = new Rng(state);
|
||||
for (let i = 0; i < 12; i++) rng.nextUint32();
|
||||
return rng.state;
|
||||
}
|
||||
|
||||
/** Mutable wrapper over an RngState. The engine keeps `state` inside MatchState. */
|
||||
export class Rng {
|
||||
state: RngState;
|
||||
constructor(state: RngState) { this.state = [state[0] >>> 0, state[1] >>> 0, state[2] >>> 0, state[3] >>> 0]; }
|
||||
static fromSeed(seed: string): Rng { return new Rng(seedRng(seed)); }
|
||||
|
||||
nextUint32(): number {
|
||||
let [a, b, c, d] = this.state;
|
||||
const t = (((a + b) | 0) + d) | 0;
|
||||
d = (d + 1) | 0;
|
||||
a = b ^ (b >>> 9);
|
||||
b = (c + (c << 3)) | 0;
|
||||
c = (c << 21) | (c >>> 11);
|
||||
c = (c + t) | 0;
|
||||
this.state = [a >>> 0, b >>> 0, c >>> 0, d >>> 0];
|
||||
return t >>> 0;
|
||||
}
|
||||
/** Float in [0, 1). */
|
||||
next(): number { return this.nextUint32() / 4294967296; }
|
||||
/** Integer in [0, n). Unbiased via rejection sampling. */
|
||||
int(n: number): number {
|
||||
if (!Number.isInteger(n) || n <= 0 || n > 4294967296) throw new RangeError('Rng.int needs a positive integer bound');
|
||||
const limit = 4294967296 - (4294967296 % n);
|
||||
let x: number;
|
||||
do x = this.nextUint32(); while (x >= limit);
|
||||
return x % n;
|
||||
}
|
||||
pick<T>(items: readonly T[]): T {
|
||||
if (!items.length) throw new RangeError('Rng.pick on empty list');
|
||||
return items[this.int(items.length)];
|
||||
}
|
||||
/** Fisher–Yates; returns a new array. */
|
||||
shuffle<T>(items: readonly T[]): T[] {
|
||||
const out = items.slice();
|
||||
for (let i = out.length - 1; i > 0; i--) {
|
||||
const j = this.int(i + 1);
|
||||
[out[i], out[j]] = [out[j], out[i]];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
/**
|
||||
* Ruleset: every rule number as data, so peer-hosted modes can vary them
|
||||
* without running code. parseRuleset() is the only way untrusted JSON should
|
||||
* become a Ruleset; it enforces bounds that keep matches short and terminating.
|
||||
*/
|
||||
import { z } from 'zod';
|
||||
import { KEYWORDS, LANE_MODIFIERS } from './keywords.ts';
|
||||
import type { Ruleset } from './types.ts';
|
||||
|
||||
const int = (min: number, max: number) => z.number().int().min(min).max(max);
|
||||
const params = z.record(z.string().max(32), z.number().finite().min(-100).max(100))
|
||||
.refine(value => Object.keys(value).length <= 8, 'Too many params');
|
||||
|
||||
export const RulesetSchema = z.object({
|
||||
id: z.string().regex(/^[a-z0-9][a-z0-9-]{0,47}$/),
|
||||
name: z.string().min(1).max(64),
|
||||
version: int(1, 1_000_000),
|
||||
lanes: int(1, 5),
|
||||
laneCapacity: int(1, 8),
|
||||
maxTurns: int(1, 12),
|
||||
deck: z.object({ min: int(1, 40), max: int(1, 40), maxCopiesPerPage: int(1, 40) }).strict(),
|
||||
hand: z.object({ start: int(0, 10), max: int(1, 12), drawPerTurn: int(0, 3) }).strict(),
|
||||
energy: z.object({ start: int(0, 20), perTurn: int(0, 5), max: int(1, 20) }).strict(),
|
||||
keywords: z.record(z.string(), params).refine(value => Object.keys(value).length <= 32, 'Too many keywords'),
|
||||
laneModifiers: z.object({
|
||||
pool: z.array(z.string()).max(32),
|
||||
revealTurns: z.array(int(1, 12)).max(5),
|
||||
params: z.record(z.string(), params),
|
||||
}).strict(),
|
||||
tieBreak: z.enum(['totalPower', 'draw']),
|
||||
}).strict().superRefine((rules, ctx) => {
|
||||
const issue = (message: string) => ctx.addIssue({ code: 'custom', message });
|
||||
if (rules.deck.min > rules.deck.max) issue('deck.min > deck.max');
|
||||
if (rules.hand.start > rules.hand.max) issue('hand.start > hand.max');
|
||||
if (rules.energy.start > rules.energy.max) issue('energy.start > energy.max');
|
||||
if (rules.laneModifiers.revealTurns.length !== rules.lanes) issue('laneModifiers.revealTurns must have one entry per lane');
|
||||
if (rules.laneModifiers.pool.length && rules.laneModifiers.pool.length < rules.lanes) issue('laneModifiers.pool needs at least one modifier per lane (or be empty)');
|
||||
for (const id of Object.keys(rules.keywords)) if (!Object.hasOwn(KEYWORDS, id)) issue(`Unknown keyword: ${id}`);
|
||||
for (const id of [...rules.laneModifiers.pool, ...Object.keys(rules.laneModifiers.params)])
|
||||
if (!Object.hasOwn(LANE_MODIFIERS, id)) issue(`Unknown lane modifier: ${id}`);
|
||||
});
|
||||
|
||||
/** Validate untrusted ruleset JSON. Throws a ZodError with readable issues. */
|
||||
export function parseRuleset(input: unknown): Ruleset {
|
||||
return RulesetSchema.parse(input) as Ruleset;
|
||||
}
|
||||
|
||||
/** Placeholder base rules (Snap-style lanes) until DESIGN.md v1 lands. */
|
||||
export const DEFAULT_RULESET: Ruleset = {
|
||||
id: 'wikideck-standard',
|
||||
name: 'WikiDeck Standard',
|
||||
version: 1,
|
||||
lanes: 3,
|
||||
laneCapacity: 4,
|
||||
maxTurns: 6,
|
||||
deck: { min: 12, max: 12, maxCopiesPerPage: 2 },
|
||||
hand: { start: 3, max: 7, drawPerTurn: 1 },
|
||||
energy: { start: 1, perTurn: 1, max: 6 },
|
||||
keywords: { rally: { amount: 1 }, anchor: { amount: 2 } },
|
||||
laneModifiers: {
|
||||
pool: ['plain', 'portal', 'narrow'],
|
||||
revealTurns: [1, 2, 3],
|
||||
params: { portal: { categoryIndex: 0, amount: 2 }, narrow: { maxCost: 3 } },
|
||||
},
|
||||
tieBreak: 'totalPower',
|
||||
};
|
||||
|
||||
export function energyForTurn(rules: Ruleset, turn: number): number {
|
||||
return Math.min(rules.energy.max, rules.energy.start + (turn - 1) * rules.energy.perTurn);
|
||||
}
|
||||
@@ -1,158 +0,0 @@
|
||||
/**
|
||||
* WikiDeck game engine types (off-chain). Everything here is plain JSON data:
|
||||
* MatchState round-trips through JSON.stringify/parse with no loss.
|
||||
* Contract: docs/game/ENGINE_API.md. Announce changes on claude/wikideck#3.
|
||||
*/
|
||||
import type { RngState } from './rng.ts';
|
||||
|
||||
export type PlayerId = 0 | 1;
|
||||
export const PLAYERS: readonly PlayerId[] = [0, 1];
|
||||
|
||||
/** Category buckets from server/wiki.ts. */
|
||||
export type Category = 'Space' | 'Nature' | 'People' | 'Science' | 'History' | 'Culture';
|
||||
|
||||
/** A card as the engine sees it. Built from enrichment data by cards.ts, or a starter/loaner card. */
|
||||
export interface GameCard {
|
||||
/** Unique within one deck (e.g. the NFT card hash, or `starter:<pageId>:<n>`). */
|
||||
id: string;
|
||||
name: string;
|
||||
pageId: number | null;
|
||||
category: Category;
|
||||
cost: number;
|
||||
power: number;
|
||||
/** Keyword id from the ruleset's keyword list, or null. */
|
||||
keyword: string | null;
|
||||
/** 'owned' = an NFT the player holds (never moved or burned by a match). */
|
||||
source: 'owned' | 'starter' | 'loaner';
|
||||
/** Optional display/tie-break data; never used for rules unless a keyword says so. */
|
||||
meta?: Record<string, string | number | boolean | null>;
|
||||
}
|
||||
|
||||
/** All rule numbers. Peer-hosted modes override these as data (see ruleset.ts). */
|
||||
export interface Ruleset {
|
||||
id: string;
|
||||
name: string;
|
||||
version: number;
|
||||
lanes: number;
|
||||
/** Cards that may sit on one side of one lane. */
|
||||
laneCapacity: number;
|
||||
maxTurns: number;
|
||||
deck: { min: number; max: number; maxCopiesPerPage: number };
|
||||
hand: { start: number; max: number; drawPerTurn: number };
|
||||
/** Energy available on turn t (1-based) = min(max, start + (t - 1) * perTurn). Unspent energy is lost. */
|
||||
energy: { start: number; perTurn: number; max: number };
|
||||
/** Keyword ids that cards may carry in this mode, with tunable numbers per keyword. */
|
||||
keywords: Record<string, Record<string, number>>;
|
||||
laneModifiers: {
|
||||
/** Pool of lane modifier ids; one is drawn (without replacement) per lane at match start. */
|
||||
pool: string[];
|
||||
/** Turn on which lane i's modifier becomes visible and active (length = lanes). */
|
||||
revealTurns: number[];
|
||||
params: Record<string, Record<string, number>>;
|
||||
};
|
||||
/** How the match ends when lanes tie on count. */
|
||||
tieBreak: 'totalPower' | 'draw';
|
||||
}
|
||||
|
||||
export interface CardInPlay {
|
||||
card: GameCard;
|
||||
owner: PlayerId;
|
||||
lane: number;
|
||||
/** Turn the card was revealed. */
|
||||
turn: number;
|
||||
/** Permanent power changes from effects (onReveal buffs etc.). */
|
||||
bonus: number;
|
||||
}
|
||||
|
||||
export interface StagedPlay { cardId: string; lane: number }
|
||||
|
||||
export interface PlayerState {
|
||||
deck: GameCard[];
|
||||
hand: GameCard[];
|
||||
/** Energy left this turn (after staging). */
|
||||
energy: number;
|
||||
/** Plays chosen this turn, hidden from the opponent until reveal. Order matters. */
|
||||
staged: StagedPlay[];
|
||||
ended: boolean;
|
||||
discard: GameCard[];
|
||||
}
|
||||
|
||||
export interface LaneState {
|
||||
modifier: string | null;
|
||||
cards: [CardInPlay[], CardInPlay[]];
|
||||
}
|
||||
|
||||
export type MatchPhase = 'planning' | 'over';
|
||||
|
||||
export type LogEvent =
|
||||
| { t: 'turnStart'; turn: number; energy: [number, number] }
|
||||
| { t: 'draw'; player: PlayerId; cardId: string }
|
||||
| { t: 'reveal'; player: PlayerId; cardId: string; lane: number }
|
||||
| { t: 'laneRevealed'; lane: number; modifier: string | null }
|
||||
| { t: 'effect'; source: string; player: PlayerId; text: string }
|
||||
| { t: 'concede'; player: PlayerId }
|
||||
| { t: 'matchOver'; result: MatchResult };
|
||||
|
||||
export interface MatchState {
|
||||
schema: 'wikideck-match/1';
|
||||
ruleset: Ruleset;
|
||||
seed: string;
|
||||
rng: RngState;
|
||||
turn: number;
|
||||
phase: MatchPhase;
|
||||
/** Player who reveals first this turn. */
|
||||
firstToReveal: PlayerId;
|
||||
players: [PlayerState, PlayerState];
|
||||
lanes: LaneState[];
|
||||
log: LogEvent[];
|
||||
/** Every action applied so far: (ruleset, decks, seed, actions) replays the match exactly. */
|
||||
actions: Action[];
|
||||
result: MatchResult | null;
|
||||
}
|
||||
|
||||
export type Action =
|
||||
| { type: 'play'; player: PlayerId; cardId: string; lane: number }
|
||||
/** Take back a staged (unrevealed) play this turn; refunds its energy. */
|
||||
| { type: 'unstage'; player: PlayerId; cardId: string }
|
||||
| { type: 'endTurn'; player: PlayerId }
|
||||
| { type: 'concede'; player: PlayerId };
|
||||
|
||||
export interface MatchResult {
|
||||
/** null = draw. */
|
||||
winner: PlayerId | null;
|
||||
reason: 'lanes' | 'totalPower' | 'draw' | 'concede';
|
||||
lanesWon: [number, number];
|
||||
/** lanePower[lane][player] at the end. */
|
||||
lanePower: [number, number][];
|
||||
totalPower: [number, number];
|
||||
turns: number;
|
||||
}
|
||||
|
||||
/** What one player is allowed to see. Use this for UI and AI, never raw MatchState. */
|
||||
export interface PlayerView {
|
||||
you: PlayerId;
|
||||
ruleset: Ruleset;
|
||||
turn: number;
|
||||
phase: MatchPhase;
|
||||
firstToReveal: PlayerId;
|
||||
energy: number;
|
||||
hand: GameCard[];
|
||||
staged: StagedPlay[];
|
||||
ended: boolean;
|
||||
deckCount: number;
|
||||
opponent: { handCount: number; deckCount: number; stagedCount: number; ended: boolean };
|
||||
lanes: {
|
||||
/** null when not yet revealed. */
|
||||
modifier: string | null;
|
||||
modifierRevealed: boolean;
|
||||
/** cards[0] = yours, cards[1] = opponent's (revealed only). */
|
||||
cards: [CardInPlay[], CardInPlay[]];
|
||||
/** power[0] = yours, power[1] = opponent's. */
|
||||
power: [number, number];
|
||||
}[];
|
||||
result: MatchResult | null;
|
||||
}
|
||||
|
||||
export class IllegalActionError extends Error {
|
||||
constructor(message: string) { super(message); this.name = 'IllegalActionError'; }
|
||||
}
|
||||
+2
-1
@@ -10,6 +10,7 @@ import { Card, samples, imageCredit, type CardData } from './Card.tsx';
|
||||
import { WalletPanel } from './WalletPanel.tsx';
|
||||
import { useModalFocus } from './useModalFocus.ts';
|
||||
import { ThemePicker } from './ThemePicker.tsx';
|
||||
import { LoginButton } from './auth/LoginButton.tsx';
|
||||
import { TradeDesk } from './TradeDesk.tsx';
|
||||
import { IS_MAINNET, NETWORK_GENESIS_TIME, NETWORK_LABEL } from '../shared/network.ts';
|
||||
import { StateClient } from '../shared/rpc-client.ts';
|
||||
@@ -170,7 +171,7 @@ export default function App() {
|
||||
<button className="help-link" onClick={() => setDialog('guide')}><CircleHelp size={16} /> The field guide <ArrowUpRight size={14} /></button>
|
||||
</aside>
|
||||
<div className="main-shell">
|
||||
<header className="topbar"><div className="breadcrumbs">Explore <ChevronRight size={13} /><span>{view}</span></div><div className="top-actions"><span className="testnet-brand">RandomX <b>{NETWORK_LABEL}</b></span><ThemePicker /><span className="network-pill"><span className={`network-dot ${!rpcAvailable || !snapshot?.peers ? 'disconnected' : ''}`} />{peerLabel}</span><button className="wallet-button" onClick={openWallet}><span className="wallet-avatar"><WalletIcon size={14} /></span>{wallet ? short(wallet.address) : 'Open wallet'}<ChevronRight size={14} /></button></div></header>
|
||||
<header className="topbar"><div className="breadcrumbs">Explore <ChevronRight size={13} /><span>{view}</span></div><div className="top-actions"><span className="testnet-brand">RandomX <b>{NETWORK_LABEL}</b></span><ThemePicker /><LoginButton /><span className="network-pill"><span className={`network-dot ${!rpcAvailable || !snapshot?.peers ? 'disconnected' : ''}`} />{peerLabel}</span><button className="wallet-button" onClick={openWallet}><span className="wallet-avatar"><WalletIcon size={14} /></span>{wallet ? short(wallet.address) : 'Open wallet'}<ChevronRight size={14} /></button></div></header>
|
||||
<main>
|
||||
<div className="testnet-status" role="status"><span><span className={`network-dot ${rpcAvailable ? '' : 'disconnected'}`} /> RPC {rpcAvailable ? 'available' : 'unavailable'}</span><span>{peerLabel}</span><span>{IS_MAINNET?'MAINNET · experimental · unaudited · no value promised':'TESTNET · experimental · no value promised'}</span>{snapshot && !rpcAvailable && <strong>Showing last known state</strong>}</div>
|
||||
{error && <div className="error-banner" role="alert"><CircleHelp size={17} /><span>{error}</span><button onClick={retry}>Retry</button><button aria-label="Dismiss error" onClick={() => setError('')}><X size={16} /></button></div>}
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import { useEffect, useState, useSyncExternalStore } from 'react';
|
||||
import { Link2, LoaderCircle, LogIn, LogOut, UserRound } from 'lucide-react';
|
||||
import { getWallet, subscribeWallet, type Wallet } from '../wallet.ts';
|
||||
import { account, completeLogin, isCallback, linkWallet, login, logout, subscribeAuth, type Account } from './session.ts';
|
||||
import './auth.css';
|
||||
|
||||
export function useAccount(): Account | undefined {
|
||||
return useSyncExternalStore(subscribeAuth, account, () => undefined);
|
||||
}
|
||||
|
||||
/** Deterministic initials avatar (LDAP accounts have no picture claim; no third-party image hosts). */
|
||||
export function Avatar({ name, seed, size = 22 }: { name: string; seed: string; size?: number }) {
|
||||
let h = 0; for (const c of seed) h = (h * 31 + c.charCodeAt(0)) >>> 0;
|
||||
const initials = name.split(/\s+/).filter(Boolean).slice(0, 2).map(w => [...w][0]).join('').toUpperCase() || '?';
|
||||
return <span className="auth-avatar" aria-hidden="true"
|
||||
style={{ width: size, height: size, fontSize: size * 0.42, background: `hsl(${h % 360} 45% 42%)` }}>{initials}</span>;
|
||||
}
|
||||
|
||||
const short = (s: string) => `${s.slice(0, 6)}…${s.slice(-4)}`;
|
||||
|
||||
export function LoginButton() {
|
||||
const me = useAccount();
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [notice, setNotice] = useState('');
|
||||
const [wallet, setWallet] = useState<Wallet>();
|
||||
|
||||
useEffect(() => {
|
||||
if (!isCallback(location.href)) return;
|
||||
setBusy(true);
|
||||
completeLogin(location.href)
|
||||
.then(({ returnTo }) => history.replaceState(null, '', returnTo))
|
||||
.catch(e => { history.replaceState(null, '', '/'); setNotice(e instanceof Error ? e.message : 'Login failed'); })
|
||||
.finally(() => setBusy(false));
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
const update = () => { void getWallet().then(setWallet).catch(() => setWallet(undefined)); };
|
||||
update(); return subscribeWallet(update);
|
||||
}, []);
|
||||
|
||||
const run = async (fn: () => Promise<unknown>) => {
|
||||
setBusy(true); setNotice('');
|
||||
try { await fn(); } catch (e) { setNotice(e instanceof Error ? e.message : 'Request failed'); }
|
||||
finally { setBusy(false); }
|
||||
};
|
||||
|
||||
if (!me) return <span className="auth-wrap">
|
||||
<button className="wallet-button auth-button" disabled={busy} aria-label="Log in with eom.dev" title="Log in with eom.dev" onClick={() => run(() => login())}>
|
||||
<span className="wallet-avatar">{busy ? <LoaderCircle className="spin" size={14} /> : <LogIn size={14} />}</span>
|
||||
<span className="auth-label">Log in with eom.dev</span>
|
||||
</button>
|
||||
{notice && <span className="auth-notice" role="alert">{notice}</span>}
|
||||
</span>;
|
||||
|
||||
const linked = wallet && me.wallets.some(w => w.address === wallet.address);
|
||||
return <span className="auth-wrap">
|
||||
<button className="wallet-button auth-button" aria-expanded={open} aria-label={`eom.dev account: ${me.name}`} onClick={() => setOpen(o => !o)}>
|
||||
<Avatar name={me.name} seed={me.sub} /><span className="auth-label">{me.name}</span>
|
||||
</button>
|
||||
{open && <div className="auth-menu" role="menu">
|
||||
<div className="auth-menu-head"><Avatar name={me.name} seed={me.sub} size={34} />
|
||||
<div><strong>{me.name}</strong>{me.username && <small>@{me.username} · eom.dev</small>}</div></div>
|
||||
<div className="auth-menu-section">
|
||||
<small>LINKED WALLETS</small>
|
||||
{me.wallets.length ? me.wallets.map(w => <code key={w.address}>{short(w.address)}</code>) : <p>None yet.</p>}
|
||||
</div>
|
||||
{linked ? <p className="auth-ok"><UserRound size={14} /> This wallet is linked.</p>
|
||||
: <>{wallet && <p className="auth-consent">Linking shows your eom.dev name ({me.name}) next to this wallet address on leaderboards, and anyone can look it up. You can unlink later.</p>}<button className="button dark full" role="menuitem" disabled={busy || !wallet} onClick={() => run(async () => {
|
||||
await linkWallet(wallet); setNotice('Wallet linked.');
|
||||
})}>{busy ? <LoaderCircle className="spin" size={15} /> : <Link2 size={15} />}
|
||||
{wallet ? `Link wallet ${short(wallet.address)}` : 'Unlock your wallet to link it'}</button></>}
|
||||
{notice && <p className="auth-notice" role="status">{notice}</p>}
|
||||
<button className="button full" role="menuitem" onClick={() => { logout(); setOpen(false); }}><LogOut size={15} /> Log out</button>
|
||||
</div>}
|
||||
</span>;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
.auth-wrap{position:relative;display:inline-flex;align-items:center;gap:8px}
|
||||
.auth-avatar{display:inline-grid;place-items:center;border-radius:50%;color:#fff;font-weight:650;flex-shrink:0;line-height:1}
|
||||
.auth-button .auth-avatar{margin-right:2px}
|
||||
.auth-menu{position:absolute;top:calc(100% + 8px);right:0;z-index:40;width:280px;padding:14px;border-radius:10px;
|
||||
background:var(--surface, #fff);color:inherit;border:1px solid rgba(127,127,127,.25);box-shadow:0 12px 32px rgba(0,0,0,.18);
|
||||
display:flex;flex-direction:column;gap:10px}
|
||||
.auth-menu-head{display:flex;align-items:center;gap:10px}
|
||||
.auth-menu-head small,.auth-menu-section small{display:block;opacity:.65;font-size:10px;letter-spacing:.6px}
|
||||
.auth-menu-section code{display:block;font-size:11px;margin-top:4px}
|
||||
.auth-menu-section p,.auth-ok{font-size:11px;opacity:.8;margin:4px 0 0;display:flex;align-items:center;gap:6px}
|
||||
.auth-notice{font-size:11px;max-width:260px}
|
||||
.auth-consent{font-size:11px;line-height:1.5;opacity:.8;margin:0}
|
||||
.auth-label{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:140px}
|
||||
/* Narrow screens: the top bar has no spare width, so float the account button outside its flow. */
|
||||
@media (max-width:480px){
|
||||
.auth-label{display:none}
|
||||
.auth-wrap{position:fixed;right:14px;bottom:14px;z-index:45}
|
||||
.auth-wrap .auth-button{border-radius:999px;padding:6px;box-shadow:0 6px 18px rgba(0,0,0,.22)}
|
||||
.auth-menu{top:auto;bottom:calc(100% + 8px);width:min(280px,calc(100vw - 28px))}
|
||||
.auth-wrap>.auth-notice{position:absolute;bottom:calc(100% + 8px);right:0;width:min(260px,calc(100vw - 28px))}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
// eom.dev login (Dex, OIDC authorization code + PKCE S256, public client "wikideck").
|
||||
// The browser only navigates to Dex. The node exchanges the code and verifies the ID token
|
||||
// (Dex sends no CORS headers), so there is no browser -> Dex fetch and no CSP change.
|
||||
// Tokens live in sessionStorage (cleared with the tab), never localStorage.
|
||||
import { getWallet, sign, type Wallet } from '../wallet.ts';
|
||||
import { clientLinkMessage } from '../../shared/account-link.ts';
|
||||
|
||||
export type LinkedWallet = { address: string; linkedAt: number };
|
||||
export type Account = { sub: string; issuer: string; name: string; username: string; wallets: LinkedWallet[] };
|
||||
type Session = { idToken: string; expiresAt: number; account: Account };
|
||||
type Pending = { state: string; nonce: string; verifier: string; redirectUri: string; returnTo: string; createdAt: number };
|
||||
type AuthConfig = { issuer: string; clientId: string; scopes: string; authorizationEndpoint: string; redirectUris: string[] };
|
||||
|
||||
const SESSION_KEY = 'wikideck.auth.session';
|
||||
const PENDING_KEY = 'wikideck.auth.pending';
|
||||
export const CALLBACK_PATH = '/auth/callback';
|
||||
export const NATIVE_REDIRECT = 'dev.eom.wikideck:/oauth/callback';
|
||||
|
||||
const listeners = new Set<() => void>();
|
||||
let current: Session | undefined = load();
|
||||
export function subscribeAuth(fn: () => void): () => void { listeners.add(fn); return () => { listeners.delete(fn); }; }
|
||||
function notify() { for (const fn of listeners) fn(); }
|
||||
|
||||
function load(): Session | undefined {
|
||||
try {
|
||||
const raw = sessionStorage.getItem(SESSION_KEY);
|
||||
const s = raw ? JSON.parse(raw) as Session : undefined;
|
||||
return s && s.expiresAt > Date.now() + 30_000 ? s : undefined;
|
||||
} catch { return undefined; }
|
||||
}
|
||||
function save(s: Session | undefined) {
|
||||
current = s;
|
||||
try { if (s) sessionStorage.setItem(SESSION_KEY, JSON.stringify(s)); else sessionStorage.removeItem(SESSION_KEY); } catch { /* memory only */ }
|
||||
notify();
|
||||
}
|
||||
export function account(): Account | undefined {
|
||||
if (current && current.expiresAt <= Date.now() + 30_000) save(undefined);
|
||||
return current?.account;
|
||||
}
|
||||
|
||||
const b64url = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
||||
const random = (n = 32) => b64url(crypto.getRandomValues(new Uint8Array(n)));
|
||||
export async function pkceChallenge(verifier: string): Promise<string> {
|
||||
return b64url(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))));
|
||||
}
|
||||
|
||||
type CapacitorGlobal = { isNativePlatform?: () => boolean; Plugins?: { Browser?: { open(o: { url: string }): Promise<void>; close?(): Promise<void> } } };
|
||||
const capacitor = () => (globalThis as { Capacitor?: CapacitorGlobal }).Capacitor;
|
||||
export const isNative = () => Boolean(capacitor()?.isNativePlatform?.());
|
||||
export function redirectUri(): string { return isNative() ? NATIVE_REDIRECT : `${location.origin}${CALLBACK_PATH}`; }
|
||||
|
||||
/**
|
||||
* Node base URL. Empty on the web (same origin). Capacitor builds bundle the UI locally, so the
|
||||
* app sets `globalThis.WIKIDECK_NODE_URL = 'http://192.168.1.32:3101'` (or similar) before use.
|
||||
*/
|
||||
export const nodeBase = () => ((globalThis as { WIKIDECK_NODE_URL?: string }).WIKIDECK_NODE_URL ?? '').replace(/\/+$/, '');
|
||||
|
||||
async function api<T>(path: string, init: RequestInit & { token?: string } = {}): Promise<T> {
|
||||
const { token, ...rest } = init;
|
||||
const res = await fetch(`${nodeBase()}/api/account/${path}`, { cache: 'no-store', signal: AbortSignal.timeout(15000), ...rest,
|
||||
headers: { ...(rest.body ? { 'Content-Type': 'application/json' } : {}), ...(token ? { Authorization: `Bearer ${token}` } : {}) } });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (res.status === 401 && token) save(undefined);
|
||||
if (!res.ok) throw new Error(typeof data.error === 'string' ? data.error : 'Account request failed');
|
||||
return data as T;
|
||||
}
|
||||
|
||||
export async function login(returnTo = location.pathname + location.search): Promise<void> {
|
||||
const config = await api<AuthConfig>('config');
|
||||
const uri = redirectUri();
|
||||
if (!config.redirectUris.includes(uri)) throw new Error(`This node is not set up for eom.dev login from ${uri}.`);
|
||||
const pending: Pending = { state: random(), nonce: random(), verifier: random(48), redirectUri: uri,
|
||||
returnTo: returnTo.startsWith('/') && !returnTo.startsWith('//') ? returnTo : '/', createdAt: Date.now() };
|
||||
sessionStorage.setItem(PENDING_KEY, JSON.stringify(pending));
|
||||
const url = new URL(config.authorizationEndpoint);
|
||||
url.search = new URLSearchParams({ response_type: 'code', client_id: config.clientId, redirect_uri: uri,
|
||||
scope: config.scopes, state: pending.state, nonce: pending.nonce,
|
||||
code_challenge: await pkceChallenge(pending.verifier), code_challenge_method: 'S256' }).toString();
|
||||
// Capacitor: system browser (never a WebView) + custom-scheme redirect, per RFC 8252.
|
||||
const browser = capacitor()?.Plugins?.Browser;
|
||||
if (isNative() && browser) await browser.open({ url: url.toString() });
|
||||
else location.assign(url.toString());
|
||||
}
|
||||
|
||||
export const isCallback = (url: string) => {
|
||||
const u = new URL(url);
|
||||
return (u.pathname === CALLBACK_PATH || url.startsWith(NATIVE_REDIRECT)) && (u.searchParams.has('code') || u.searchParams.has('error'));
|
||||
};
|
||||
|
||||
/** Finish a login from the redirect URL. Web: called on load. Capacitor: call from App 'appUrlOpen'. */
|
||||
export async function completeLogin(url: string): Promise<{ returnTo: string }> {
|
||||
const params = new URL(url).searchParams;
|
||||
const raw = sessionStorage.getItem(PENDING_KEY);
|
||||
sessionStorage.removeItem(PENDING_KEY); // single use
|
||||
const pending = raw ? JSON.parse(raw) as Pending : undefined;
|
||||
if (!pending || Date.now() - pending.createdAt > 10 * 60_000) throw new Error('Login expired. Please try again.');
|
||||
if (params.get('state') !== pending.state) throw new Error('Login state mismatch. Please try again.');
|
||||
if (params.get('error')) throw new Error(`Login cancelled: ${params.get('error_description') ?? params.get('error')}`.slice(0, 160));
|
||||
const code = params.get('code');
|
||||
if (!code) throw new Error('Login response had no code.');
|
||||
const s = await api<Session>('token', { method: 'POST', body: JSON.stringify({ code, codeVerifier: pending.verifier,
|
||||
redirectUri: pending.redirectUri, nonce: pending.nonce }) });
|
||||
save(s);
|
||||
if (isNative()) void capacitor()?.Plugins?.Browser?.close?.().catch(() => {});
|
||||
return { returnTo: pending.returnTo };
|
||||
}
|
||||
|
||||
/** Local logout. Dex publishes no end_session endpoint, so the Dex SSO cookie may remain. */
|
||||
export function logout(): void { save(undefined); }
|
||||
|
||||
export async function refreshAccount(): Promise<Account | undefined> {
|
||||
if (!current) return undefined;
|
||||
const me = await api<Account>('me', { token: current.idToken });
|
||||
save({ ...current, account: me });
|
||||
return me;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prove wallet ownership: the node issues a one-time nonce. The client builds the link message
|
||||
* itself (shared/account-link.ts) and never signs node-supplied text, so a hostile node or a
|
||||
* network attacker cannot get a transfer or trade signed. The key never leaves the client.
|
||||
*/
|
||||
export async function linkWallet(wallet?: Wallet, signer: (w: Wallet, message: string) => Promise<string> = sign): Promise<LinkedWallet> {
|
||||
if (!current) throw new Error('Log in with your eom.dev account first.');
|
||||
const session = current;
|
||||
const w = wallet ?? await getWallet();
|
||||
if (!w) throw new Error('Unlock your wallet first.');
|
||||
const token = session.idToken;
|
||||
const challenge = await api<{ nonce?: unknown; message?: unknown; expiresAt?: unknown }>('challenge',
|
||||
{ method: 'POST', token, body: JSON.stringify({ address: w.address }) });
|
||||
const message = clientLinkMessage(session.account, w.address, challenge);
|
||||
const signature = await signer(w, message);
|
||||
const linked = await api<LinkedWallet>('link', { method: 'POST', token,
|
||||
body: JSON.stringify({ nonce: challenge.nonce, address: w.address, publicKey: w.publicKey, signature }) });
|
||||
await refreshAccount().catch(() => {});
|
||||
return linked;
|
||||
}
|
||||
|
||||
/** Leaderboard display names for wallet addresses (only linked wallets resolve). */
|
||||
export async function displayNames(addresses: string[]): Promise<Record<string, string>> {
|
||||
if (!addresses.length) return {};
|
||||
const { names } = await api<{ names: Record<string, string> }>(`names?addresses=${addresses.slice(0, 100).join(',')}`);
|
||||
return names;
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { generateKeyPairSync, sign } from 'node:crypto';
|
||||
import { mkdtemp, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import express from 'express';
|
||||
import { address } from '../server/testnet/consensus.ts';
|
||||
import { AccountStore, CHALLENGE_TTL_MS, LinkError, MAX_PENDING_PER_ACCOUNT } from '../server/account/store.ts';
|
||||
import { clientLinkMessage, linkMessage } from '../shared/account-link.ts';
|
||||
import { nftTransferMessage } from '../shared/testnet.ts';
|
||||
import { createAccountRouter } from '../server/account/router.ts';
|
||||
import { DexKeys, oidcConfig } from '../server/account/oidc.ts';
|
||||
|
||||
function wallet() {
|
||||
const keys = generateKeyPairSync('ec', { namedCurve: 'prime256v1' });
|
||||
const publicKey = keys.publicKey.export({ type: 'spki', format: 'der' }).toString('base64');
|
||||
return { publicKey, address: address(publicKey), sign: (m: string) =>
|
||||
sign('sha256', Buffer.from(m), { key: keys.privateKey, dsaEncoding: 'ieee-p1363' }).toString('base64') };
|
||||
}
|
||||
const ada = { sub: 'user-ada', issuer: 'https://dex.test/', name: 'Ada', username: 'ada' };
|
||||
const bob = { sub: 'user-bob', issuer: 'https://dex.test/', name: 'Bob', username: 'bob' };
|
||||
|
||||
async function withStore(fn: (s: AccountStore, clock: { now: number }) => Promise<void> | void) {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'wikideck-account-'));
|
||||
const clock = { now: 1_800_000_000_000 };
|
||||
const store = new AccountStore(join(dir, 'accounts.sqlite'), () => clock.now);
|
||||
try { store.upsert(ada); store.upsert(bob); await fn(store, clock); }
|
||||
finally { store.close(); await rm(dir, { recursive: true, force: true }); }
|
||||
}
|
||||
const code = (fn: () => unknown, status: number) => assert.throws(fn, e => e instanceof LinkError && e.status === status);
|
||||
|
||||
test('account link: a valid wallet signature links the wallet and names resolve', () => withStore(store => {
|
||||
const w = wallet();
|
||||
const c = store.challenge(ada, w.address);
|
||||
const linked = store.link(ada, { nonce: c.nonce, address: w.address, publicKey: w.publicKey, signature: w.sign(c.message) });
|
||||
assert.equal(linked.address, w.address);
|
||||
assert.deepEqual(store.wallets(ada.sub).map(x => x.address), [w.address]);
|
||||
assert.deepEqual(store.names([w.address, 'f'.repeat(64)]), { [w.address]: 'Ada' });
|
||||
}));
|
||||
|
||||
test('account link: a signature from the wrong key is rejected', () => withStore(store => {
|
||||
const w = wallet(), attacker = wallet();
|
||||
const c = store.challenge(ada, w.address);
|
||||
// Attacker signs with their own key but claims the victim's address and public key.
|
||||
code(() => store.link(ada, { nonce: c.nonce, address: w.address, publicKey: w.publicKey, signature: attacker.sign(c.message) }), 401);
|
||||
// Or presents their own public key for the victim's address.
|
||||
const c2 = store.challenge(ada, w.address);
|
||||
code(() => store.link(ada, { nonce: c2.nonce, address: w.address, publicKey: attacker.publicKey, signature: attacker.sign(c2.message) }), 400);
|
||||
assert.deepEqual(store.wallets(ada.sub), []);
|
||||
}));
|
||||
|
||||
test('account link: replayed, expired and cross-account challenges are rejected', () => withStore((store, clock) => {
|
||||
const w = wallet();
|
||||
const c = store.challenge(ada, w.address);
|
||||
const input = { nonce: c.nonce, address: w.address, publicKey: w.publicKey, signature: w.sign(c.message) };
|
||||
store.link(ada, input);
|
||||
code(() => store.link(ada, input), 409); // replay
|
||||
const c2 = store.challenge(ada, w.address);
|
||||
clock.now += CHALLENGE_TTL_MS + 1;
|
||||
code(() => store.link(ada, { ...input, nonce: c2.nonce, signature: w.sign(c2.message) }), 409); // expired
|
||||
const c3 = store.challenge(ada, w.address);
|
||||
code(() => store.link(bob, { ...input, nonce: c3.nonce, signature: w.sign(c3.message) }), 409); // challenge bound to ada
|
||||
// A wallet already linked to ada cannot be claimed by bob even with a fresh, valid proof.
|
||||
const c4 = store.challenge(bob, w.address);
|
||||
code(() => store.link(bob, { ...input, nonce: c4.nonce, signature: w.sign(c4.message) }), 409);
|
||||
assert.equal(store.unlink(ada.sub, w.address), true);
|
||||
}));
|
||||
|
||||
test('account HTTP: login exchange, bearer auth and wallet link end to end', async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'wikideck-account-http-'));
|
||||
const rsa = generateKeyPairSync('rsa', { modulusLength: 2048 });
|
||||
const config = { ...oidcConfig({}), issuer: 'https://dex.test/' };
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const enc = (v: unknown) => Buffer.from(JSON.stringify(v)).toString('base64url');
|
||||
const nonce = 'nonce-'.padEnd(24, 'x');
|
||||
const input = `${enc({ alg: 'RS256', kid: 'k1' })}.${enc({ iss: config.issuer, sub: 'user-ada', aud: 'wikideck',
|
||||
iat: now, exp: now + 600, name: 'Ada', preferred_username: 'ada', nonce })}`;
|
||||
const idToken = `${input}.${sign('sha256', Buffer.from(input), rsa.privateKey).toString('base64url')}`;
|
||||
let tokenBody = '';
|
||||
const fetcher = (async (url: URL | string, init?: RequestInit) => {
|
||||
const u = String(url);
|
||||
const json = (v: unknown, status = 200) => new Response(JSON.stringify(v), { status, headers: { 'content-type': 'application/json' } });
|
||||
if (u.endsWith('openid-configuration')) return json({ issuer: config.issuer, authorization_endpoint: 'https://dex.test/auth',
|
||||
token_endpoint: 'https://dex.test/token', jwks_uri: 'https://dex.test/keys' });
|
||||
if (u.endsWith('/keys')) return json({ keys: [{ ...rsa.publicKey.export({ format: 'jwk' }), kid: 'k1' }] });
|
||||
if (u.endsWith('/token')) { tokenBody = String(init?.body); return json({ id_token: idToken, access_token: 'a', token_type: 'bearer' }); }
|
||||
return json({}, 404);
|
||||
}) as typeof fetch;
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use('/api/account', createAccountRouter({ config, dataDir: dir, keys: new DexKeys(config, fetcher), fetcher }));
|
||||
const server = app.listen(0, '127.0.0.1');
|
||||
await new Promise(r => server.once('listening', r));
|
||||
const base = `http://127.0.0.1:${(server.address() as { port: number }).port}/api/account`;
|
||||
const call = async (path: string, body?: unknown, token?: string) => {
|
||||
const res = await fetch(base + path, { method: body ? 'POST' : 'GET', headers: { 'content-type': 'application/json',
|
||||
...(token ? { authorization: `Bearer ${token}` } : {}) }, body: body ? JSON.stringify(body) : undefined });
|
||||
return { status: res.status, body: await res.json() };
|
||||
};
|
||||
try {
|
||||
const cfg = await call('/config');
|
||||
assert.equal(cfg.body.authorizationEndpoint, 'https://dex.test/auth');
|
||||
assert.equal(cfg.body.clientId, 'wikideck');
|
||||
const verifier = 'v'.repeat(43);
|
||||
const bad = await call('/token', { code: 'c', codeVerifier: verifier, redirectUri: 'https://evil.test/cb', nonce });
|
||||
assert.equal(bad.status, 400);
|
||||
const wrongNonce = await call('/token', { code: 'c', codeVerifier: verifier, redirectUri: config.redirectUris[0], nonce: 'z'.repeat(24) });
|
||||
assert.equal(wrongNonce.status, 401);
|
||||
const login = await call('/token', { code: 'c', codeVerifier: verifier, redirectUri: config.redirectUris[0], nonce });
|
||||
assert.equal(login.status, 200);
|
||||
assert.equal(login.body.account.name, 'ada');
|
||||
const sent = new URLSearchParams(tokenBody);
|
||||
assert.equal(sent.get('client_id'), 'wikideck');
|
||||
assert.equal(sent.get('code_verifier'), verifier);
|
||||
assert.equal(sent.get('client_secret'), null);
|
||||
assert.equal((await call('/me')).status, 401);
|
||||
assert.equal((await call('/me', undefined, idToken)).body.username, 'ada');
|
||||
const w = wallet();
|
||||
const ch = await call('/challenge', { address: w.address }, idToken);
|
||||
const link = await call('/link', { nonce: ch.body.nonce, address: w.address, publicKey: w.publicKey, signature: w.sign(ch.body.message) }, idToken);
|
||||
assert.equal(link.status, 201);
|
||||
const replay = await call('/link', { nonce: ch.body.nonce, address: w.address, publicKey: w.publicKey, signature: w.sign(ch.body.message) }, idToken);
|
||||
assert.equal(replay.status, 409);
|
||||
assert.deepEqual((await call(`/names?addresses=${w.address}`)).body.names, { [w.address]: 'ada' });
|
||||
} finally {
|
||||
await new Promise(r => server.close(r));
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('account link: pending challenges are capped per account, not just globally', () => withStore(store => {
|
||||
const w = wallet();
|
||||
for (let i = 0; i < MAX_PENDING_PER_ACCOUNT; i++) store.challenge(ada, w.address);
|
||||
code(() => store.challenge(ada, w.address), 429);
|
||||
store.challenge(bob, w.address); // other users are unaffected
|
||||
}));
|
||||
|
||||
test('account link (client): only a locally built link message is ever signed', () => {
|
||||
const w = wallet(), now = 1_800_000_000_000;
|
||||
const good = { nonce: 'a'.repeat(24), expiresAt: now + 60_000 };
|
||||
const expected = linkMessage({ issuer: ada.issuer, sub: ada.sub, address: w.address, ...good });
|
||||
assert.equal(clientLinkMessage(ada, w.address, { ...good, message: expected }, now), expected);
|
||||
// A hostile node substitutes a card-transfer tuple for the link message.
|
||||
const transfer = nftTransferMessage({ chainId: 'd'.repeat(64), cardHash: 'b'.repeat(64), from: w.address, to: 'c'.repeat(64), sequence: 1 } as never);
|
||||
assert.throws(() => clientLinkMessage(ada, w.address, { ...good, message: transfer }, now), /Nothing was signed/);
|
||||
assert.throws(() => clientLinkMessage(ada, w.address, { nonce: '["x"]', expiresAt: good.expiresAt }, now), /invalid link challenge/);
|
||||
assert.throws(() => clientLinkMessage(ada, w.address, { nonce: good.nonce, expiresAt: now + 3_600_000 }, now), /invalid link challenge/);
|
||||
assert.throws(() => clientLinkMessage(ada, w.address, { nonce: good.nonce, expiresAt: now - 1 }, now), /invalid link challenge/);
|
||||
});
|
||||
|
||||
test('account link (client): linkWallet refuses a transfer message from the node and signs nothing', async () => {
|
||||
const w = wallet();
|
||||
const store = new Map<string, string>();
|
||||
const g = globalThis as Record<string, unknown>;
|
||||
const saved = { sessionStorage: g.sessionStorage, fetch: g.fetch };
|
||||
g.sessionStorage = { getItem: (k: string) => store.get(k) ?? null, setItem: (k: string, v: string) => { store.set(k, v); },
|
||||
removeItem: (k: string) => { store.delete(k); } };
|
||||
store.set('wikideck.auth.session', JSON.stringify({ idToken: 'tok', expiresAt: Date.now() + 3_600_000,
|
||||
account: { ...ada, wallets: [] } }));
|
||||
const transfer = nftTransferMessage({ chainId: 'd'.repeat(64), cardHash: 'b'.repeat(64), from: w.address, to: 'c'.repeat(64), sequence: 1 } as never);
|
||||
const requests: string[] = [];
|
||||
g.fetch = (async (url: string) => { requests.push(String(url));
|
||||
return new Response(JSON.stringify({ nonce: 'a'.repeat(24), expiresAt: Date.now() + 60_000, message: transfer }),
|
||||
{ headers: { 'content-type': 'application/json' } }); }) as typeof fetch;
|
||||
try {
|
||||
const { linkWallet } = await import('../src/auth/session.ts');
|
||||
let signed = 0;
|
||||
await assert.rejects(linkWallet({ address: w.address, publicKey: w.publicKey }, async () => { signed++; return 'sig'; }), /Nothing was signed/);
|
||||
assert.equal(signed, 0);
|
||||
assert.deepEqual(requests.map(u => u.split('/').pop()), ['challenge']); // never reached /link
|
||||
} finally { g.sessionStorage = saved.sessionStorage; g.fetch = saved.fetch; }
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { generateKeyPairSync, sign, type KeyObject } from 'node:crypto';
|
||||
import { DexKeys, TokenError, displayName, oidcConfig, verifyIdToken } from '../server/account/oidc.ts';
|
||||
|
||||
const config = { ...oidcConfig({}), issuer: 'https://dex.test/' };
|
||||
const NOW = 1_800_000_000_000;
|
||||
const t = Math.floor(NOW / 1000);
|
||||
|
||||
function rsa() { return generateKeyPairSync('rsa', { modulusLength: 2048 }); }
|
||||
const main = rsa(), other = rsa();
|
||||
|
||||
export function jwt(claims: Record<string, unknown>, key: KeyObject = main.privateKey, header: Record<string, unknown> = { alg: 'RS256', kid: 'k1' }): string {
|
||||
const enc = (v: unknown) => Buffer.from(JSON.stringify(v)).toString('base64url');
|
||||
const input = `${enc(header)}.${enc(claims)}`;
|
||||
return `${input}.${sign('sha256', Buffer.from(input), key).toString('base64url')}`;
|
||||
}
|
||||
const good = (over: Record<string, unknown> = {}) => ({ iss: config.issuer, sub: 'user-1', aud: 'wikideck',
|
||||
iat: t - 10, exp: t + 3600, name: 'Ada Lovelace', preferred_username: 'ada', email: 'ada@example.test', nonce: 'n'.repeat(16), ...over });
|
||||
|
||||
function fakeDex(calls: string[] = []) {
|
||||
const jwks = { keys: [{ ...main.publicKey.export({ format: 'jwk' }), kid: 'k1', use: 'sig', alg: 'RS256' }] };
|
||||
const fetcher = (async (url: URL | string) => {
|
||||
const u = String(url); calls.push(u);
|
||||
const json = (v: unknown) => new Response(JSON.stringify(v), { headers: { 'content-type': 'application/json' } });
|
||||
if (u.endsWith('/.well-known/openid-configuration')) return json({ issuer: config.issuer,
|
||||
authorization_endpoint: 'https://dex.test/auth', token_endpoint: 'https://dex.test/token', jwks_uri: 'https://dex.test/keys' });
|
||||
if (u === 'https://dex.test/keys') return json(jwks);
|
||||
return new Response('{}', { status: 404 });
|
||||
}) as typeof fetch;
|
||||
return new DexKeys(config, fetcher, () => NOW);
|
||||
}
|
||||
|
||||
const rejects = (p: Promise<unknown>, msg: RegExp) => assert.rejects(p, e => e instanceof TokenError && msg.test(e.message));
|
||||
|
||||
test('account: a good ID token verifies against the JWKS', async () => {
|
||||
const claims = await verifyIdToken(jwt(good()), fakeDex(), config, { now: NOW, nonce: 'n'.repeat(16) });
|
||||
assert.equal(claims.sub, 'user-1');
|
||||
assert.equal(displayName(claims), 'ada'); // username preferred over real name
|
||||
});
|
||||
|
||||
test('account: expired tokens are rejected (beyond clock skew)', async () => {
|
||||
await rejects(verifyIdToken(jwt(good({ exp: t - 61 })), fakeDex(), config, { now: NOW }), /expired/);
|
||||
// Within the 60 s skew still passes.
|
||||
await verifyIdToken(jwt(good({ exp: t - 30 })), fakeDex(), config, { now: NOW });
|
||||
});
|
||||
|
||||
test('account: wrong audience and wrong issuer are rejected', async () => {
|
||||
await rejects(verifyIdToken(jwt(good({ aud: 'www-membership' })), fakeDex(), config, { now: NOW }), /audience/);
|
||||
await rejects(verifyIdToken(jwt(good({ aud: ['other', 'wikideck'] })), fakeDex(), config, { now: NOW }), /authorized party/);
|
||||
await verifyIdToken(jwt(good({ aud: ['other', 'wikideck'], azp: 'wikideck' })), fakeDex(), config, { now: NOW });
|
||||
await rejects(verifyIdToken(jwt(good({ iss: 'https://evil.test/' })), fakeDex(), config, { now: NOW }), /issuer/);
|
||||
await rejects(verifyIdToken(jwt(good({ iss: 'https://dex.test' })), fakeDex(), config, { now: NOW }), /issuer/);
|
||||
});
|
||||
|
||||
test('account: forged signatures, alg confusion and unknown keys are rejected', async () => {
|
||||
await rejects(verifyIdToken(jwt(good(), other.privateKey), fakeDex(), config, { now: NOW }), /signature/);
|
||||
const parts = jwt(good()).split('.');
|
||||
const tampered = `${parts[0]}.${Buffer.from(JSON.stringify(good({ sub: 'admin' }))).toString('base64url')}.${parts[2]}`;
|
||||
await rejects(verifyIdToken(tampered, fakeDex(), config, { now: NOW }), /signature/);
|
||||
const none = `${Buffer.from(JSON.stringify({ alg: 'none', kid: 'k1' })).toString('base64url')}.${parts[1]}.`;
|
||||
await rejects(verifyIdToken(none, fakeDex(), config, { now: NOW }), /algorithm/);
|
||||
await rejects(verifyIdToken(jwt(good(), main.privateKey, { alg: 'RS256', kid: 'nope' }), fakeDex(), config, { now: NOW }), /signing key/);
|
||||
await rejects(verifyIdToken('a.b', fakeDex(), config, { now: NOW }), /Malformed/);
|
||||
});
|
||||
|
||||
test('account: nonce, future iat and nbf are enforced', async () => {
|
||||
await rejects(verifyIdToken(jwt(good()), fakeDex(), config, { now: NOW, nonce: 'x'.repeat(16) }), /nonce/);
|
||||
await rejects(verifyIdToken(jwt(good({ iat: t + 600 })), fakeDex(), config, { now: NOW }), /future/);
|
||||
await rejects(verifyIdToken(jwt(good({ nbf: t + 600 })), fakeDex(), config, { now: NOW }), /not yet/);
|
||||
});
|
||||
|
||||
test('account: JWKS is cached and discovery issuer must match', async () => {
|
||||
const calls: string[] = [];
|
||||
const keys = fakeDex(calls);
|
||||
await verifyIdToken(jwt(good()), keys, config, { now: NOW });
|
||||
await verifyIdToken(jwt(good()), keys, config, { now: NOW });
|
||||
assert.equal(calls.filter(c => c.endsWith('/keys')).length, 1);
|
||||
const bad = new DexKeys({ ...config, issuer: 'https://dex.test/other/' }, (async () =>
|
||||
new Response(JSON.stringify({ issuer: 'https://dex.test/' }))) as typeof fetch);
|
||||
await assert.rejects(bad.meta(), /issuer mismatch/);
|
||||
});
|
||||
|
||||
test('account: display names never fall back to email and are sanitised', () => {
|
||||
assert.equal(displayName({ sub: 'abcdef123', preferred_username: 'ada', name: 'Ada Lovelace' }), 'ada');
|
||||
assert.equal(displayName({ sub: 'abcdef123', name: 'Ada Lovelace' }), 'Ada Lovelace');
|
||||
assert.equal(displayName({ sub: 'abcdef123' }), 'player-abcdef');
|
||||
assert.equal(displayName({ sub: 's', name: 'A\u0000B' + 'x'.repeat(100) }).length, 48);
|
||||
});
|
||||
@@ -1,105 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
percentile, percentiles, fame, costFor, homeStat, trendFor, deriveCard,
|
||||
type CardInput, type PercentileTable, type DerivationRules,
|
||||
} from '../shared/game/derive.ts';
|
||||
import { forAll } from './game/property.ts';
|
||||
|
||||
/** Cut points 1..99: score s sits at percentile ~s, which makes examples readable. */
|
||||
const LINEAR = Array.from({ length: 99 }, (_, i) => i + 1);
|
||||
const TABLE: PercentileTable = { attention: LINEAR, depth: LINEAR, reach: LINEAR };
|
||||
const RULES: DerivationRules = {
|
||||
costThresholds: [15, 35, 55, 75, 90], powerByCost: [0, 1, 2, 4, 5, 7, 9], trendUp: 25, trendDown: -25,
|
||||
};
|
||||
|
||||
function input(stats: CardInput['snapshot']['stats'], trendPercent: number | null = null): CardInput {
|
||||
return { cardId: 'c1', pageId: 1, title: 'T', category: 'Science', rarity: 'Common',
|
||||
snapshot: { stats }, live: { trendPercent } };
|
||||
}
|
||||
|
||||
test('percentile counts cuts strictly below plus half of equal ones, rounded down (§1.1)', () => {
|
||||
assert.equal(percentile(0, LINEAR), 0);
|
||||
assert.equal(percentile(50, LINEAR), 49); // 49 below + 0.5 equal → 49
|
||||
assert.equal(percentile(50.5, LINEAR), 50);
|
||||
assert.equal(percentile(1000, LINEAR), 99);
|
||||
assert.equal(percentile(5, [5, 5, 5, 5]), 2);
|
||||
assert.equal(percentile(5, [1, 5, 5, 9]), 2); // 1 + 2/2
|
||||
});
|
||||
|
||||
test('null attention gives a null percentile and is ignored by fame (§1.1, §1.2)', () => {
|
||||
const pct = percentiles({ attention: null, depth: 61, reach: 31 }, TABLE);
|
||||
assert.deepEqual(pct, { attention: null, depth: 60, reach: 30 });
|
||||
assert.equal(fame(pct), 45);
|
||||
});
|
||||
|
||||
test('fame rounds half up', () => {
|
||||
assert.equal(fame({ attention: 10, depth: 11, reach: null }), 11); // 10.5 → 11
|
||||
assert.equal(fame({ attention: 10, depth: 10, reach: 11 }), 10); // 10.33 → 10
|
||||
assert.equal(fame({ attention: 10, depth: 11, reach: 11 }), 11); // 10.67 → 11
|
||||
});
|
||||
|
||||
test('cost is 1 + thresholds ≤ fame, spanning 1–6 (§1.2)', () => {
|
||||
const t = RULES.costThresholds;
|
||||
assert.equal(costFor(0, t), 1);
|
||||
assert.equal(costFor(14, t), 1);
|
||||
assert.equal(costFor(15, t), 2);
|
||||
assert.equal(costFor(54, t), 3);
|
||||
assert.equal(costFor(55, t), 4);
|
||||
assert.equal(costFor(89, t), 5);
|
||||
assert.equal(costFor(90, t), 6);
|
||||
assert.equal(costFor(100, t), 6);
|
||||
});
|
||||
|
||||
test('home stat is the highest percentile, ties broken depth > reach > attention (§1.4)', () => {
|
||||
assert.equal(homeStat({ attention: 90, depth: 10, reach: 10 }), 'attention');
|
||||
assert.equal(homeStat({ attention: 50, depth: 50, reach: 50 }), 'depth');
|
||||
assert.equal(homeStat({ attention: 50, depth: 40, reach: 50 }), 'reach');
|
||||
assert.equal(homeStat({ attention: 60, depth: 40, reach: 60 }), 'reach');
|
||||
assert.equal(homeStat({ attention: null, depth: 0, reach: 0 }), 'depth');
|
||||
assert.equal(homeStat({ attention: null, depth: 0, reach: 1 }), 'reach');
|
||||
});
|
||||
|
||||
test('trend is ±1 at the inclusive thresholds and 0 for null (§1.6)', () => {
|
||||
assert.equal(trendFor(25, RULES), 1);
|
||||
assert.equal(trendFor(24.9, RULES), 0);
|
||||
assert.equal(trendFor(-25, RULES), -1);
|
||||
assert.equal(trendFor(-24.9, RULES), 0);
|
||||
assert.equal(trendFor(null, RULES), 0);
|
||||
assert.equal(trendFor(Number.NaN, RULES), 0);
|
||||
assert.equal(trendFor(1e9, RULES), 1); // inflated live views are still worth only +1
|
||||
});
|
||||
|
||||
test('deriveCard assembles cost, power, home, faction and trend', () => {
|
||||
const card = deriveCard(input({ attention: 81, depth: 71, reach: 61 }, 40), RULES, TABLE);
|
||||
// pct 80/70/60 → fame 70 → cost 4 → power 5
|
||||
assert.deepEqual(card, { cardId: 'c1', pageId: 1, title: 'T', faction: 'Science', rarity: 'Common',
|
||||
cost: 4, power: 5, home: 'attention', trend: 1, keyword: null });
|
||||
});
|
||||
|
||||
test('deriveCard passes the keyword picker the derived card', () => {
|
||||
const card = deriveCard(input({ attention: 10, depth: 20, reach: 30 }), RULES, TABLE,
|
||||
base => `${base.faction}:${base.home}:${base.cost}`);
|
||||
assert.equal(card.keyword, 'Science:reach:2');
|
||||
});
|
||||
|
||||
test('power depends only on cost: forged 100/100/100 stats only move a card up the curve (§1.3)', () => {
|
||||
const forged = deriveCard(input({ attention: 100, depth: 100, reach: 100 }), RULES, TABLE);
|
||||
assert.equal(forged.cost, 6);
|
||||
assert.equal(forged.power, RULES.powerByCost[6]);
|
||||
forAll(300, g => {
|
||||
const stats = { attention: g.bool(0.1) ? null : g.int(0, 100), depth: g.int(0, 100), reach: g.int(0, 100) };
|
||||
const card = deriveCard(input(stats, g.bool(0.2) ? null : g.int(-100, 100)), RULES, TABLE);
|
||||
assert.ok(card.cost >= 1 && card.cost <= 6);
|
||||
assert.equal(card.power, RULES.powerByCost[card.cost]);
|
||||
assert.ok(stats[card.home] !== null, 'home is never a null stat');
|
||||
// Raising any single stat never lowers cost.
|
||||
const bumped = { ...stats, depth: Math.min(100, stats.depth + g.int(1, 30)) };
|
||||
assert.ok(deriveCard(input(bumped), RULES, TABLE).cost >= card.cost);
|
||||
});
|
||||
});
|
||||
|
||||
test('deriveCard rejects a rules config without a power for the derived cost', () => {
|
||||
assert.throws(() => deriveCard(input({ attention: 100, depth: 100, reach: 100 }),
|
||||
{ ...RULES, powerByCost: [0, 1, 2] }, TABLE), RangeError);
|
||||
});
|
||||
@@ -1,95 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
DEFAULT_RULESET, IllegalActionError, Rng, applyAction, createMatch, deserialize, isOver, legalActions,
|
||||
parseRuleset, replay, result, serialize, starterDeck, viewFor, type Action, type GameCard, type MatchState, type PlayerId,
|
||||
} from '../shared/game/index.ts';
|
||||
|
||||
const decks = (seed = 'd'): [GameCard[], GameCard[]] => [starterDeck(`${seed}-a`), starterDeck(`${seed}-b`)];
|
||||
|
||||
function randomPlay(seed: string, ruleset = DEFAULT_RULESET): MatchState {
|
||||
let state = createMatch(ruleset, decks(seed), seed);
|
||||
const chooser = Rng.fromSeed(`bot:${seed}`);
|
||||
for (let steps = 0; !isOver(state); steps++) {
|
||||
assert.ok(steps < 1000, 'match must terminate');
|
||||
const player = chooser.int(2) as PlayerId;
|
||||
const actions = legalActions(state, player);
|
||||
if (!actions.length) continue;
|
||||
state = applyAction(state, chooser.pick(actions));
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
test('rng is deterministic and seed-sensitive', () => {
|
||||
const a = Rng.fromSeed('x'), b = Rng.fromSeed('x'), c = Rng.fromSeed('y');
|
||||
const seq = (r: Rng) => Array.from({ length: 8 }, () => r.nextUint32());
|
||||
assert.deepEqual(seq(a), seq(b));
|
||||
assert.notDeepEqual(seq(Rng.fromSeed('x')), seq(c));
|
||||
const r = Rng.fromSeed('bounds');
|
||||
for (let i = 0; i < 1000; i++) { const n = r.int(7); assert.ok(n >= 0 && n < 7); }
|
||||
});
|
||||
|
||||
test('default ruleset validates; bad rulesets are rejected', () => {
|
||||
assert.deepEqual(parseRuleset(DEFAULT_RULESET), DEFAULT_RULESET);
|
||||
assert.throws(() => parseRuleset({ ...DEFAULT_RULESET, maxTurns: 99 }));
|
||||
assert.throws(() => parseRuleset({ ...DEFAULT_RULESET, keywords: { nope: {} } }));
|
||||
assert.throws(() => parseRuleset({ ...DEFAULT_RULESET, extra: 1 }));
|
||||
});
|
||||
|
||||
test('starter decks are legal, deterministic and non-NFT', () => {
|
||||
const deck = starterDeck('s');
|
||||
assert.equal(deck.length, 12);
|
||||
assert.deepEqual(deck, starterDeck('s'));
|
||||
assert.ok(deck.every(card => card.source === 'starter'));
|
||||
assert.deepEqual(deck.map(c => c.cost).sort().join(''), '112233445566');
|
||||
});
|
||||
|
||||
test('match setup: hands, energy, turn 1', () => {
|
||||
const state = createMatch(DEFAULT_RULESET, decks(), 'setup');
|
||||
assert.equal(state.turn, 1);
|
||||
for (const p of state.players) { assert.equal(p.hand.length, 4); assert.equal(p.deck.length, 8); assert.equal(p.energy, 1); }
|
||||
assert.throws(() => createMatch(DEFAULT_RULESET, [decks()[0].slice(0, 5), decks()[1]], 's'), IllegalActionError);
|
||||
});
|
||||
|
||||
test('staging is hidden from the opponent until reveal', () => {
|
||||
let state = createMatch(DEFAULT_RULESET, decks(), 'hidden');
|
||||
const play = legalActions(state, 0).find(a => a.type === 'play') as Extract<Action, { type: 'play' }>;
|
||||
assert.ok(play, 'turn 1 should have a 1-cost play');
|
||||
state = applyAction(state, play);
|
||||
assert.equal(viewFor(state, 1).opponent.stagedCount, 1);
|
||||
assert.equal(viewFor(state, 1).lanes[play.lane].cards[1].length, 0);
|
||||
assert.equal(JSON.stringify(viewFor(state, 1)).includes(`"${play.cardId}"`), false);
|
||||
state = applyAction(state, { type: 'endTurn', player: 0 });
|
||||
state = applyAction(state, { type: 'endTurn', player: 1 });
|
||||
assert.equal(state.turn, 2);
|
||||
assert.equal(viewFor(state, 1).lanes[play.lane].cards[1][0].card.id, play.cardId);
|
||||
assert.throws(() => applyAction(state, { type: 'play', player: 0, cardId: play.cardId, lane: 0 }), IllegalActionError);
|
||||
});
|
||||
|
||||
test('unstage refunds energy', () => {
|
||||
let state = createMatch(DEFAULT_RULESET, decks(), 'unstage');
|
||||
const play = legalActions(state, 0).find(a => a.type === 'play') as Extract<Action, { type: 'play' }>;
|
||||
state = applyAction(state, play);
|
||||
state = applyAction(state, { type: 'unstage', player: 0, cardId: play.cardId });
|
||||
assert.equal(state.players[0].energy, 1);
|
||||
assert.equal(state.players[0].staged.length, 0);
|
||||
});
|
||||
|
||||
test('concede ends the match for the other player', () => {
|
||||
const state = applyAction(createMatch(DEFAULT_RULESET, decks(), 'c'), { type: 'concede', player: 1 });
|
||||
assert.equal(isOver(state), true);
|
||||
assert.equal(result(state)?.winner, 0);
|
||||
assert.deepEqual(legalActions(state, 0), []);
|
||||
});
|
||||
|
||||
test('random legal play terminates within maxTurns, and replays and serialises exactly', () => {
|
||||
for (let i = 0; i < 40; i++) {
|
||||
const seed = `prop-${i}`;
|
||||
const end = randomPlay(seed);
|
||||
const r = result(end)!;
|
||||
assert.ok(r.turns <= DEFAULT_RULESET.maxTurns);
|
||||
assert.deepEqual(randomPlay(seed), end);
|
||||
assert.deepEqual(replay(DEFAULT_RULESET, decks(seed), seed, end.actions), end);
|
||||
assert.deepEqual(deserialize(serialize(end)), end);
|
||||
}
|
||||
});
|
||||
@@ -1,147 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { KEYWORDS, Rng, hiddenFrom, laneFaction, parseRuleset } from '../shared/game/index.ts';
|
||||
import { card, cardPower, emptyBoard, endOfTurn, lanePower, place, reveal, testRules } from './game/build.ts';
|
||||
|
||||
test('every keyword has an id matching its key, a name and rules text', () => {
|
||||
for (const [id, def] of Object.entries(KEYWORDS)) {
|
||||
assert.equal(def.id, id);
|
||||
assert.ok(def.name && def.text, `${id} needs name and text`);
|
||||
}
|
||||
});
|
||||
|
||||
test('the all-keywords test ruleset validates', () => {
|
||||
assert.doesNotThrow(() => parseRuleset(testRules()));
|
||||
});
|
||||
|
||||
test('Edition: +2 for each other copy of the same article on your side, any lane', () => {
|
||||
const s = emptyBoard();
|
||||
const a = place(s, 0, 0, card({ pageId: 42, power: 5, keyword: 'edition' }));
|
||||
assert.equal(cardPower(s, a), 5);
|
||||
const b = place(s, 0, 2, card({ pageId: 42, power: 5, keyword: 'edition' }));
|
||||
assert.equal(cardPower(s, a), 7);
|
||||
assert.equal(cardPower(s, b), 7);
|
||||
place(s, 1, 0, card({ pageId: 42, power: 5 })); // the opponent's copy doesn't count
|
||||
assert.equal(cardPower(s, a), 7);
|
||||
});
|
||||
|
||||
test('Translated: +1 to your first card in each other lane that has one', () => {
|
||||
const s = emptyBoard();
|
||||
const left = place(s, 0, 0, card({ power: 2 }));
|
||||
const leftSecond = place(s, 0, 0, card({ power: 2 }));
|
||||
const enemy = place(s, 1, 2, card({ power: 2 }));
|
||||
const t = reveal(s, 0, 1, card({ power: 4, keyword: 'translated' }));
|
||||
assert.equal(left.bonus, 1);
|
||||
assert.equal(leftSecond.bonus, 0);
|
||||
assert.equal(enemy.bonus, 0);
|
||||
assert.equal(t.bonus, 0);
|
||||
});
|
||||
|
||||
test('Viral: adds a 1-power Mention token to a random other lane with space', () => {
|
||||
const s = emptyBoard();
|
||||
reveal(s, 0, 1, card({ keyword: 'viral' }), new Rng([9, 9, 9, 9]));
|
||||
const tokens = s.lanes.flatMap((lane, index) => lane.cards[0].filter(c => c.card.meta?.token).map(c => ({ c, index })));
|
||||
assert.equal(tokens.length, 1);
|
||||
assert.notEqual(tokens[0].index, 1);
|
||||
assert.equal(tokens[0].c.lane, tokens[0].index);
|
||||
assert.equal(cardPower(s, tokens[0].c), 1);
|
||||
});
|
||||
|
||||
test('Viral: deterministic for the same rng, and a no-op when no other lane has space', () => {
|
||||
const run = () => { const s = emptyBoard(); reveal(s, 0, 1, card({ id: 'v', name: 'V', pageId: 1, keyword: 'viral' }), new Rng([5, 6, 7, 8])); return s.lanes; };
|
||||
assert.deepEqual(run(), run());
|
||||
const s = emptyBoard();
|
||||
for (const lane of [0, 2]) for (let i = 0; i < s.ruleset.laneCapacity; i++) place(s, 0, lane, card());
|
||||
const before = JSON.stringify(s.lanes);
|
||||
reveal(s, 0, 1, card({ id: 'viral-full', keyword: 'viral' }));
|
||||
s.lanes[1].cards[0].pop();
|
||||
assert.equal(JSON.stringify(s.lanes), before);
|
||||
});
|
||||
|
||||
test('Rising: +1 at each end of turn, capped at +3', () => {
|
||||
const s = emptyBoard();
|
||||
const r = place(s, 0, 1, card({ power: 3, keyword: 'rising' }));
|
||||
const seen = [];
|
||||
for (let i = 0; i < 5; i++) { endOfTurn(s, r); seen.push(cardPower(s, r)); }
|
||||
assert.deepEqual(seen, [4, 5, 6, 6, 6]);
|
||||
});
|
||||
|
||||
test('Rising: the cap counts only Rising gains, not other bonuses', () => {
|
||||
const s = emptyBoard();
|
||||
const r = place(s, 0, 1, card({ power: 3, keyword: 'rising' }));
|
||||
r.bonus += 5; // e.g. Translated/Rally
|
||||
for (let i = 0; i < 4; i++) endOfTurn(s, r);
|
||||
assert.equal(cardPower(s, r), 11);
|
||||
});
|
||||
|
||||
test('Nostalgic: +3 only when losing the lane, judged without itself (DESIGN example: 2 vs 8)', () => {
|
||||
const s = emptyBoard();
|
||||
place(s, 0, 1, card({ power: 2 }));
|
||||
place(s, 1, 1, card({ power: 8 }));
|
||||
const n = reveal(s, 0, 1, card({ power: 3, keyword: 'nostalgic' }));
|
||||
assert.equal(cardPower(s, n), 6);
|
||||
assert.deepEqual(lanePower(s, 1), [8, 8]);
|
||||
});
|
||||
|
||||
test('Nostalgic: no bonus when tied or winning', () => {
|
||||
const s = emptyBoard();
|
||||
place(s, 0, 1, card({ power: 4 }));
|
||||
place(s, 1, 1, card({ power: 4 }));
|
||||
assert.equal(reveal(s, 0, 1, card({ power: 3, keyword: 'nostalgic' })).bonus, 0);
|
||||
const t = emptyBoard();
|
||||
assert.equal(reveal(t, 0, 1, card({ power: 3, keyword: 'nostalgic' })).bonus, 0); // 0 vs 0 is not losing
|
||||
});
|
||||
|
||||
test('Encyclopedic: +2 when alone here; floors its own negative bonus', () => {
|
||||
const s = emptyBoard();
|
||||
const e = reveal(s, 0, 1, card({ power: 7, keyword: 'encyclopedic' }));
|
||||
assert.equal(cardPower(s, e), 9);
|
||||
place(s, 0, 2, card());
|
||||
const f = (() => { place(s, 0, 2, card()); return reveal(s, 0, 2, card({ power: 7, keyword: 'encyclopedic' })); })();
|
||||
assert.equal(cardPower(s, f), 7);
|
||||
f.bonus = -4;
|
||||
assert.equal(cardPower(s, f), 7);
|
||||
});
|
||||
|
||||
test('Local: +2 only in a lane whose faction matches', () => {
|
||||
const s = emptyBoard();
|
||||
assert.equal(laneFaction(s, 0), 'Science');
|
||||
assert.equal(laneFaction(s, 1), null);
|
||||
const home = place(s, 0, 0, card({ power: 2, category: 'Science', keyword: 'local' }));
|
||||
const away = place(s, 0, 1, card({ power: 2, category: 'Science', keyword: 'local' }));
|
||||
const wrong = place(s, 0, 0, card({ power: 2, category: 'History', keyword: 'local' }));
|
||||
assert.deepEqual([cardPower(s, home), cardPower(s, away), cardPower(s, wrong)], [4, 2, 2]);
|
||||
});
|
||||
|
||||
test('laneFaction is null until the portal lane is revealed', () => {
|
||||
const s = emptyBoard(testRules({ laneModifiers: { pool: [], revealTurns: [3, 1, 1], params: { portal: { categoryIndex: 3, amount: 0 } } } }));
|
||||
assert.equal(laneFaction(s, 0), null);
|
||||
s.turn = 3;
|
||||
assert.equal(laneFaction(s, 0), 'Science');
|
||||
});
|
||||
|
||||
test('Wildcard: takes the lane faction on reveal, and then counts for Local', () => {
|
||||
const s = emptyBoard();
|
||||
const w = reveal(s, 0, 0, card({ category: 'Culture', keyword: 'wildcard' }));
|
||||
assert.equal(w.card.category, 'Science');
|
||||
const plain = reveal(s, 0, 1, card({ category: 'Culture', keyword: 'wildcard' }));
|
||||
assert.equal(plain.card.category, 'Culture');
|
||||
});
|
||||
|
||||
test('Obscure: hidden from the opponent only, and only while the match runs', () => {
|
||||
const s = emptyBoard();
|
||||
const o = place(s, 0, 1, card({ keyword: 'obscure' }));
|
||||
assert.equal(hiddenFrom(s, o, 1), true);
|
||||
assert.equal(hiddenFrom(s, o, 0), false);
|
||||
s.phase = 'over';
|
||||
assert.equal(hiddenFrom(s, o, 1), false);
|
||||
});
|
||||
|
||||
test('a keyword the ruleset does not enable has no effect', () => {
|
||||
const s = emptyBoard(testRules({ keywords: {} }));
|
||||
place(s, 0, 0, card({ pageId: 7, power: 5, keyword: 'edition' }));
|
||||
const b = place(s, 0, 1, card({ pageId: 7, power: 5, keyword: 'edition' }));
|
||||
assert.equal(cardPower(s, b), 5);
|
||||
const o = place(s, 0, 2, card({ keyword: 'obscure' }));
|
||||
assert.equal(hiddenFrom(s, o, 1), false);
|
||||
});
|
||||
@@ -1,100 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
createMatch, legalActions, applyAction, isOver, result, serialize, deserialize, starterDeck, PLAYERS,
|
||||
type Action, type GameCard, type MatchState,
|
||||
} from '../shared/game/index.ts';
|
||||
import { forAll, type Gen } from './game/property.ts';
|
||||
import { testRules } from './game/build.ts';
|
||||
|
||||
type State = MatchState;
|
||||
/** Every keyword enabled, so property runs exercise all effects. */
|
||||
const RULES = testRules({ laneModifiers: { pool: ['plain', 'portal', 'narrow'], revealTurns: [1, 2, 3],
|
||||
params: { portal: { categoryIndex: 3, amount: 1 }, narrow: { maxCost: 3 } } } });
|
||||
const KEYWORD_IDS = Object.keys(RULES.keywords);
|
||||
/** Generous bound: a match must finish well within this many actions. */
|
||||
const MAX_ACTIONS = 2000;
|
||||
|
||||
/** Starter deck with random keywords sprinkled in (shared pageIds so Edition can fire). */
|
||||
function randomDeck(g: Gen, tag: string): GameCard[] {
|
||||
return starterDeck(tag, RULES).map(c => ({ ...c, keyword: g.bool(0.6) ? g.pick(KEYWORD_IDS) : null,
|
||||
category: g.pick(['Space', 'Nature', 'People', 'Science', 'History', 'Culture'] as const) }));
|
||||
}
|
||||
|
||||
function randomMatch(g: Gen, seed: number) {
|
||||
return createMatch(RULES, [randomDeck(g, `a-${seed}`), randomDeck(g, `b-${seed}`)], `match-${seed}`);
|
||||
}
|
||||
|
||||
/** Plays random legal actions until the match ends; returns the final state and the action log. */
|
||||
function playOut(g: Gen, state: State, check?: (s: State) => void) {
|
||||
const log: unknown[] = [];
|
||||
let steps = 0;
|
||||
while (!isOver(state)) {
|
||||
const options = PLAYERS.flatMap(player => legalActions(state, player));
|
||||
assert.ok(options.length > 0, `no legal actions in a live match at step ${steps}`);
|
||||
const action = g.pick(options);
|
||||
log.push(action);
|
||||
state = applyAction(state, action);
|
||||
check?.(state);
|
||||
assert.ok(++steps <= MAX_ACTIONS, `match did not terminate within ${MAX_ACTIONS} actions`);
|
||||
}
|
||||
return { state, log };
|
||||
}
|
||||
|
||||
test('random legal play never crashes and always terminates with a result', () => {
|
||||
forAll(200, (g, seed) => {
|
||||
const { state } = playOut(g, randomMatch(g, seed));
|
||||
const outcome = result(state);
|
||||
assert.ok(outcome, 'finished match has a result');
|
||||
});
|
||||
});
|
||||
|
||||
test('same seed and same actions give the same result', () => {
|
||||
forAll(50, (g, seed) => {
|
||||
const decks: [GameCard[], GameCard[]] = [randomDeck(g, `a-${seed}`), randomDeck(g, `b-${seed}`)];
|
||||
const first = playOut(g, createMatch(RULES, decks, `m-${seed}`));
|
||||
// Replay the exact action log on a fresh match from the same seed.
|
||||
let replay = createMatch(RULES, decks, `m-${seed}`);
|
||||
for (const action of first.log) replay = applyAction(replay, action as Action);
|
||||
assert.deepEqual(replay, first.state);
|
||||
assert.deepEqual(result(replay), result(first.state));
|
||||
});
|
||||
});
|
||||
|
||||
test('createMatch is deterministic for a seed and varies across seeds', () => {
|
||||
const a = createMatch(RULES, [starterDeck('x'), starterDeck('y')], 'same');
|
||||
const b = createMatch(RULES, [starterDeck('x'), starterDeck('y')], 'same');
|
||||
assert.deepEqual(a, b);
|
||||
const distinct = new Set(Array.from({ length: 20 }, (_, i) =>
|
||||
JSON.stringify(createMatch(RULES, [starterDeck('x'), starterDeck('y')], `seed-${i}`))));
|
||||
assert.ok(distinct.size > 1, 'different seeds should shuffle differently');
|
||||
});
|
||||
|
||||
test('serialize/deserialize round-trips after every action', () => {
|
||||
forAll(30, (g, seed) => {
|
||||
playOut(g, randomMatch(g, seed), s => {
|
||||
assert.deepEqual(deserialize(serialize(s)), s);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('applyAction never mutates its input state', () => {
|
||||
forAll(30, (g, seed) => {
|
||||
let state = randomMatch(g, seed);
|
||||
let steps = 0;
|
||||
while (!isOver(state) && steps++ < MAX_ACTIONS) {
|
||||
const before = JSON.stringify(state);
|
||||
const action = g.pick(PLAYERS.flatMap(player => legalActions(state, player)));
|
||||
const next = applyAction(state, action);
|
||||
assert.equal(JSON.stringify(state), before);
|
||||
state = next;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
test('a finished match offers no legal actions', () => {
|
||||
forAll(30, (g, seed) => {
|
||||
const { state } = playOut(g, randomMatch(g, seed));
|
||||
for (const player of PLAYERS) assert.deepEqual(legalActions(state, player), []);
|
||||
});
|
||||
});
|
||||
@@ -1,61 +0,0 @@
|
||||
/** Hand-built match states for keyword unit tests. */
|
||||
import {
|
||||
DEFAULT_RULESET, Rng, createMatch, starterDeck, KEYWORDS, cardPower, lanePower,
|
||||
type CardInPlay, type Category, type EffectContext, type GameCard, type MatchState, type PlayerId, type Ruleset,
|
||||
} from '../../shared/game/index.ts';
|
||||
|
||||
export const ALL_KEYWORDS: Ruleset['keywords'] = {
|
||||
rally: { amount: 1 }, anchor: { amount: 2 }, edition: { amount: 2 }, translated: { amount: 1 },
|
||||
viral: { amount: 1 }, rising: { amount: 1, max: 3 }, nostalgic: { amount: 3 }, encyclopedic: { amount: 2 },
|
||||
obscure: {}, local: { amount: 2 }, wildcard: {},
|
||||
};
|
||||
|
||||
/** A ruleset with every keyword on and lane 0 a revealed Science portal (lanes 1–2 plain). */
|
||||
export function testRules(overrides: Partial<Ruleset> = {}): Ruleset {
|
||||
return {
|
||||
...DEFAULT_RULESET, keywords: ALL_KEYWORDS,
|
||||
laneModifiers: { pool: [], revealTurns: [1, 1, 1], params: { portal: { categoryIndex: 3, amount: 0 } } },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
/** An empty board on turn 1 with lane 0 set to the Science portal. */
|
||||
export function emptyBoard(rules = testRules()): MatchState {
|
||||
const state = createMatch(rules, [starterDeck('a', rules), starterDeck('b', rules)], 'keyword-test');
|
||||
for (const lane of state.lanes) lane.cards = [[], []];
|
||||
state.lanes[0].modifier = 'portal';
|
||||
state.lanes[1].modifier = 'plain';
|
||||
state.lanes[2].modifier = 'plain';
|
||||
return state;
|
||||
}
|
||||
|
||||
let serial = 0;
|
||||
export function card(overrides: Partial<GameCard> = {}): GameCard {
|
||||
serial++;
|
||||
return { id: `t${serial}`, name: `Card ${serial}`, pageId: 1000 + serial, category: 'Culture' as Category,
|
||||
cost: 1, power: 2, keyword: null, source: 'loaner', ...overrides };
|
||||
}
|
||||
|
||||
export function place(state: MatchState, owner: PlayerId, lane: number, c: GameCard): CardInPlay {
|
||||
const inPlay: CardInPlay = { card: c, owner, lane, turn: state.turn, bonus: 0 };
|
||||
state.lanes[lane].cards[owner].push(inPlay);
|
||||
return inPlay;
|
||||
}
|
||||
|
||||
export function ctxFor(state: MatchState, keyword: string, lane: number, rng = new Rng([1, 2, 3, 4])): EffectContext {
|
||||
return { state, rng, params: state.ruleset.keywords[keyword] ?? {}, lane, log: () => {}, power: c => cardPower(state, c) };
|
||||
}
|
||||
|
||||
/** Place a card and fire its onReveal, as the engine does at reveal. */
|
||||
export function reveal(state: MatchState, owner: PlayerId, lane: number, c: GameCard, rng?: Rng): CardInPlay {
|
||||
const inPlay = place(state, owner, lane, c);
|
||||
if (c.keyword) KEYWORDS[c.keyword]?.onReveal?.(ctxFor(state, c.keyword, lane, rng), inPlay);
|
||||
return inPlay;
|
||||
}
|
||||
|
||||
export function endOfTurn(state: MatchState, self: CardInPlay): void {
|
||||
const keyword = self.card.keyword;
|
||||
if (keyword) KEYWORDS[keyword]?.endOfTurn?.(ctxFor(state, keyword, self.lane), self);
|
||||
}
|
||||
|
||||
export { cardPower, lanePower };
|
||||
@@ -1,47 +0,0 @@
|
||||
/**
|
||||
* Tiny dependency-free property-testing helper. Each case gets its own seed
|
||||
* so a failure reports a reproducible seed: rerun with PROP_SEED=<seed>.
|
||||
*/
|
||||
export function mulberry32(seed: number): () => number {
|
||||
let a = seed >>> 0;
|
||||
return () => {
|
||||
a = (a + 0x6d2b79f5) >>> 0;
|
||||
let t = a;
|
||||
t = Math.imul(t ^ (t >>> 15), t | 1);
|
||||
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
}
|
||||
|
||||
export interface Gen {
|
||||
rand: () => number;
|
||||
int(min: number, max: number): number;
|
||||
pick<T>(items: readonly T[]): T;
|
||||
bool(p?: number): boolean;
|
||||
}
|
||||
|
||||
export function gen(seed: number): Gen {
|
||||
const rand = mulberry32(seed);
|
||||
return {
|
||||
rand,
|
||||
int: (min, max) => min + Math.floor(rand() * (max - min + 1)),
|
||||
pick: items => {
|
||||
if (!items.length) throw new Error('pick from empty list');
|
||||
return items[Math.floor(rand() * items.length)];
|
||||
},
|
||||
bool: (p = 0.5) => rand() < p,
|
||||
};
|
||||
}
|
||||
|
||||
export function forAll(runs: number, property: (g: Gen, seed: number) => void, baseSeed = 0x5eed): void {
|
||||
const fixed = process.env.PROP_SEED;
|
||||
const seeds = fixed ? [Number(fixed)] : Array.from({ length: runs }, (_, i) => (baseSeed + i * 2654435761) >>> 0);
|
||||
for (const seed of seeds) {
|
||||
try {
|
||||
property(gen(seed), seed);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
throw new Error(`Property failed for seed ${seed} (rerun with PROP_SEED=${seed}): ${message}`, { cause: error });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { WikipediaArticleSource } from '../server/wiki.ts';
|
||||
import { WikipediaEnrichment } from '../server/enrichment.ts';
|
||||
import { ARTICLE_USER_AGENT, ENRICHMENT_USER_AGENT, wikimediaUserAgent } from '../server/wikimedia-user-agent.ts';
|
||||
|
||||
function capture() {
|
||||
const agents: string[] = [];
|
||||
const fetcher: typeof fetch = async (_input, init) => {
|
||||
agents.push(new Headers(init?.headers).get('User-Agent') ?? '');
|
||||
return new Response('rate limited', { status: 429, headers: { 'Content-Type': 'text/plain' } });
|
||||
};
|
||||
return { agents, fetcher };
|
||||
}
|
||||
async function agentsFor(env: string | undefined) {
|
||||
const previous = process.env.WIKIDECK_USER_AGENT;
|
||||
if (env === undefined) delete process.env.WIKIDECK_USER_AGENT; else process.env.WIKIDECK_USER_AGENT = env;
|
||||
try {
|
||||
const article = capture(), enrichment = capture();
|
||||
await assert.rejects(new WikipediaArticleSource(article.fetcher).random());
|
||||
await new WikipediaEnrichment({ fetch: enrichment.fetcher }).getFresh(12345).catch(() => {});
|
||||
return { article: article.agents, enrichment: enrichment.agents };
|
||||
} finally {
|
||||
if (previous === undefined) delete process.env.WIKIDECK_USER_AGENT; else process.env.WIKIDECK_USER_AGENT = previous;
|
||||
}
|
||||
}
|
||||
|
||||
test('default Wikimedia user agents are unchanged when WIKIDECK_USER_AGENT is unset', async () => {
|
||||
assert.equal(ARTICLE_USER_AGENT, 'Wikideck/0.1 (experimental Wikipedia article cards)');
|
||||
assert.equal(ENRICHMENT_USER_AGENT, 'Wikideck/0.1 (Wikipedia off-chain page enrichment)');
|
||||
const { article, enrichment } = await agentsFor(undefined);
|
||||
assert.ok(article.length > 0 && article.every(a => a === ARTICLE_USER_AGENT));
|
||||
assert.ok(enrichment.length > 0 && enrichment.every(a => a === ENRICHMENT_USER_AGENT));
|
||||
});
|
||||
|
||||
test('WIKIDECK_USER_AGENT overrides both Wikimedia clients', async () => {
|
||||
const ua = 'WikiDeck-testnet/0.1 (https://gitea.eom.dev/claude/wikideck; private testnet)';
|
||||
const { article, enrichment } = await agentsFor(ua);
|
||||
assert.ok(article.length > 0 && article.every(a => a === ua));
|
||||
assert.ok(enrichment.length > 0 && enrichment.every(a => a === ua));
|
||||
});
|
||||
|
||||
test('blank, oversized or control-character overrides fall back to the default', () => {
|
||||
for (const bad of ['', ' ', 'x'.repeat(257), 'bad\r\nX-Injected: 1', 'tab\there'])
|
||||
assert.equal(wikimediaUserAgent('fallback', { WIKIDECK_USER_AGENT: bad }), 'fallback');
|
||||
assert.equal(wikimediaUserAgent('fallback', {}), 'fallback');
|
||||
assert.equal(wikimediaUserAgent('fallback', { WIKIDECK_USER_AGENT: ' Custom/1.0 (x) ' }), 'Custom/1.0 (x)');
|
||||
});
|
||||
Reference in New Issue
Block a user