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

142 lines
7.8 KiB
TypeScript

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')
.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: the eom.dev username, else name; never the email address. */
export function displayName(claims: Pick<IdClaims, 'name' | 'preferred_username' | 'sub'>): string {
const raw = (claims.preferred_username || claims.name || `player-${claims.sub.slice(0, 6)}`).normalize('NFKC');
return raw.replace(/[\u0000-\u001f\u007f]/g, '').trim().slice(0, 48) || 'player';
}