Compare commits

..
Author SHA1 Message Date
claudeandClaude Opus 5.5 2f494e399c deploy/night: autodeploy follows night/2026-11-17 by default
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 21:35:00 -05:00
10 changed files with 10 additions and 690 deletions
+1 -1
View File
@@ -16,7 +16,7 @@ A 3-node **testnet-only** fixture on poweredge-r350. It is reachable on the LAN
- `compose.lan.yaml` also sets, per node:
- `WIKIDECK_USER_AGENT`, a Wikimedia-policy UA with a project URL (#19). Without it, Wikipedia returned 429 to our egress and templates failed.
- the game-mode env from #22: A = classic and trending, B = draft, C = all three.
- `autodeploy.sh` follows the integration branch. Run it from a dedicated detached worktree: `git worktree add --detach ../deploy-src origin/night/2026-11-16 && cd ../deploy-src && deploy/night/autodeploy.sh`. It polls the Gitea API every 3 min and redeploys whenever the head moves.
- `autodeploy.sh` follows the integration branch. Run it from a dedicated detached worktree: `git worktree add --detach ../deploy-src origin/night/2026-11-17 && cd ../deploy-src && deploy/night/autodeploy.sh`. It polls the Gitea API every 3 min and redeploys whenever the head moves.
- `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.
+1 -1
View File
@@ -6,7 +6,7 @@
# because lobbies are in memory and a restart ends games in progress.
# Head detection uses the public Gitea API, which also works where SSH auth isn't available.
set -u
BRANCH=${BRANCH:-night/2026-11-16}
BRANCH=${BRANCH:-night/2026-11-17}
API=${API:-https://gitea.eom.dev/api/v1/repos/claude/wikideck}
INTERVAL=${INTERVAL:-180}
LOG=${LOG:-/tmp/wikideck-night-autodeploy.log}
-73
View File
@@ -1,73 +0,0 @@
# Ownership and collection API (Night 2, #57)
Server-side checks that a player owns the cards they play. Off-chain only: nothing here moves, burns or locks a card, and nothing changes consensus.
## The rules (ruleset data)
| Key | Default | Meaning |
|---|---|---|
| `deckSize` | 40 | A constructed deck has exactly this many cards. A testnet mode file may lower it. |
| `maxCopiesPerPage` | 4 | The MTG-style copy limit. Cards minted from the same Wikipedia `pageId` are separate cards, but at most this many go in one deck. |
| `minConfirmations` | 1 | The confirmations each card's mint block needs. Rated play uses `RATED_MIN_CONFIRMATIONS` = 3. |
## `server/game/ownership.ts` (used by the PvP host)
```ts
verifyAccount(deps, idToken: unknown): Promise<Account>
resolveDeck(deps, account, tokenIds: unknown, opts?: Partial<OwnershipRules>): Promise<ChainCard[]>
collection(deps, account, opts?: { minConfirmations?: number }): Promise<ChainCard[]>
```
- **`deps`** is `{ ledger, accounts, verifyIdToken }`. In production, `server/testnet/http.ts` builds it from the node's `Ledger`, the shared `AccountStore`, and `accountVerifier()` from `server/account/router.ts`. It passes the result to `gameRouter({ ownership })`.
- **`resolveDeck`** accepts token ids only, never card JSON. For each card it checks:
- the card is on the canonical chain (`ledger.nft()`);
- its current owner (after transfers) is one of the account's linked wallets;
- it has enough confirmations;
- the deck size and copy limit.
Each card is rebuilt from its own block (`article` and `statsSnapshot`). The cards come back in the order given.
- **Errors** are thrown as `DeckError { code, status, tokenIds, pageId? }`. `tokenIds` lists every offending card of that class.
| `code` | `status` |
|---|---|
| `auth` | 401 |
| `size` | 400 |
| `duplicate-token` | 400 |
| `unknown-token` (not on chain, or malformed) | 400 |
| `not-owned` (includes "no linked wallet") | 403 |
| `unconfirmed` | 400 |
| `copy-limit` | 400 |
`OwnershipUnavailable` (503) means Dex is unreachable or the chain tip kept moving during a read.
- **`collection`** pages `ledger.deck()` (24 per page) across every linked wallet at one canonical tip, restarting if the tip moves. There is no 128-block snapshot cap.
## `GET /api/game/collection`
`Authorization: Bearer <Dex ID token>` (the same token as `/api/account/me`). Optional: `?minConfirmations=N`.
```ts
{
tip, wallets: string[],
deckSize: 40, copyLimit: 4, maxCopiesPerPage: 4, minConfirmations: 1,
owned: number, // confirmed cards across all linked wallets
playable: number, // Σ min(copies, copyLimit) per pageId
needed: number, // max(0, deckSize - playable)
eligible: boolean, // playable >= deckSize
cards: ChainCard[] // tokenId, owner, confirmations, pageId, title, revisionId, url, extract, imageUrl?,
// height, blockHash, createdAt, powHash, article, statsSnapshot
}
```
| Case | Response |
|---|---|
| No linked wallets | 200 with `cards: []` and `needed: 40` |
| Missing or invalid token | 401 |
| Dex unreachable | 503 |
| Bad query | 400 |
The UI shows `playable / deckSize`, for example "23 / 40 cards", and how to mine.
## Not covered (known gaps)
- **Peer hosts.** Account stores are per node, and a Dex token sent to a peer could be replayed elsewhere (engineer review §2, G6). This API is for the self-hosted node only. The stretch fix is a wallet-signed deck claim.
- **Plausibility of minted stats** (G5): `pageId` → `title` and `revisionId` → `size` are not cross-checked yet.
+2 -17
View File
@@ -12,28 +12,12 @@ export type AccountDeps = { config?: OidcConfig; keys?: DexKeys; store?: Account
type Authed = Request & { account?: Account };
const hex64 = z.string().regex(/^[a-f0-9]{64}$/);
/**
* Verifies a Dex ID token and records the account. Shared with the game routes
* (server/game/collection.ts, the PvP host) so every route uses the same store and keys.
* Throws TokenError (status 401) for a bad token; other errors mean Dex is unreachable.
*/
export function accountVerifier(config: OidcConfig, keys: Pick<DexKeys, 'key'>, store: Pick<AccountStore, 'upsert'>,
now: () => number = Date.now): (idToken: string) => Promise<Account> {
return async idToken => {
const claims = await verifyIdToken(idToken, keys, config, { now: now() });
const account: Account = { sub: claims.sub, issuer: claims.iss, name: displayName(claims), username: claims.preferred_username ?? '' };
store.upsert(account);
return account;
};
}
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 verify = accountVerifier(config, keys, store, now);
const toAccount = (claims: Awaited<ReturnType<typeof verifyIdToken>>): Account =>
({ sub: claims.sub, issuer: claims.iss, name: displayName(claims), username: claims.preferred_username ?? '' });
@@ -42,7 +26,8 @@ export function createAccountRouter(deps: AccountDeps = {}): Router {
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 = await verify(m[1]);
req.account = toAccount(await verifyIdToken(m[1], keys, config, { now: now() }));
store.upsert(req.account);
next();
} catch (e) { next(e); }
};
-76
View File
@@ -1,76 +0,0 @@
/**
* GET /api/game/collection Authorization: Bearer <Dex ID token> [?minConfirmations=N]
*
* Every card the account's linked wallets own (no 128-block cap) and whether that is enough to
* build a deck. Eligibility counts the copy limit: 40 copies of one article is 4 playable cards.
*/
import { Router, type Request, type Response } from 'express';
import { DeckError, collectionAt, ownershipRules, playableCount, verifyAccount,
type ChainCard, type OwnershipDeps, type OwnershipRules } from './ownership.ts';
export type CollectionResponse = {
tip: string;
wallets: string[];
deckSize: number;
/** Max copies per pageId. `maxCopiesPerPage` is the same value under the ruleset's name. */
copyLimit: number;
maxCopiesPerPage: number;
minConfirmations: number;
/** Confirmed cards across all linked wallets. */
owned: number;
/** Σ min(copies, copyLimit) per pageId: the most cards a legal deck can draw from. */
playable: number;
/** max(0, deckSize - playable). */
needed: number;
/** playable >= deckSize. */
eligible: boolean;
/** `duel` is present when the server has a frozen profile for the card (see collectionRouter's `duelCard`). */
cards: (ChainCard & { duel?: unknown })[];
};
export function collectionResponse(deps: Pick<OwnershipDeps, 'ledger' | 'accounts'>, sub: string,
rules?: Partial<OwnershipRules>): CollectionResponse {
const r = ownershipRules(rules);
const { tip, wallets, cards } = collectionAt(deps, { sub }, { minConfirmations: r.minConfirmations });
const playable = playableCount(cards, r.maxCopiesPerPage);
return { tip, wallets, deckSize: r.deckSize, copyLimit: r.maxCopiesPerPage, maxCopiesPerPage: r.maxCopiesPerPage,
minConfirmations: r.minConfirmations, owned: cards.length, playable, needed: Math.max(0, r.deckSize - playable),
eligible: playable >= r.deckSize, cards };
}
export type CollectionRouterDeps = OwnershipDeps & {
rules?: Partial<OwnershipRules>;
/**
* Optional: the same chain card → duel card function the PvP host uses, so the browser shows and
* plays exactly what PvP would. Return undefined while a card's profile is pending; it must not fetch.
*/
duelCard?: (card: ChainCard) => unknown;
};
export function collectionRouter(deps: CollectionRouterDeps): Router {
const router = Router();
router.get('/', async (req: Request, res: Response) => {
res.setHeader('Cache-Control', 'no-store');
const q = req.query.minConfirmations;
if (q !== undefined && (typeof q !== 'string' || !/^[1-9]\d{0,3}$/.test(q))) { res.status(400).json({ error: 'Invalid minConfirmations' }); return; }
const m = /^Bearer ([A-Za-z0-9_.-]{1,8192})$/.exec(req.get('authorization') ?? '');
try {
const account = await verifyAccount(deps, m?.[1]);
const body = collectionResponse(deps, account.sub, { ...deps.rules, ...(q ? { minConfirmations: Number(q) } : {}) });
if (deps.duelCard) {
const toDuel = deps.duelCard;
body.cards = body.cards.map(c => {
let duel: unknown;
try { duel = toDuel(c); } catch { duel = undefined; }
return duel === undefined ? c : { ...c, duel };
});
}
res.json(body);
} catch (e) {
const err = e as Error & { status?: number };
const status = e instanceof DeckError ? err.status! : err.status === 503 ? 503 : 500;
res.status(status).json({ error: status === 500 ? 'Collection unavailable' : err.message });
}
});
return router;
}
+1 -4
View File
@@ -12,14 +12,11 @@ import { createGameRouter } from './router.ts';
import { MatchStore } from './store.ts';
import type { EnginePort } from './engine-port.ts';
import { TrendCache } from './trends.ts';
import type { OwnershipDeps } from './ownership.ts';
type Enrichment = { get(pageId: number): Promise<{ pageviews: { trendPercent: number | null } }> };
export async function gameRouter(options: { dataDir: string | null; enrichment?: Enrichment;
engine?: EnginePort<any, any, any, any>; env?: NodeJS.ProcessEnv; warmTrends?: boolean; handleSignals?: boolean;
/** Server-side ownership (#57) for ./ownership.ts verifyAccount/resolveDeck/collection; absent in Night 1 tests. */
ownership?: OwnershipDeps }): Promise<express.Router> {
engine?: EnginePort<any, any, any, any>; env?: NodeJS.ProcessEnv; warmTrends?: boolean; handleSignals?: boolean }): Promise<express.Router> {
const env = options.env ?? process.env;
const engine = options.engine ?? (await import('./engine-binding.ts')).engineBinding;
const modes = loadModes(env);
-211
View File
@@ -1,211 +0,0 @@
/**
* Server-side ownership for constructed play (Night 2, #57). Signature agreed with host-pvp (#56).
*
* The host never trusts card data from a client. A deck arrives as token ids only; each one
* must be on the canonical chain, owned by one of the account's linked wallets, and confirmed
* enough. The card is then rebuilt from its own block (article + mint stats snapshot).
*
* Off-chain only: nothing here moves, burns or locks a card, and nothing touches consensus.
* No Wikipedia calls; the only I/O is the injected ID-token verifier (Dex JWKS, cached).
*/
import type { Account } from '../account/store.ts';
import type { Article } from '../../shared/protocol.ts';
import type { MintStatsSnapshot } from '../../shared/enrichment.ts';
import type { TestnetBlock } from '../../shared/testnet.ts';
export type OwnershipRules = {
/** Exact deck size for constructed play. Production is 40; a testnet mode file may lower it. */
deckSize: number;
/** MTG-style copy limit: cards minted from the same Wikipedia pageId. */
maxCopiesPerPage: number;
/** Minimum confirmations of each card's mint block (1 casual, 3 rated). */
minConfirmations: number;
};
export const DEFAULT_OWNERSHIP_RULES: Readonly<OwnershipRules> = Object.freeze({ deckSize: 40, maxCopiesPerPage: 4, minConfirmations: 1 });
export const RATED_MIN_CONFIRMATIONS = 3;
/** Upper bound on any deck request we will even look at (a deck is 40; this only guards the loop). */
export const MAX_DECK_TOKENS = 200;
/** Guard against an unbounded collection. Far above anything the chain can mint for one player soon. */
export const MAX_COLLECTION = 20_000;
/** server/testnet/ledger.ts MAX_DECK_PAGE. */
const PAGE = 24;
/** A tip change mid-scan restarts the scan; give up after this many rather than loop forever. */
const MAX_RESTARTS = 4;
// Structural: server/testnet/ledger.ts `Ledger` and server/account/store.ts `AccountStore`
// satisfy these, and tests pass in-memory fixtures.
export type OwnershipLedger = {
nft(tokenId: string): { block: TestnetBlock; owner: string; sequence: number; confirmations: number } | undefined;
deck(address: string, offset: number, limit: number): {
tip: string; total: number; next: number | null;
nfts: { block: TestnetBlock; sequence: number; confirmations: number }[];
};
summary(): { tip: string; height: number };
};
export type OwnershipAccounts = { wallets(sub: string): { address: string }[]; upsert?(a: Account): void };
export type OwnershipDeps = {
ledger: OwnershipLedger;
accounts: OwnershipAccounts;
/** server/account/router.ts accountVerifier(); throws an error with status 401 for a bad token. */
verifyIdToken(idToken: string): Promise<Account>;
};
/** One owned NFT as built from its canonical block (never from client JSON). */
export type ChainCard = {
tokenId: string;
/** Current owner (after transfers), one of the account's linked wallets. */
owner: string;
confirmations: number;
pageId: number;
title: string;
revisionId: number;
url: string;
extract: string;
imageUrl?: string;
height: number;
blockHash: string;
createdAt: number;
powHash: string;
article: Article;
statsSnapshot: MintStatsSnapshot;
};
export type DeckErrorCode = 'auth' | 'size' | 'duplicate-token' | 'unknown-token' | 'not-owned' | 'unconfirmed' | 'copy-limit';
const STATUS: Record<DeckErrorCode, 400 | 401 | 403> = {
auth: 401, size: 400, 'duplicate-token': 400, 'unknown-token': 400, 'not-owned': 403, unconfirmed: 400, 'copy-limit': 400,
};
export class DeckError extends Error {
readonly code: DeckErrorCode;
/** Every offending token of this class, so the UI can highlight them. */
readonly tokenIds: string[];
readonly status: 400 | 401 | 403;
readonly pageId?: number;
constructor(code: DeckErrorCode, message: string, tokenIds: string[] = [], pageId?: number) {
super(message);
this.name = 'DeckError';
this.code = code; this.tokenIds = tokenIds; this.status = STATUS[code];
if (pageId !== undefined) this.pageId = pageId;
}
}
/** Thrown when Dex or the ledger cannot answer right now (not the player's fault). */
export class OwnershipUnavailable extends Error { readonly status = 503; }
const TOKEN = /^[a-f0-9]{64}$/;
const isInt = (n: unknown, min: number, max: number): n is number => Number.isSafeInteger(n) && (n as number) >= min && (n as number) <= max;
/** Merges partial rules over the defaults and rejects nonsense (mode files are data, so validate). */
export function ownershipRules(rules: Partial<OwnershipRules> = {}): OwnershipRules {
const defined = Object.fromEntries(Object.entries(rules).filter(([, v]) => v !== undefined)) as Partial<OwnershipRules>;
const r = { ...DEFAULT_OWNERSHIP_RULES, ...defined };
if (!isInt(r.deckSize, 1, MAX_DECK_TOKENS)) throw new RangeError(`deckSize must be 1..${MAX_DECK_TOKENS}`);
if (!isInt(r.maxCopiesPerPage, 1, MAX_DECK_TOKENS)) throw new RangeError(`maxCopiesPerPage must be 1..${MAX_DECK_TOKENS}`);
if (!isInt(r.minConfirmations, 1, 1_000_000)) throw new RangeError('minConfirmations must be >= 1');
return r;
}
/** Builds the card from the canonical block. `owner` is the current owner from the index, not the miner. */
export function cardFromChain(nft: { block: TestnetBlock; confirmations: number }, owner: string): ChainCard {
const b = structuredClone(nft.block);
const card: ChainCard = { tokenId: b.tokenId, owner, confirmations: nft.confirmations,
pageId: b.article.pageId, title: b.article.title, revisionId: b.article.revisionId, url: b.article.url, extract: b.article.extract,
height: b.height, blockHash: b.hash, createdAt: b.createdAt, powHash: b.powHash, article: b.article, statsSnapshot: b.statsSnapshot };
if (b.article.image) card.imageUrl = b.article.image;
return card;
}
/** Verifies a Dex ID token from a request body. Throws DeckError('auth') or OwnershipUnavailable. */
export async function verifyAccount(deps: Pick<OwnershipDeps, 'verifyIdToken'>, idToken: unknown): Promise<Account> {
if (typeof idToken !== 'string' || !idToken || idToken.length > 8192) throw new DeckError('auth', 'Log in with your eom.dev account to play with your cards');
try { return await deps.verifyIdToken(idToken); }
catch (e) {
if ((e as { status?: number }).status === 401) throw new DeckError('auth', (e as Error).message || 'Log in again with your eom.dev account');
throw new OwnershipUnavailable('eom.dev login is temporarily unavailable');
}
}
/**
* Verifies a constructed deck for an already-verified account. Resolves to the cards in the
* order given, or throws the first class of DeckError found (listing every offending token).
*/
export async function resolveDeck(deps: Pick<OwnershipDeps, 'ledger' | 'accounts'>, account: Pick<Account, 'sub'>, tokenIds: unknown,
opts?: Partial<OwnershipRules>): Promise<ChainCard[]> {
const r = ownershipRules(opts);
if (!Array.isArray(tokenIds) || tokenIds.length > MAX_DECK_TOKENS) throw new DeckError('size', `A deck is exactly ${r.deckSize} cards`);
const invalid = tokenIds.filter(t => typeof t !== 'string' || !TOKEN.test(t)).map(t => String(t).slice(0, 80)).slice(0, 10);
if (invalid.length) throw new DeckError('unknown-token', 'Invalid card identifier', invalid);
const ids = tokenIds as string[];
if (ids.length !== r.deckSize) throw new DeckError('size', `A deck is exactly ${r.deckSize} cards (got ${ids.length})`);
const seen = new Set<string>(), dupes = new Set<string>();
for (const id of ids) (seen.has(id) ? dupes : seen).add(id);
if (dupes.size) throw new DeckError('duplicate-token', 'The same card appears more than once', [...dupes]);
const wallets = new Set(deps.accounts.wallets(account.sub).map(w => w.address));
if (!wallets.size) throw new DeckError('not-owned', 'Link a wallet to your eom.dev account to play with your cards', ids);
const cards: ChainCard[] = [], missing: string[] = [], foreign: string[] = [], young: string[] = [];
for (const id of ids) {
const nft = deps.ledger.nft(id);
if (!nft || nft.block.tokenId !== id) { missing.push(id); continue; }
if (!wallets.has(nft.owner)) { foreign.push(id); continue; }
if (nft.confirmations < r.minConfirmations) { young.push(id); continue; }
cards.push(cardFromChain(nft, nft.owner));
}
if (missing.length) throw new DeckError('unknown-token', 'Card not found on the canonical chain', missing);
if (foreign.length) throw new DeckError('not-owned', 'Card is not owned by a wallet linked to this account', foreign);
if (young.length) throw new DeckError('unconfirmed', `Card needs ${r.minConfirmations} confirmation${r.minConfirmations === 1 ? '' : 's'}`, young);
const byPage = new Map<number, string[]>();
for (const c of cards) byPage.set(c.pageId, [...(byPage.get(c.pageId) ?? []), c.tokenId]);
for (const [pageId, tokens] of byPage)
if (tokens.length > r.maxCopiesPerPage) throw new DeckError('copy-limit', `At most ${r.maxCopiesPerPage} copies of the same article`, tokens, pageId);
return cards;
}
/**
* Every card the account owns across its linked wallets, read at one canonical tip (restarting
* if the tip moves), with no snapshot cap. Only cards with `minConfirmations` (default 1).
*/
export async function collection(deps: Pick<OwnershipDeps, 'ledger' | 'accounts'>, account: Pick<Account, 'sub'>,
opts: { minConfirmations?: number } = {}): Promise<ChainCard[]> {
return collectionAt(deps, account, opts).cards;
}
/** collection() plus the tip and wallets it was read at. Synchronous. */
export function collectionAt(deps: Pick<OwnershipDeps, 'ledger' | 'accounts'>, account: Pick<Account, 'sub'>,
opts: { minConfirmations?: number } = {}): { tip: string; wallets: string[]; cards: ChainCard[] } {
const minConfirmations = ownershipRules({ minConfirmations: opts.minConfirmations }).minConfirmations;
const wallets = [...new Set(deps.accounts.wallets(account.sub).map(w => w.address))];
for (let attempt = 0; attempt <= MAX_RESTARTS; attempt++) {
const tip = deps.ledger.summary().tip;
const cards = scan(deps.ledger, wallets, tip, minConfirmations);
if (cards) return { tip, wallets, cards };
}
throw new OwnershipUnavailable('The chain is moving too fast to read a consistent collection; try again');
}
/** Returns null if the tip moved during the scan. */
function scan(ledger: OwnershipLedger, wallets: string[], tip: string, minConfirmations: number): ChainCard[] | null {
const cards: ChainCard[] = [];
for (const address of wallets) {
let offset: number | null = 0;
while (offset !== null) {
const page = ledger.deck(address, offset, PAGE);
if (page.tip !== tip) return null;
for (const nft of page.nfts) {
if (nft.confirmations >= minConfirmations) cards.push(cardFromChain(nft, address));
if (cards.length > MAX_COLLECTION) throw new OwnershipUnavailable('Collection too large to list');
}
// Defensive: a page that makes no progress would loop forever.
offset = page.next !== null && page.next > offset ? page.next : null;
}
}
return cards;
}
/** How many of these cards a legal deck could use under the copy limit: Σ min(copies, limit) per pageId. */
export function playableCount(cards: Pick<ChainCard, 'pageId'>[], maxCopiesPerPage: number): number {
const perPage = new Map<number, number>();
for (const c of cards) perPage.set(c.pageId, (perPage.get(c.pageId) ?? 0) + 1);
let n = 0; for (const count of perPage.values()) n += Math.min(count, maxCopiesPerPage);
return n;
}
+3 -10
View File
@@ -17,10 +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 { accountVerifier, createAccountRouter } from '../account/router.ts';
import { AccountStore } from '../account/store.ts';
import { DexKeys, oidcConfig } from '../account/oidc.ts';
import { collectionRouter } from '../game/collection.ts';
import { createAccountRouter } from '../account/router.ts';
const root = fileURLToPath(new URL('../../', import.meta.url));
assertLaunchAllowed();
@@ -153,12 +150,8 @@ app.post('/p2p/transaction',workLimit,async(req,res)=>{
const id=await ledger.submitTransaction(transaction);
res.status(202).json({id,status:'pending'});
});
// One account store and one Dex key cache, shared by the account and game routes (#57).
const oidc=oidcConfig(), dexKeys=new DexKeys(oidc), accounts=new AccountStore(resolve(dataDir,'accounts.sqlite'));
const ownership={ledger,accounts,verifyIdToken:accountVerifier(oidc,dexKeys,accounts)};
app.use('/api/account',createAccountRouter({config:oidc,keys:dexKeys,store:accounts}));
app.use('/api/game/collection',collectionRouter(ownership));
app.use('/api/game',await (await import('../game/index.ts')).gameRouter({dataDir,enrichment:wikipediaEnrichment,ownership}));
app.use('/api/account',createAccountRouter({dataDir}));
app.use('/api/game',await (await import('../game/index.ts')).gameRouter({dataDir,enrichment:wikipediaEnrichment}));
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 -6
View File
@@ -10,7 +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, useAccount } from './auth/LoginButton.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';
@@ -48,7 +48,6 @@ function transferProblem(state: TestnetSnapshot, card: CardData, address: string
export default function App() {
const [view, setView] = useState<View>('Discover');
const linkedAccount = useAccount();
const [wallet, setWallet] = useState<Wallet>();
const [snapshot, setSnapshot] = useState<TestnetSnapshot>();
const [rpcAvailable, setRpcAvailable] = useState(false);
@@ -128,10 +127,7 @@ export default function App() {
} catch (e) { setTransferError(message(e)); }
finally { transferInFlight.current = false; setTransferBusy(false); }
};
// Every canonical card owned by this browser's wallet or any wallet linked to the eom.dev account (#57).
// The full canonical chain is paged in by StateClient, so nothing is capped at 128 blocks.
const mine = new Set([wallet?.address, ...(linkedAccount?.wallets ?? []).map(w => w.address)].filter(Boolean));
const owned = snapshot?.blocks.filter(b => mine.has(testnetOwnerOf(snapshot, b.tokenId) ?? '')) ?? [];
const owned = snapshot?.blocks.filter(b => wallet && testnetOwnerOf(snapshot, b.tokenId) === wallet.address) ?? [];
const visibleCards = view === 'My collection' ? owned.map(asCard)
: snapshot?.blocks.length ? [...snapshot.blocks].reverse().slice(0, 12).map(asCard) : samples;
const filtered = visibleCards.filter(c => (category === 'All cards' || c.article.category === category) &&
-291
View File
@@ -1,291 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import express from 'express';
import type { AddressInfo } from 'node:net';
import { resolveDeck, collection, verifyAccount, playableCount, ownershipRules, DEFAULT_OWNERSHIP_RULES,
DeckError, OwnershipUnavailable, type OwnershipDeps, type OwnershipLedger } from '../server/game/ownership.ts';
import { collectionRouter, collectionResponse } from '../server/game/collection.ts';
import type { Account } from '../server/account/store.ts';
import type { TestnetBlock } from '../shared/testnet.ts';
// In-memory fixture: the same shape as Ledger.nft/deck/summary and AccountStore.wallets. No network.
const hex = (s: string) => createHash('sha256').update(s).digest('hex');
const ALICE = hex('alice'), ALICE2 = hex('alice-2'), BOB = hex('bob');
function block(n: number, pageId: number, miner: string): TestnetBlock {
return {
version: 6, network: 'testnet', chainId: 'test', height: n, previousHash: hex(`b${n - 1}`), createdAt: 1_800_000_000 + n,
article: { pageId, title: `Article ${pageId}`, extract: `Extract ${pageId}.`, url: `https://en.wikipedia.org/?curid=${pageId}`,
revisionId: 1000 + pageId, source: 'live', category: 'History' },
statsSnapshot: { capturedAt: '2026-11-17T00:00:00Z', revisionId: 1000 + pageId, pageBytes: 5000 + pageId, languageCount: 3,
languagesTruncated: false, pageviews: null } as unknown as TestnetBlock['statsSnapshot'],
owner: miner, publicKey: 'pk', nonce: 0, target: 'f'.repeat(64), key: '0'.repeat(64), transactionsRoot: '0'.repeat(64),
stateRoot: '0'.repeat(64), hash: hex(`b${n}`), tokenId: hex(`t${n}`), powHash: hex(`p${n}`), signature: 'sig', transactions: [],
} as unknown as TestnetBlock;
}
class FakeLedger implements OwnershipLedger {
tip = 'tip-0';
height = 0;
cards: { block: TestnetBlock; owner: string }[] = [];
deckCalls = 0;
onDeck?: () => void;
mint(owner: string, pageId: number): string {
const b = block(++this.height, pageId, owner);
this.cards.push({ block: b, owner });
this.tip = `tip-${this.height}`;
return b.tokenId;
}
mineEmpty(n = 1) { this.height += n; this.tip = `tip-${this.height}`; }
transfer(token: string, to: string) { this.cards.find(c => c.block.tokenId === token)!.owner = to; }
private conf(b: TestnetBlock) { return this.height - b.height + 1; }
nft(token: string) {
const c = this.cards.find(x => x.block.tokenId === token);
return c ? { block: structuredClone(c.block), owner: c.owner, sequence: 0, confirmations: this.conf(c.block) } : undefined;
}
deck(address: string, offset: number, limit: number) {
this.deckCalls++;
assert.ok(limit <= 24, 'ledger pages are at most 24');
const mine = this.cards.filter(c => c.owner === address);
const nfts = mine.slice(offset, offset + limit).map(c => ({ block: structuredClone(c.block), sequence: 0, confirmations: this.conf(c.block) }));
const result = { tip: this.tip, total: mine.length, next: offset + nfts.length < mine.length ? offset + nfts.length : null, nfts };
this.onDeck?.();
return result;
}
summary() { return { tip: this.tip, height: this.height, network: 'testnet', chainId: 'test' }; }
}
function fixture(wallets: Record<string, string[]> = { alice: [ALICE, ALICE2], bob: [BOB] }) {
const ledger = new FakeLedger();
const deps: OwnershipDeps = { ledger, accounts: { wallets: sub => (wallets[sub] ?? []).map(address => ({ address })) },
verifyIdToken: async (t: string): Promise<Account> => {
const m = /^good\.token\.(\w+)$/.exec(t);
if (m) return { sub: m[1], issuer: 'https://dex.example/', name: m[1], username: m[1] };
if (t === 'dex.is.down') throw new Error('fetch failed');
throw Object.assign(new Error('Token expired'), { status: 401 });
} };
return { ledger, deps };
}
/** n cards for `owner`, distinct pageIds starting at `firstPage`. */
const mintMany = (l: FakeLedger, owner: string, n: number, firstPage = 1) => Array.from({ length: n }, (_, i) => l.mint(owner, firstPage + i));
const ALICE_ACCT = { sub: 'alice' }, BOB_ACCT = { sub: 'bob' };
async function rejects(p: Promise<unknown>, code: string, tokenIds?: string[]) {
await assert.rejects(p, (e: unknown) => {
assert.ok(e instanceof DeckError, String(e));
assert.equal(e.code, code);
if (tokenIds) assert.deepEqual(e.tokenIds, tokenIds);
return true;
});
}
test('defaults are a 40-card deck, 4 copies per article, 1 confirmation', () => {
assert.deepEqual({ ...DEFAULT_OWNERSHIP_RULES }, { deckSize: 40, maxCopiesPerPage: 4, minConfirmations: 1 });
assert.equal(ownershipRules({ deckSize: 10, minConfirmations: undefined }).minConfirmations, 1);
assert.throws(() => ownershipRules({ deckSize: 0 }), RangeError);
assert.throws(() => ownershipRules({ maxCopiesPerPage: 1.5 }), RangeError);
assert.throws(() => ownershipRules({ minConfirmations: 0 }), RangeError);
});
test('verifyAccount maps token failures to DeckError(auth) and Dex outages to OwnershipUnavailable', async () => {
const { deps } = fixture();
assert.equal((await verifyAccount(deps, 'good.token.alice')).sub, 'alice');
for (const t of [undefined, '', 42, 'x'.repeat(9000)]) await rejects(verifyAccount(deps, t), 'auth');
await assert.rejects(verifyAccount(deps, 'bad'), (e: unknown) => e instanceof DeckError && e.code === 'auth' && e.status === 401 && e.message === 'Token expired');
await assert.rejects(verifyAccount(deps, 'dex.is.down'), (e: unknown) => e instanceof OwnershipUnavailable && e.status === 503);
});
test('resolveDeck accepts 40 owned cards across linked wallets and builds them from the chain, in order', async () => {
const { ledger, deps } = fixture();
const ids = [...mintMany(ledger, ALICE, 25, 1), ...mintMany(ledger, ALICE2, 15, 100)].reverse();
const cards = await resolveDeck(deps, ALICE_ACCT, ids);
assert.equal(cards.length, 40);
assert.deepEqual(cards.map(c => c.tokenId), ids);
const c = cards.find(x => x.pageId === 100)!;
const chain = ledger.nft(c.tokenId)!.block;
assert.equal(c.owner, ALICE2);
assert.equal(c.title, 'Article 100');
assert.equal(c.revisionId, 1100);
assert.equal(c.article.title, 'Article 100');
assert.equal(c.statsSnapshot.pageBytes, 5100);
assert.equal(c.blockHash, chain.hash);
assert.equal(c.powHash, chain.powHash);
assert.equal(c.height, chain.height);
});
test('resolveDeck takes token ids only: card data is never taken from the client', async () => {
const { ledger, deps } = fixture();
const ids = mintMany(ledger, ALICE, 40);
const forged = ids.map(tokenId => ({ tokenId, article: { title: 'Barack Obama' }, statsSnapshot: { pageBytes: 9e9 } }));
await rejects(resolveDeck(deps, ALICE_ACCT, forged), 'unknown-token');
});
test('resolveDeck enforces the exact deck size from ruleset data', async () => {
const { ledger, deps } = fixture();
const ids = mintMany(ledger, ALICE, 41);
for (const deck of [ids.slice(0, 39), ids, [], 'nope', null, Array(10_000).fill(ids[0])]) await rejects(resolveDeck(deps, ALICE_ACCT, deck), 'size');
assert.equal((await resolveDeck(deps, ALICE_ACCT, ids.slice(0, 10), { deckSize: 10 })).length, 10, 'a testnet mode may lower deckSize');
});
test('resolveDeck rejects malformed and duplicated token ids', async () => {
const { ledger, deps } = fixture();
const ids = mintMany(ledger, ALICE, 40);
await rejects(resolveDeck(deps, ALICE_ACCT, [...ids.slice(0, 39), 'ABC']), 'unknown-token', ['ABC']);
await rejects(resolveDeck(deps, ALICE_ACCT, [...ids.slice(0, 39), ids[0]]), 'duplicate-token', [ids[0]]);
});
test('resolveDeck requires a linked wallet', async () => {
const { ledger, deps } = fixture();
const ids = mintMany(ledger, ALICE, 40);
await assert.rejects(resolveDeck(deps, { sub: 'stranger' }, ids), (e: unknown) => e instanceof DeckError && e.code === 'not-owned' && e.status === 403 && /Link a wallet/.test(e.message));
});
test('resolveDeck rejects unknown cards and cards owned by someone else, listing every one', async () => {
const { ledger, deps } = fixture();
const ids = mintMany(ledger, ALICE, 38);
const bobs = mintMany(ledger, BOB, 2, 500);
await rejects(resolveDeck(deps, ALICE_ACCT, [...ids, ...bobs]), 'not-owned', bobs);
await rejects(resolveDeck(deps, ALICE_ACCT, [...ids, hex('nope'), bobs[0]]), 'unknown-token', [hex('nope')]);
// Bob cannot field Alice's cards either, even though they exist.
await rejects(resolveDeck(deps, BOB_ACCT, [...ids, ...bobs]), 'not-owned', ids);
});
test('ownership follows transfers: the current owner, not the miner, may play the card', async () => {
const { ledger, deps } = fixture();
const ids = mintMany(ledger, ALICE, 40);
ledger.transfer(ids[7], BOB);
await rejects(resolveDeck(deps, ALICE_ACCT, ids), 'not-owned', [ids[7]]);
const cards = await resolveDeck(deps, BOB_ACCT, [ids[7], ...mintMany(ledger, BOB, 39, 300)]);
assert.equal(cards[0].owner, BOB);
});
test('resolveDeck requires minConfirmations (3 for rated play)', async () => {
const { ledger, deps } = fixture();
const ids = mintMany(ledger, ALICE, 40);
// The last card has 1 confirmation, the one before it 2.
await rejects(resolveDeck(deps, ALICE_ACCT, ids, { minConfirmations: 3 }), 'unconfirmed', ids.slice(38));
ledger.mineEmpty(2);
assert.equal((await resolveDeck(deps, ALICE_ACCT, ids, { minConfirmations: 3 })).length, 40);
});
test('duplicates of an article count as separate cards, up to 4 copies per pageId', async () => {
const { ledger, deps } = fixture();
const base = mintMany(ledger, ALICE, 35, 1);
const copies = Array.from({ length: 5 }, () => ledger.mint(ALICE, 777));
await assert.rejects(resolveDeck(deps, ALICE_ACCT, [...base, ...copies]),
(e: unknown) => e instanceof DeckError && e.code === 'copy-limit' && e.pageId === 777 && e.tokenIds.length === 5);
const cards = await resolveDeck(deps, ALICE_ACCT, [...base, ...copies.slice(0, 4), ledger.mint(ALICE, 900)]);
assert.equal(cards.filter(c => c.pageId === 777).length, 4);
assert.equal((await resolveDeck(deps, ALICE_ACCT, [...base, ...copies], { maxCopiesPerPage: 5 })).length, 40, 'the copy limit is ruleset data');
});
test('playableCount applies the copy limit', () => {
const cards = [1, 1, 1, 1, 1, 1, 2, 3].map(pageId => ({ pageId }));
assert.equal(playableCount(cards, 4), 6);
assert.equal(playableCount(cards, 1), 3);
});
test('collection lists every owned card across wallets with no 128-block cap', async () => {
const { ledger, deps } = fixture();
mintMany(ledger, ALICE, 150, 1);
mintMany(ledger, BOB, 10, 1000);
mintMany(ledger, ALICE2, 3, 2000);
const cards = await collection(deps, ALICE_ACCT);
assert.equal(cards.length, 153);
assert.equal(new Set(cards.map(x => x.tokenId)).size, 153);
assert.ok(cards.every(x => x.owner === ALICE || x.owner === ALICE2));
const r = collectionResponse(deps, 'alice');
assert.equal(r.owned, 153); assert.equal(r.playable, 153); assert.equal(r.needed, 0); assert.equal(r.eligible, true);
assert.deepEqual(r.wallets, [ALICE, ALICE2]);
assert.equal(r.tip, ledger.tip);
assert.deepEqual(await collection(deps, { sub: 'stranger' }), []);
});
test('collection shows progress toward 40 and applies the copy limit to eligibility', () => {
const { ledger, deps } = fixture();
mintMany(ledger, ALICE, 20, 1);
for (let i = 0; i < 10; i++) ledger.mint(ALICE, 4242);
const c = collectionResponse(deps, 'alice');
assert.equal(c.owned, 30); assert.equal(c.playable, 24); assert.equal(c.needed, 16); assert.equal(c.eligible, false);
assert.equal(c.deckSize, 40); assert.equal(c.copyLimit, 4); assert.equal(c.maxCopiesPerPage, 4);
assert.equal(collectionResponse(deps, 'alice', { deckSize: 20 }).eligible, true);
const none = collectionResponse(deps, 'stranger');
assert.equal(none.owned, 0); assert.equal(none.needed, 40); assert.deepEqual(none.cards, []);
});
test('collection only counts cards with enough confirmations', async () => {
const { ledger, deps } = fixture();
mintMany(ledger, ALICE, 5);
assert.equal((await collection(deps, ALICE_ACCT, { minConfirmations: 3 })).length, 3);
});
test('collection restarts when the tip moves mid-scan and gives up if it never settles', async () => {
const { ledger, deps } = fixture();
mintMany(ledger, ALICE, 60);
let moves = 1;
ledger.onDeck = () => { if (moves-- > 0) ledger.mint(ALICE, 9999); };
const c = collectionResponse(deps, 'alice');
assert.equal(c.owned, 61);
assert.equal(c.tip, ledger.tip);
ledger.onDeck = () => { ledger.mineEmpty(); };
await assert.rejects(collection(deps, ALICE_ACCT), OwnershipUnavailable);
});
async function serve(router: express.Router) {
const app = express();
app.use('/api/game/collection', router);
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 AddressInfo).port}/api/game/collection`;
return { base, close: () => new Promise(r => server.close(r)) };
}
test('GET /api/game/collection requires a verified eom.dev token (local loopback only, no upstream)', async () => {
const { ledger, deps } = fixture();
mintMany(ledger, ALICE, 23);
const { base, close } = await serve(collectionRouter(deps));
const as = (t: string) => ({ headers: { authorization: `Bearer ${t}` } });
try {
let res = await fetch(base);
assert.equal(res.status, 401);
res = await fetch(base, as('bad.token.x!'));
assert.equal(res.status, 401);
res = await fetch(base, as('expired.token.x'));
assert.equal(res.status, 401);
assert.equal((await res.json()).error, 'Token expired');
res = await fetch(base, as('dex.is.down'));
assert.equal(res.status, 503);
res = await fetch(`${base}?minConfirmations=abc`, as('good.token.alice'));
assert.equal(res.status, 400);
res = await fetch(base, as('good.token.alice'));
assert.equal(res.status, 200);
assert.equal(res.headers.get('cache-control'), 'no-store');
const body = await res.json();
assert.equal(body.owned, 23); assert.equal(body.playable, 23); assert.equal(body.needed, 17);
assert.equal(body.eligible, false); assert.equal(body.deckSize, 40); assert.equal(body.copyLimit, 4);
assert.equal(body.cards.length, 23);
assert.equal(body.cards[0].title, 'Article 1');
assert.equal(body.cards[0].pageId, 1);
res = await fetch(`${base}?minConfirmations=3`, as('good.token.alice'));
assert.equal((await res.json()).owned, 21);
res = await fetch(base, as('good.token.bob'));
assert.equal((await res.json()).owned, 0);
} finally { await close(); }
});
test('GET /api/game/collection attaches the injected duel card when one is ready, and omits it otherwise', async () => {
const { ledger, deps } = fixture();
mintMany(ledger, ALICE, 3);
const duelCard = (c: { pageId: number }) => {
if (c.pageId === 2) return undefined; // profile pending
if (c.pageId === 3) throw new Error('boom'); // never breaks the collection
return { kind: 'Figure', pageId: c.pageId };
};
const { base, close } = await serve(collectionRouter({ ...deps, duelCard }));
try {
const body = await (await fetch(base, { headers: { authorization: 'Bearer good.token.alice' } })).json();
assert.deepEqual(body.cards.map((c: { duel?: unknown }) => c.duel), [{ kind: 'Figure', pageId: 1 }, undefined, undefined]);
assert.ok(!('duel' in body.cards[1]));
} finally { await close(); }
});