Files
wikideck/src/auth/session.ts
T
2026-11-17 05:45:26 +00:00

174 lines
9.4 KiB
TypeScript

// eom.dev login (Dex, OIDC authorization code + PKCE S256, public client "wikideck").
// The browser only navigates to Dex. The node exchanges the code and verifies the ID token
// (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[] };
type Session = { idToken: string; expiresAt: number; account: Account };
type Pending = { state: string; nonce: string; verifier: string; redirectUri: string; returnTo: string; createdAt: number };
type AuthConfig = { issuer: string; clientId: string; scopes: string; authorizationEndpoint: string; redirectUris: string[] };
const SESSION_KEY = 'wikideck.auth.session';
const PENDING_KEY = 'wikideck.auth.pending';
export const CALLBACK_PATH = '/auth/callback';
export const NATIVE_REDIRECT = 'dev.eom.wikideck:/oauth/callback';
const listeners = new Set<() => void>();
let current: Session | undefined = load();
export function subscribeAuth(fn: () => void): () => void { listeners.add(fn); return () => { listeners.delete(fn); }; }
function notify() { for (const fn of listeners) fn(); }
function load(): Session | undefined {
try {
const raw = sessionStorage.getItem(SESSION_KEY);
const s = raw ? JSON.parse(raw) as Session : undefined;
return s && s.expiresAt > Date.now() + 30_000 ? s : undefined;
} catch { return undefined; }
}
function save(s: Session | undefined) {
current = s;
try { if (s) sessionStorage.setItem(SESSION_KEY, JSON.stringify(s)); else sessionStorage.removeItem(SESSION_KEY); } catch { /* memory only */ }
notify();
}
let loginError = '';
/** Last login failure (expired, state mismatch, cancelled, invalid_grant…), for the UI; '' when none. */
export const authError = (): string => loginError;
export function clearAuthError(): void { if (loginError) { loginError = ''; notify(); } }
export function account(): Account | undefined {
if (current && current.expiresAt <= Date.now() + 30_000) save(undefined);
return current?.account;
}
const b64url = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
const random = (n = 32) => b64url(crypto.getRandomValues(new Uint8Array(n)));
export async function pkceChallenge(verifier: string): Promise<string> {
return b64url(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))));
}
type NativeBrowser = { open(o: { url: string }): Promise<void>; close?(): Promise<void> };
type CapacitorGlobal = { isNativePlatform?: () => boolean; Plugins?: { Browser?: NativeBrowser } };
const capacitor = () => (globalThis as { Capacitor?: CapacitorGlobal }).Capacitor;
let nativeBrowser: NativeBrowser | undefined;
/**
* Native apps: pass the imported `@capacitor/browser` plugin so login opens in the system
* browser (Custom Tab / SFSafariViewController), never inside the WebView. Example (src/native.ts):
* import { Browser } from '@capacitor/browser';
* setNativeBrowser(Browser);
* onDeepLink(u => { if (isCallback(u.href)) void completeLogin(u.href); });
*/
export function setNativeBrowser(browser: NativeBrowser): void { nativeBrowser = browser; }
const browserPlugin = () => nativeBrowser ?? capacitor()?.Plugins?.Browser;
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<T>(path: string, init: RequestInit & { token?: string } = {}): Promise<T> {
const { token, ...rest } = init;
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);
if (!res.ok) throw new Error(typeof data.error === 'string' ? data.error : 'Account request failed');
return data as T;
}
export async function login(returnTo = location.pathname + location.search): Promise<void> {
const config = await api<AuthConfig>('config');
const uri = redirectUri();
if (!config.redirectUris.includes(uri)) throw new Error(`This node is not set up for eom.dev login from ${uri}.`);
const pending: Pending = { state: random(), nonce: random(), verifier: random(48), redirectUri: uri,
returnTo: returnTo.startsWith('/') && !returnTo.startsWith('//') ? returnTo : '/', createdAt: Date.now() };
sessionStorage.setItem(PENDING_KEY, JSON.stringify(pending));
const url = new URL(config.authorizationEndpoint);
url.search = new URLSearchParams({ response_type: 'code', client_id: config.clientId, redirect_uri: uri,
scope: config.scopes, state: pending.state, nonce: pending.nonce,
code_challenge: await pkceChallenge(pending.verifier), code_challenge_method: 'S256' }).toString();
// Capacitor: system browser (never a WebView) + custom-scheme redirect, per RFC 8252.
const browser = browserPlugin();
if (isNative()) {
if (!browser) throw new Error('System browser unavailable: the app must call setNativeBrowser(Browser).');
await browser.open({ url: url.toString() });
} else location.assign(url.toString());
}
export const isCallback = (url: string) => {
const u = new URL(url);
return (u.pathname === CALLBACK_PATH || url.startsWith(NATIVE_REDIRECT)) && (u.searchParams.has('code') || u.searchParams.has('error'));
};
/** Finish a login from the redirect URL. Web: called on load. Capacitor: call from App 'appUrlOpen'. */
export async function completeLogin(url: string): Promise<{ returnTo: string }> {
try {
const result = await finishLogin(url);
clearAuthError();
return result;
} catch (e) {
loginError = (e instanceof Error ? e.message : 'Login failed').slice(0, 200); notify();
throw e;
}
}
async function finishLogin(url: string): Promise<{ returnTo: string }> {
const params = new URL(url).searchParams;
const raw = sessionStorage.getItem(PENDING_KEY);
sessionStorage.removeItem(PENDING_KEY); // single use
const pending = raw ? JSON.parse(raw) as Pending : undefined;
if (!pending || Date.now() - pending.createdAt > 10 * 60_000) throw new Error('Login expired. Please try again.');
if (params.get('state') !== pending.state) throw new Error('Login state mismatch. Please try again.');
if (params.get('error')) throw new Error(`Login cancelled: ${params.get('error_description') ?? params.get('error')}`.slice(0, 160));
const code = params.get('code');
if (!code) throw new Error('Login response had no code.');
const s = await api<Session>('token', { method: 'POST', body: JSON.stringify({ code, codeVerifier: pending.verifier,
redirectUri: pending.redirectUri, nonce: pending.nonce }) });
save(s);
if (isNative()) void browserPlugin()?.close?.().catch(() => {});
return { returnTo: pending.returnTo };
}
/** Local logout. Dex publishes no end_session endpoint, so the Dex SSO cookie may remain. */
export function logout(): void { save(undefined); }
export async function refreshAccount(): Promise<Account | undefined> {
if (!current) return undefined;
const me = await api<Account>('me', { token: current.idToken });
save({ ...current, account: me });
return me;
}
/**
* 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.');
const session = current;
const w = wallet ?? await getWallet();
if (!w) throw new Error('Unlock your wallet first.');
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 message = clientLinkMessage(session.account, w.address, challenge);
const signature = await signer(w, message);
const linked = await api<LinkedWallet>('link', { method: 'POST', token,
body: JSON.stringify({ nonce: challenge.nonce, address: w.address, publicKey: w.publicKey, signature }) });
await refreshAccount().catch(() => {});
return linked;
}
/** Leaderboard display names for wallet addresses (only linked wallets resolve). */
export async function displayNames(addresses: string[]): Promise<Record<string, string>> {
if (!addresses.length) return {};
const { names } = await api<{ names: Record<string, string> }>(`names?addresses=${addresses.slice(0, 100).join(',')}`);
return names;
}