From 1435eeb1078de2c61ddd89233af774b84cea9318 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 23:04:49 -0500 Subject: [PATCH] account: client builds the link message; mobile top bar; review fixes - shared/account-link.ts: linkMessage + clientLinkMessage. The wallet only signs a message the client builds locally (validated nonce/expiry) and refuses when the node's text differs, so a hostile node or network attacker cannot get a transfer or trade signed (night-review must-fix 1). - Narrow screens (<480px): the account button floats outside the top bar, icon only with aria-label (must-fix 2: 360px overflow). - Leaderboard names prefer preferred_username over the LDAP real name; consent text sits on the Link button. - At most 5 pending link challenges per account (429). - nodeBase(): WIKIDECK_NODE_URL for Capacitor builds. - Tests: hostile transfer message is never signed, per-account cap. Co-Authored-By: Claude Opus 5.5 --- server/account/README.md | 7 +++--- server/account/oidc.ts | 4 +-- server/account/store.ts | 15 +++++------ shared/account-link.ts | 25 +++++++++++++++++++ src/auth/LoginButton.tsx | 14 +++++------ src/auth/auth.css | 10 ++++++++ src/auth/session.ts | 25 ++++++++++++++----- tests/account-link.test.ts | 51 +++++++++++++++++++++++++++++++++++--- tests/account-oidc.test.ts | 5 ++-- 9 files changed, 124 insertions(+), 32 deletions(-) create mode 100644 shared/account-link.ts diff --git a/server/account/README.md b/server/account/README.md index 3f2c722..de49bb7 100644 --- a/server/account/README.md +++ b/server/account/README.md @@ -17,10 +17,10 @@ Off-chain only. Nothing here changes blocks, transfers, trades or validation. 4. The browser keeps the ID token in **sessionStorage** and sends it as `Authorization: Bearer`. 5. **Linking a wallet:** - `POST challenge {address}` → `{nonce, message, expiresAt}` - - the wallet signs `message` locally with `src/wallet.ts` `sign` + - the **client builds the message itself** (`shared/account-link.ts` `clientLinkMessage`). It validates the nonce and expiry, refuses if the node's `message` differs, and signs locally with `src/wallet.ts` `sign`. The wallet never signs node-supplied text. - `POST link {nonce, address, publicKey, signature}` - Nonces are single use, expire after 5 minutes, and are bound to (sub, address). One wallet belongs to one account. + Nonces are single use, expire after 5 minutes, and are bound to (sub, address). There are at most 5 pending per account. One wallet belongs to one account. ## Endpoints (`/api/account/...`) | Method | Path | Auth | Purpose | @@ -31,7 +31,7 @@ Off-chain only. Nothing here changes blocks, transfers, trades or validation. | POST | `challenge` | Bearer | one-time link challenge | | POST | `link` | Bearer | prove wallet ownership, store mapping | | DELETE | `link/:address` | Bearer | unlink | -| GET | `names?addresses=a,b` | none | leaderboard display names (`name` → `preferred_username`; never email) | +| GET | `names?addresses=a,b` | none | leaderboard display names (`preferred_username`, else `name`; never email) | Signed link message (off-chain, domain-tagged): `["wikideck:account-link:v1", NETWORK, issuer, sub, address, nonce, expiresAt]` @@ -46,6 +46,7 @@ Signed link message (off-chain, domain-tagged): - **Storage:** `$WIKIDECK_DATA_DIR/accounts.sqlite`. ## Capacitor +- The UI is bundled locally, so set `globalThis.WIKIDECK_NODE_URL = 'http://192.168.1.32:3101'` before using `src/auth`. That node's POST origin check must allow the app's WebView origin. - Register the URL scheme `dev.eom.wikideck`. - Install `@capacitor/browser` and `@capacitor/app`. - Add the listener: diff --git a/server/account/oidc.ts b/server/account/oidc.ts index 9b80617..a2df418 100644 --- a/server/account/oidc.ts +++ b/server/account/oidc.ts @@ -134,8 +134,8 @@ export async function exchangeCode(keys: DexKeys, input: { code: string; codeVer return { idToken: body.id_token }; } -/** Display name used on leaderboards; never the email address. */ +/** Display name used on leaderboards: the eom.dev username, else name; never the email address. */ export function displayName(claims: Pick): string { - const raw = (claims.name || claims.preferred_username || `player-${claims.sub.slice(0, 6)}`).normalize('NFKC'); + const raw = (claims.preferred_username || claims.name || `player-${claims.sub.slice(0, 6)}`).normalize('NFKC'); return raw.replace(/[\u0000-\u001f\u007f]/g, '').trim().slice(0, 48) || 'player'; } diff --git a/server/account/store.ts b/server/account/store.ts index 6d5405e..3e91dcf 100644 --- a/server/account/store.ts +++ b/server/account/store.ts @@ -1,21 +1,16 @@ 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'; +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; - -/** - * 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 const MAX_PENDING_PER_ACCOUNT = 5; export class LinkError extends Error { readonly status: number; @@ -62,6 +57,8 @@ export class AccountStore { 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 }); diff --git a/shared/account-link.ts b/shared/account-link.ts new file mode 100644 index 0000000..b86bb02 --- /dev/null +++ b/shared/account-link.ts @@ -0,0 +1,25 @@ +import { NETWORK } from './testnet.ts'; + +// Off-chain wallet <-> eom.dev account proof. Pure, shared by node and client so the +// client builds the exact text it signs and never signs server-chosen text. +export type LinkChallenge = { nonce: string; expiresAt: number }; +export const LINK_NONCE = /^[A-Za-z0-9_-]{16,64}$/; +export const LINK_CHALLENGE_MAX_MS = 10 * 60_000; + +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]); +} + +/** Client side: validate a node challenge and build the message locally. Throws on anything unexpected. */ +export function clientLinkMessage(account: { issuer: string; sub: string }, address: string, + challenge: { nonce?: unknown; expiresAt?: unknown; message?: unknown }, now = Date.now()): string { + const { nonce, expiresAt } = challenge; + if (typeof nonce !== 'string' || !LINK_NONCE.test(nonce)) throw new Error('The node sent an invalid link challenge.'); + if (typeof expiresAt !== 'number' || !Number.isSafeInteger(expiresAt) || expiresAt <= now || expiresAt > now + LINK_CHALLENGE_MAX_MS) + throw new Error('The node sent an invalid link challenge.'); + if (!/^[a-f0-9]{64}$/.test(address)) throw new Error('Invalid wallet address.'); + const message = linkMessage({ issuer: account.issuer, sub: account.sub, address, nonce, expiresAt }); + if (challenge.message !== undefined && challenge.message !== message) + throw new Error('The node asked the wallet to sign something other than an account link. Nothing was signed.'); + return message; +} diff --git a/src/auth/LoginButton.tsx b/src/auth/LoginButton.tsx index c8c4da7..de8f235 100644 --- a/src/auth/LoginButton.tsx +++ b/src/auth/LoginButton.tsx @@ -45,30 +45,30 @@ export function LoginButton() { }; if (!me) return - {notice && {notice}} ; const linked = wallet && me.wallets.some(w => w.address === wallet.address); return - {open &&
{me.name}{me.username && @{me.username} · eom.dev}
LINKED WALLETS - {me.wallets.length ? me.wallets.map(w => {short(w.address)}) :

None yet. Linking shows your name on leaderboards.

} + {me.wallets.length ? me.wallets.map(w => {short(w.address)}) :

None yet.

}
{linked ?

This wallet is linked.

- : } + {wallet ? `Link wallet ${short(wallet.address)}` : 'Unlock your wallet to link it'}} {notice &&

{notice}

}
} diff --git a/src/auth/auth.css b/src/auth/auth.css index 4a4f175..3995faf 100644 --- a/src/auth/auth.css +++ b/src/auth/auth.css @@ -9,3 +9,13 @@ .auth-menu-section code{display:block;font-size:11px;margin-top:4px} .auth-menu-section p,.auth-ok{font-size:11px;opacity:.8;margin:4px 0 0;display:flex;align-items:center;gap:6px} .auth-notice{font-size:11px;max-width:260px} +.auth-consent{font-size:11px;line-height:1.5;opacity:.8;margin:0} +.auth-label{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:140px} +/* Narrow screens: the top bar has no spare width, so float the account button outside its flow. */ +@media (max-width:480px){ + .auth-label{display:none} + .auth-wrap{position:fixed;right:14px;bottom:14px;z-index:45} + .auth-wrap .auth-button{border-radius:999px;padding:6px;box-shadow:0 6px 18px rgba(0,0,0,.22)} + .auth-menu{top:auto;bottom:calc(100% + 8px);width:min(280px,calc(100vw - 28px))} + .auth-wrap>.auth-notice{position:absolute;bottom:calc(100% + 8px);right:0;width:min(260px,calc(100vw - 28px))} +} diff --git a/src/auth/session.ts b/src/auth/session.ts index 769592d..6de057d 100644 --- a/src/auth/session.ts +++ b/src/auth/session.ts @@ -3,6 +3,7 @@ // (Dex sends no CORS headers), so there is no browser -> Dex fetch and no CSP change. // Tokens live in sessionStorage (cleared with the tab), never localStorage. import { getWallet, sign, type Wallet } from '../wallet.ts'; +import { clientLinkMessage } from '../../shared/account-link.ts'; export type LinkedWallet = { address: string; linkedAt: number }; export type Account = { sub: string; issuer: string; name: string; username: string; wallets: LinkedWallet[] }; @@ -48,9 +49,15 @@ const capacitor = () => (globalThis as { Capacitor?: CapacitorGlobal }).Capacito export const isNative = () => Boolean(capacitor()?.isNativePlatform?.()); export function redirectUri(): string { return isNative() ? NATIVE_REDIRECT : `${location.origin}${CALLBACK_PATH}`; } +/** + * Node base URL. Empty on the web (same origin). Capacitor builds bundle the UI locally, so the + * app sets `globalThis.WIKIDECK_NODE_URL = 'http://192.168.1.32:3101'` (or similar) before use. + */ +export const nodeBase = () => ((globalThis as { WIKIDECK_NODE_URL?: string }).WIKIDECK_NODE_URL ?? '').replace(/\/+$/, ''); + async function api(path: string, init: RequestInit & { token?: string } = {}): Promise { const { token, ...rest } = init; - const res = await fetch(`/api/account/${path}`, { cache: 'no-store', signal: AbortSignal.timeout(15000), ...rest, + const res = await fetch(`${nodeBase()}/api/account/${path}`, { cache: 'no-store', signal: AbortSignal.timeout(15000), ...rest, headers: { ...(rest.body ? { 'Content-Type': 'application/json' } : {}), ...(token ? { Authorization: `Bearer ${token}` } : {}) } }); const data = await res.json().catch(() => ({})); if (res.status === 401 && token) save(undefined); @@ -108,15 +115,21 @@ export async function refreshAccount(): Promise { return me; } -/** Prove wallet ownership: the node issues a one-time challenge; the key signs locally and never leaves the client. */ -export async function linkWallet(wallet?: Wallet): Promise { +/** + * Prove wallet ownership: the node issues a one-time nonce. The client builds the link message + * itself (shared/account-link.ts) and never signs node-supplied text, so a hostile node or a + * network attacker cannot get a transfer or trade signed. The key never leaves the client. + */ +export async function linkWallet(wallet?: Wallet, signer: (w: Wallet, message: string) => Promise = sign): Promise { if (!current) throw new Error('Log in with your eom.dev account first.'); + const session = current; const w = wallet ?? await getWallet(); if (!w) throw new Error('Unlock your wallet first.'); - const token = current.idToken; - const challenge = await api<{ nonce: string; message: string; expiresAt: number }>('challenge', + const token = session.idToken; + const challenge = await api<{ nonce?: unknown; message?: unknown; expiresAt?: unknown }>('challenge', { method: 'POST', token, body: JSON.stringify({ address: w.address }) }); - const signature = await sign(w, challenge.message); + const message = clientLinkMessage(session.account, w.address, challenge); + const signature = await signer(w, message); const linked = await api('link', { method: 'POST', token, body: JSON.stringify({ nonce: challenge.nonce, address: w.address, publicKey: w.publicKey, signature }) }); await refreshAccount().catch(() => {}); diff --git a/tests/account-link.test.ts b/tests/account-link.test.ts index ece0473..6ef7a0c 100644 --- a/tests/account-link.test.ts +++ b/tests/account-link.test.ts @@ -6,7 +6,9 @@ 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 { 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'; @@ -107,7 +109,7 @@ test('account HTTP: login exchange, bearer auth and wallet link end to end', asy 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'); + 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); @@ -120,9 +122,52 @@ test('account HTTP: login exchange, bearer auth and wallet link end to end', asy 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' }); + 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(); + const g = globalThis as Record; + 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; } +}); diff --git a/tests/account-oidc.test.ts b/tests/account-oidc.test.ts index 5e446bd..e3e5d82 100644 --- a/tests/account-oidc.test.ts +++ b/tests/account-oidc.test.ts @@ -36,7 +36,7 @@ const rejects = (p: Promise, msg: RegExp) => assert.rejects(p, e => e i 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'); + assert.equal(displayName(claims), 'ada'); // username preferred over real name }); test('account: expired tokens are rejected (beyond clock skew)', async () => { @@ -82,7 +82,8 @@ test('account: JWKS is cached and discovery issuer must match', async () => { }); 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', preferred_username: 'ada', name: 'Ada Lovelace' }), 'ada'); + assert.equal(displayName({ sub: 'abcdef123', name: 'Ada Lovelace' }), 'Ada Lovelace'); assert.equal(displayName({ sub: 'abcdef123' }), 'player-abcdef'); assert.equal(displayName({ sub: 's', name: 'A\u0000B' + 'x'.repeat(100) }).length, 48); });