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

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

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

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

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

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

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

90 lines
5.2 KiB
TypeScript

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