forked from WikiDeck/wikideck
- 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>
129 lines
7.8 KiB
TypeScript
129 lines
7.8 KiB
TypeScript
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 });
|
|
}
|
|
});
|