Files
wikideck/tests/account-oidc.test.ts
T
claudeandClaude Opus 5.5 86fe6bffd3 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>
2026-11-16 22:55:51 -05:00

89 lines
5.3 KiB
TypeScript

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