import { DatabaseSync } from 'node:sqlite'; import { randomBytes } from 'node:crypto'; import { address as walletAddress, verifySignature } from '../testnet/consensus.ts'; import { linkMessage } from '../../shared/account-link.ts'; export { linkMessage }; // 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; export const MAX_PENDING_PER_ACCOUNT = 5; 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(); 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 { const out: Record = {}; 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); let mine = 0; for (const v of this.challenges.values()) if (v.sub === account.sub) mine++; if (mine >= MAX_PENDING_PER_ACCOUNT) throw new LinkError('Too many pending link challenges for this account; wait a few minutes', 429); 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; } }