forked from WikiDeck/wikideck
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 <noreply@anthropic.com>
This commit is contained in:
@@ -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`.
|
4. The browser keeps the ID token in **sessionStorage** and sends it as `Authorization: Bearer`.
|
||||||
5. **Linking a wallet:**
|
5. **Linking a wallet:**
|
||||||
- `POST challenge {address}` → `{nonce, message, expiresAt}`
|
- `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}`
|
- `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/...`)
|
## Endpoints (`/api/account/...`)
|
||||||
| Method | Path | Auth | Purpose |
|
| 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 | `challenge` | Bearer | one-time link challenge |
|
||||||
| POST | `link` | Bearer | prove wallet ownership, store mapping |
|
| POST | `link` | Bearer | prove wallet ownership, store mapping |
|
||||||
| DELETE | `link/:address` | Bearer | unlink |
|
| 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):
|
Signed link message (off-chain, domain-tagged):
|
||||||
`["wikideck:account-link:v1", NETWORK, issuer, sub, address, nonce, expiresAt]`
|
`["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`.
|
- **Storage:** `$WIKIDECK_DATA_DIR/accounts.sqlite`.
|
||||||
|
|
||||||
## Capacitor
|
## 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`.
|
- Register the URL scheme `dev.eom.wikideck`.
|
||||||
- Install `@capacitor/browser` and `@capacitor/app`.
|
- Install `@capacitor/browser` and `@capacitor/app`.
|
||||||
- Add the listener:
|
- Add the listener:
|
||||||
|
|||||||
@@ -134,8 +134,8 @@ export async function exchangeCode(keys: DexKeys, input: { code: string; codeVer
|
|||||||
return { idToken: body.id_token };
|
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<IdClaims, 'name' | 'preferred_username' | 'sub'>): string {
|
export function displayName(claims: Pick<IdClaims, 'name' | 'preferred_username' | 'sub'>): 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';
|
return raw.replace(/[\u0000-\u001f\u007f]/g, '').trim().slice(0, 48) || 'player';
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,21 +1,16 @@
|
|||||||
import { DatabaseSync } from 'node:sqlite';
|
import { DatabaseSync } from 'node:sqlite';
|
||||||
import { randomBytes } from 'node:crypto';
|
import { randomBytes } from 'node:crypto';
|
||||||
import { address as walletAddress, verifySignature } from '../testnet/consensus.ts';
|
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.
|
// 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 Account = { sub: string; issuer: string; name: string; username: string };
|
||||||
export type LinkedWallet = { address: string; linkedAt: number };
|
export type LinkedWallet = { address: string; linkedAt: number };
|
||||||
|
|
||||||
export const CHALLENGE_TTL_MS = 5 * 60_000;
|
export const CHALLENGE_TTL_MS = 5 * 60_000;
|
||||||
|
export const MAX_PENDING_PER_ACCOUNT = 5;
|
||||||
/**
|
|
||||||
* 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 {
|
export class LinkError extends Error {
|
||||||
readonly status: number;
|
readonly status: number;
|
||||||
@@ -62,6 +57,8 @@ export class AccountStore {
|
|||||||
const now = this.now();
|
const now = this.now();
|
||||||
for (const [k, v] of this.challenges) if (v.expiresAt <= now) this.challenges.delete(k);
|
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);
|
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 nonce = randomBytes(24).toString('base64url');
|
||||||
const expiresAt = now + CHALLENGE_TTL_MS;
|
const expiresAt = now + CHALLENGE_TTL_MS;
|
||||||
this.challenges.set(nonce, { sub: account.sub, address, expiresAt });
|
this.challenges.set(nonce, { sub: account.sub, address, expiresAt });
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -45,30 +45,30 @@ export function LoginButton() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
if (!me) return <span className="auth-wrap">
|
if (!me) return <span className="auth-wrap">
|
||||||
<button className="wallet-button auth-button" disabled={busy} onClick={() => run(() => login())}>
|
<button className="wallet-button auth-button" disabled={busy} aria-label="Log in with eom.dev" title="Log in with eom.dev" onClick={() => run(() => login())}>
|
||||||
<span className="wallet-avatar">{busy ? <LoaderCircle className="spin" size={14} /> : <LogIn size={14} />}</span>
|
<span className="wallet-avatar">{busy ? <LoaderCircle className="spin" size={14} /> : <LogIn size={14} />}</span>
|
||||||
Log in with eom.dev
|
<span className="auth-label">Log in with eom.dev</span>
|
||||||
</button>
|
</button>
|
||||||
{notice && <span className="auth-notice" role="alert">{notice}</span>}
|
{notice && <span className="auth-notice" role="alert">{notice}</span>}
|
||||||
</span>;
|
</span>;
|
||||||
|
|
||||||
const linked = wallet && me.wallets.some(w => w.address === wallet.address);
|
const linked = wallet && me.wallets.some(w => w.address === wallet.address);
|
||||||
return <span className="auth-wrap">
|
return <span className="auth-wrap">
|
||||||
<button className="wallet-button auth-button" aria-expanded={open} onClick={() => setOpen(o => !o)}>
|
<button className="wallet-button auth-button" aria-expanded={open} aria-label={`eom.dev account: ${me.name}`} onClick={() => setOpen(o => !o)}>
|
||||||
<Avatar name={me.name} seed={me.sub} />{me.name}
|
<Avatar name={me.name} seed={me.sub} /><span className="auth-label">{me.name}</span>
|
||||||
</button>
|
</button>
|
||||||
{open && <div className="auth-menu" role="menu">
|
{open && <div className="auth-menu" role="menu">
|
||||||
<div className="auth-menu-head"><Avatar name={me.name} seed={me.sub} size={34} />
|
<div className="auth-menu-head"><Avatar name={me.name} seed={me.sub} size={34} />
|
||||||
<div><strong>{me.name}</strong>{me.username && <small>@{me.username} · eom.dev</small>}</div></div>
|
<div><strong>{me.name}</strong>{me.username && <small>@{me.username} · eom.dev</small>}</div></div>
|
||||||
<div className="auth-menu-section">
|
<div className="auth-menu-section">
|
||||||
<small>LINKED WALLETS</small>
|
<small>LINKED WALLETS</small>
|
||||||
{me.wallets.length ? me.wallets.map(w => <code key={w.address}>{short(w.address)}</code>) : <p>None yet. Linking shows your name on leaderboards.</p>}
|
{me.wallets.length ? me.wallets.map(w => <code key={w.address}>{short(w.address)}</code>) : <p>None yet.</p>}
|
||||||
</div>
|
</div>
|
||||||
{linked ? <p className="auth-ok"><UserRound size={14} /> This wallet is linked.</p>
|
{linked ? <p className="auth-ok"><UserRound size={14} /> This wallet is linked.</p>
|
||||||
: <button className="button dark full" role="menuitem" disabled={busy || !wallet} onClick={() => run(async () => {
|
: <>{wallet && <p className="auth-consent">Linking shows your eom.dev name ({me.name}) next to this wallet address on leaderboards, and anyone can look it up. You can unlink later.</p>}<button className="button dark full" role="menuitem" disabled={busy || !wallet} onClick={() => run(async () => {
|
||||||
await linkWallet(wallet); setNotice('Wallet linked.');
|
await linkWallet(wallet); setNotice('Wallet linked.');
|
||||||
})}>{busy ? <LoaderCircle className="spin" size={15} /> : <Link2 size={15} />}
|
})}>{busy ? <LoaderCircle className="spin" size={15} /> : <Link2 size={15} />}
|
||||||
{wallet ? `Link wallet ${short(wallet.address)}` : 'Unlock your wallet to link it'}</button>}
|
{wallet ? `Link wallet ${short(wallet.address)}` : 'Unlock your wallet to link it'}</button></>}
|
||||||
{notice && <p className="auth-notice" role="status">{notice}</p>}
|
{notice && <p className="auth-notice" role="status">{notice}</p>}
|
||||||
<button className="button full" role="menuitem" onClick={() => { logout(); setOpen(false); }}><LogOut size={15} /> Log out</button>
|
<button className="button full" role="menuitem" onClick={() => { logout(); setOpen(false); }}><LogOut size={15} /> Log out</button>
|
||||||
</div>}
|
</div>}
|
||||||
|
|||||||
@@ -9,3 +9,13 @@
|
|||||||
.auth-menu-section code{display:block;font-size:11px;margin-top:4px}
|
.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-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-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))}
|
||||||
|
}
|
||||||
|
|||||||
+19
-6
@@ -3,6 +3,7 @@
|
|||||||
// (Dex sends no CORS headers), so there is no browser -> Dex fetch and no CSP change.
|
// (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.
|
// Tokens live in sessionStorage (cleared with the tab), never localStorage.
|
||||||
import { getWallet, sign, type Wallet } from '../wallet.ts';
|
import { getWallet, sign, type Wallet } from '../wallet.ts';
|
||||||
|
import { clientLinkMessage } from '../../shared/account-link.ts';
|
||||||
|
|
||||||
export type LinkedWallet = { address: string; linkedAt: number };
|
export type LinkedWallet = { address: string; linkedAt: number };
|
||||||
export type Account = { sub: string; issuer: string; name: string; username: string; wallets: LinkedWallet[] };
|
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 const isNative = () => Boolean(capacitor()?.isNativePlatform?.());
|
||||||
export function redirectUri(): string { return isNative() ? NATIVE_REDIRECT : `${location.origin}${CALLBACK_PATH}`; }
|
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<T>(path: string, init: RequestInit & { token?: string } = {}): Promise<T> {
|
async function api<T>(path: string, init: RequestInit & { token?: string } = {}): Promise<T> {
|
||||||
const { token, ...rest } = init;
|
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}` } : {}) } });
|
headers: { ...(rest.body ? { 'Content-Type': 'application/json' } : {}), ...(token ? { Authorization: `Bearer ${token}` } : {}) } });
|
||||||
const data = await res.json().catch(() => ({}));
|
const data = await res.json().catch(() => ({}));
|
||||||
if (res.status === 401 && token) save(undefined);
|
if (res.status === 401 && token) save(undefined);
|
||||||
@@ -108,15 +115,21 @@ export async function refreshAccount(): Promise<Account | undefined> {
|
|||||||
return me;
|
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<LinkedWallet> {
|
* 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<string> = sign): Promise<LinkedWallet> {
|
||||||
if (!current) throw new Error('Log in with your eom.dev account first.');
|
if (!current) throw new Error('Log in with your eom.dev account first.');
|
||||||
|
const session = current;
|
||||||
const w = wallet ?? await getWallet();
|
const w = wallet ?? await getWallet();
|
||||||
if (!w) throw new Error('Unlock your wallet first.');
|
if (!w) throw new Error('Unlock your wallet first.');
|
||||||
const token = current.idToken;
|
const token = session.idToken;
|
||||||
const challenge = await api<{ nonce: string; message: string; expiresAt: number }>('challenge',
|
const challenge = await api<{ nonce?: unknown; message?: unknown; expiresAt?: unknown }>('challenge',
|
||||||
{ method: 'POST', token, body: JSON.stringify({ address: w.address }) });
|
{ 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<LinkedWallet>('link', { method: 'POST', token,
|
const linked = await api<LinkedWallet>('link', { method: 'POST', token,
|
||||||
body: JSON.stringify({ nonce: challenge.nonce, address: w.address, publicKey: w.publicKey, signature }) });
|
body: JSON.stringify({ nonce: challenge.nonce, address: w.address, publicKey: w.publicKey, signature }) });
|
||||||
await refreshAccount().catch(() => {});
|
await refreshAccount().catch(() => {});
|
||||||
|
|||||||
@@ -6,7 +6,9 @@ import { tmpdir } from 'node:os';
|
|||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
import express from 'express';
|
import express from 'express';
|
||||||
import { address } from '../server/testnet/consensus.ts';
|
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 { createAccountRouter } from '../server/account/router.ts';
|
||||||
import { DexKeys, oidcConfig } from '../server/account/oidc.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);
|
assert.equal(wrongNonce.status, 401);
|
||||||
const login = await call('/token', { code: 'c', codeVerifier: verifier, redirectUri: config.redirectUris[0], nonce });
|
const login = await call('/token', { code: 'c', codeVerifier: verifier, redirectUri: config.redirectUris[0], nonce });
|
||||||
assert.equal(login.status, 200);
|
assert.equal(login.status, 200);
|
||||||
assert.equal(login.body.account.name, 'Ada');
|
assert.equal(login.body.account.name, 'ada');
|
||||||
const sent = new URLSearchParams(tokenBody);
|
const sent = new URLSearchParams(tokenBody);
|
||||||
assert.equal(sent.get('client_id'), 'wikideck');
|
assert.equal(sent.get('client_id'), 'wikideck');
|
||||||
assert.equal(sent.get('code_verifier'), verifier);
|
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);
|
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);
|
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.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 {
|
} finally {
|
||||||
await new Promise(r => server.close(r));
|
await new Promise(r => server.close(r));
|
||||||
await rm(dir, { recursive: true, force: true });
|
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; }
|
||||||
|
});
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ const rejects = (p: Promise<unknown>, msg: RegExp) => assert.rejects(p, e => e i
|
|||||||
test('account: a good ID token verifies against the JWKS', async () => {
|
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) });
|
const claims = await verifyIdToken(jwt(good()), fakeDex(), config, { now: NOW, nonce: 'n'.repeat(16) });
|
||||||
assert.equal(claims.sub, 'user-1');
|
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 () => {
|
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', () => {
|
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: 'abcdef123' }), 'player-abcdef');
|
||||||
assert.equal(displayName({ sub: 's', name: 'A\u0000B' + 'x'.repeat(100) }).length, 48);
|
assert.equal(displayName({ sub: 's', name: 'A\u0000B' + 'x'.repeat(100) }).length, 48);
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user