eom.dev accounts: Dex OIDC login (PKCE) and wallet linking

- server/account: JWKS-verified Dex ID tokens (RS256, exact issuer,
  audience/azp, exp/iat/nbf with skew, nonce), node-side code exchange as
  the public client "wikideck" (Dex sends no CORS headers), and an
  off-chain SQLite account <-> wallet store. Wallet ownership is proved by
  signing a single-use, domain-tagged off-chain challenge with the
  existing P-256 wallet key; consensus verifySignature is reused read-only.
- Routes under /api/account: config, token, me, challenge, link,
  DELETE link/:address, names (leaderboard display names, never email).
- src/auth: PKCE S256 client, sessionStorage-only tokens, LoginButton with
  initials avatar, wallet link, Capacitor system-browser + custom-scheme
  redirect support (completeLogin for appUrlOpen).
- Hooks: one import + one app.use in server/testnet/http.ts (no CSP
  change), one import + one element in src/App.tsx.
- tests/account-oidc and tests/account-link.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 22:55:51 -05:00
co-authored by Claude Opus 5.5
parent 1d3c5e5743
commit 86fe6bffd3
10 changed files with 770 additions and 1 deletions
+142
View File
@@ -0,0 +1,142 @@
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,' +
'http://127.0.0.1:5173/auth/callback,http://localhost:5173/auth/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; never the email address. */
export function displayName(claims: Pick<IdClaims, 'name' | 'preferred_username' | 'sub'>): string {
const raw = (claims.name || claims.preferred_username || `player-${claims.sub.slice(0, 6)}`).normalize('NFKC');
return raw.replace(/[\u0000-\u001f\u007f]/g, '').trim().slice(0, 48) || 'player';
}
+98
View File
@@ -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;
}
+92
View File
@@ -0,0 +1,92 @@
import { DatabaseSync } from 'node:sqlite';
import { randomBytes } from 'node:crypto';
import { address as walletAddress, verifySignature } from '../testnet/consensus.ts';
import { NETWORK } from '../../shared/testnet.ts';
// 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;
/**
* The exact text a wallet signs to prove ownership. An off-chain message with its own
* domain tag, so it can never be confused with a block, transfer or trade signature.
*/
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]);
}
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);
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;
}
}
+2
View File
@@ -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
View File
@@ -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>}
+76
View File
@@ -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} onClick={() => run(() => login())}>
<span className="wallet-avatar">{busy ? <LoaderCircle className="spin" size={14} /> : <LogIn size={14} />}</span>
Log in with eom.dev
</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} onClick={() => setOpen(o => !o)}>
<Avatar name={me.name} seed={me.sub} />{me.name}
</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. Linking shows your name on leaderboards.</p>}
</div>
{linked ? <p className="auth-ok"><UserRound size={14} /> This wallet is linked.</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>;
}
+11
View File
@@ -0,0 +1,11 @@
.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}
+131
View File
@@ -0,0 +1,131 @@
// 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';
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}`; }
async function api<T>(path: string, init: RequestInit & { token?: string } = {}): Promise<T> {
const { token, ...rest } = init;
const res = await fetch(`/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 challenge; the key signs locally and never leaves the client. */
export async function linkWallet(wallet?: Wallet): Promise<LinkedWallet> {
if (!current) throw new Error('Log in with your eom.dev account first.');
const w = wallet ?? await getWallet();
if (!w) throw new Error('Unlock your wallet first.');
const token = current.idToken;
const challenge = await api<{ nonce: string; message: string; expiresAt: number }>('challenge',
{ method: 'POST', token, body: JSON.stringify({ address: w.address }) });
const signature = await sign(w, challenge.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;
}
+128
View File
@@ -0,0 +1,128 @@
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 } from '../server/account/store.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 });
}
});
+88
View File
@@ -0,0 +1,88 @@
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 Lovelace');
});
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' }), 'ada');
assert.equal(displayName({ sub: 'abcdef123' }), 'player-abcdef');
assert.equal(displayName({ sub: 's', name: 'A\u0000B' + 'x'.repeat(100) }).length, 48);
});