Files
wikideck/server/account/router.ts
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

99 lines
5.0 KiB
TypeScript

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