forked from WikiDeck/wikideck
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>
174 lines
11 KiB
TypeScript
174 lines
11 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, MAX_PENDING_PER_ACCOUNT } from '../server/account/store.ts';
|
|
import { clientLinkMessage, linkMessage } from '../shared/account-link.ts';
|
|
import { nftTransferMessage } from '../shared/testnet.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 });
|
|
}
|
|
});
|
|
|
|
test('account link: pending challenges are capped per account, not just globally', () => withStore(store => {
|
|
const w = wallet();
|
|
for (let i = 0; i < MAX_PENDING_PER_ACCOUNT; i++) store.challenge(ada, w.address);
|
|
code(() => store.challenge(ada, w.address), 429);
|
|
store.challenge(bob, w.address); // other users are unaffected
|
|
}));
|
|
|
|
test('account link (client): only a locally built link message is ever signed', () => {
|
|
const w = wallet(), now = 1_800_000_000_000;
|
|
const good = { nonce: 'a'.repeat(24), expiresAt: now + 60_000 };
|
|
const expected = linkMessage({ issuer: ada.issuer, sub: ada.sub, address: w.address, ...good });
|
|
assert.equal(clientLinkMessage(ada, w.address, { ...good, message: expected }, now), expected);
|
|
// A hostile node substitutes a card-transfer tuple for the link message.
|
|
const transfer = nftTransferMessage({ chainId: 'd'.repeat(64), cardHash: 'b'.repeat(64), from: w.address, to: 'c'.repeat(64), sequence: 1 } as never);
|
|
assert.throws(() => clientLinkMessage(ada, w.address, { ...good, message: transfer }, now), /Nothing was signed/);
|
|
assert.throws(() => clientLinkMessage(ada, w.address, { nonce: '["x"]', expiresAt: good.expiresAt }, now), /invalid link challenge/);
|
|
assert.throws(() => clientLinkMessage(ada, w.address, { nonce: good.nonce, expiresAt: now + 3_600_000 }, now), /invalid link challenge/);
|
|
assert.throws(() => clientLinkMessage(ada, w.address, { nonce: good.nonce, expiresAt: now - 1 }, now), /invalid link challenge/);
|
|
});
|
|
|
|
test('account link (client): linkWallet refuses a transfer message from the node and signs nothing', async () => {
|
|
const w = wallet();
|
|
const store = new Map<string, string>();
|
|
const g = globalThis as Record<string, unknown>;
|
|
const saved = { sessionStorage: g.sessionStorage, fetch: g.fetch };
|
|
g.sessionStorage = { getItem: (k: string) => store.get(k) ?? null, setItem: (k: string, v: string) => { store.set(k, v); },
|
|
removeItem: (k: string) => { store.delete(k); } };
|
|
store.set('wikideck.auth.session', JSON.stringify({ idToken: 'tok', expiresAt: Date.now() + 3_600_000,
|
|
account: { ...ada, wallets: [] } }));
|
|
const transfer = nftTransferMessage({ chainId: 'd'.repeat(64), cardHash: 'b'.repeat(64), from: w.address, to: 'c'.repeat(64), sequence: 1 } as never);
|
|
const requests: string[] = [];
|
|
g.fetch = (async (url: string) => { requests.push(String(url));
|
|
return new Response(JSON.stringify({ nonce: 'a'.repeat(24), expiresAt: Date.now() + 60_000, message: transfer }),
|
|
{ headers: { 'content-type': 'application/json' } }); }) as typeof fetch;
|
|
try {
|
|
const { linkWallet } = await import('../src/auth/session.ts');
|
|
let signed = 0;
|
|
await assert.rejects(linkWallet({ address: w.address, publicKey: w.publicKey }, async () => { signed++; return 'sig'; }), /Nothing was signed/);
|
|
assert.equal(signed, 0);
|
|
assert.deepEqual(requests.map(u => u.split('/').pop()), ['challenge']); // never reached /link
|
|
} finally { g.sessionStorage = saved.sessionStorage; g.fetch = saved.fetch; }
|
|
});
|