Files
wikideck/server/account/router.ts
T
claudeandClaude Opus 5.5 feae445f5a Night 1: eom.dev accounts, Dex OIDC login (PKCE) and wallet linking (#15)
OIDC PKCE login, ID-token verification against Dex JWKS, a client-built wallet link message, an off-chain account and wallet store, and a mobile-safe login button.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 04:12:50 +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;
}