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

93 lines
5.3 KiB
TypeScript

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