forked from WikiDeck/wikideck
account: surface login errors (web and native deep link) in LoginButton
completeLogin records failures in an authError store that LoginButton subscribes to, so Capacitor deep-link errors (expired, state mismatch, invalid_grant) are shown instead of only logged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useState, useSyncExternalStore } from 'react';
|
||||
import { Link2, LoaderCircle, LogIn, LogOut, UserRound } from 'lucide-react';
|
||||
import { getWallet, subscribeWallet, type Wallet } from '../wallet.ts';
|
||||
import { account, completeLogin, isCallback, linkWallet, login, logout, subscribeAuth, type Account } from './session.ts';
|
||||
import { account, authError, clearAuthError, completeLogin, isCallback, linkWallet, login, logout, subscribeAuth, type Account } from './session.ts';
|
||||
import './auth.css';
|
||||
|
||||
export function useAccount(): Account | undefined {
|
||||
@@ -20,6 +20,8 @@ const short = (s: string) => `${s.slice(0, 6)}…${s.slice(-4)}`;
|
||||
|
||||
export function LoginButton() {
|
||||
const me = useAccount();
|
||||
// Login failures from the web callback or a native deep link (completeLogin) land here.
|
||||
const loginError = useSyncExternalStore(subscribeAuth, authError, () => '');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [notice, setNotice] = useState('');
|
||||
@@ -30,7 +32,7 @@ export function LoginButton() {
|
||||
setBusy(true);
|
||||
completeLogin(location.href)
|
||||
.then(({ returnTo }) => history.replaceState(null, '', returnTo))
|
||||
.catch(e => { history.replaceState(null, '', '/'); setNotice(e instanceof Error ? e.message : 'Login failed'); })
|
||||
.catch(() => { history.replaceState(null, '', '/'); })
|
||||
.finally(() => setBusy(false));
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
@@ -39,7 +41,7 @@ export function LoginButton() {
|
||||
}, []);
|
||||
|
||||
const run = async (fn: () => Promise<unknown>) => {
|
||||
setBusy(true); setNotice('');
|
||||
setBusy(true); setNotice(''); clearAuthError();
|
||||
try { await fn(); } catch (e) { setNotice(e instanceof Error ? e.message : 'Request failed'); }
|
||||
finally { setBusy(false); }
|
||||
};
|
||||
@@ -49,7 +51,7 @@ export function LoginButton() {
|
||||
<span className="wallet-avatar">{busy ? <LoaderCircle className="spin" size={14} /> : <LogIn size={14} />}</span>
|
||||
<span className="auth-label">Log in with eom.dev</span>
|
||||
</button>
|
||||
{notice && <span className="auth-notice" role="alert">{notice}</span>}
|
||||
{(notice || loginError) && <span className="auth-notice" role="alert">{notice || loginError}</span>}
|
||||
</span>;
|
||||
|
||||
const linked = wallet && me.wallets.some(w => w.address === wallet.address);
|
||||
|
||||
@@ -33,6 +33,11 @@ function save(s: Session | undefined) {
|
||||
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;
|
||||
@@ -102,6 +107,17 @@ export const isCallback = (url: string) => {
|
||||
|
||||
/** 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
|
||||
|
||||
@@ -31,3 +31,24 @@ test('account native: login opens the system browser with PKCE and the app redir
|
||||
assert.equal(auth.isCallback(`dev.eom.wikideck:/oauth/callback?code=c&state=${pending.state}`), true);
|
||||
} finally { Object.assign(g, saved); }
|
||||
});
|
||||
|
||||
test('account native: completeLogin failures are exposed to the UI via authError', async () => {
|
||||
const g = globalThis as Record<string, unknown>;
|
||||
const saved = { Capacitor: g.Capacitor, sessionStorage: g.sessionStorage };
|
||||
const store = new Map<string, string>();
|
||||
g.sessionStorage = { getItem: (k: string) => store.get(k) ?? null, setItem: (k: string, v: string) => { store.set(k, v); },
|
||||
removeItem: (k: string) => { store.delete(k); } };
|
||||
g.Capacitor = { isNativePlatform: () => true, Plugins: {} };
|
||||
try {
|
||||
const auth = await import('../src/auth/session.ts');
|
||||
let events = 0; const off = auth.subscribeAuth(() => { events++; });
|
||||
store.set('wikideck.auth.pending', JSON.stringify({ state: 'real-state', nonce: 'n', verifier: 'v', redirectUri: 'dev.eom.wikideck:/oauth/callback',
|
||||
returnTo: '/', createdAt: Date.now() }));
|
||||
await assert.rejects(auth.completeLogin('dev.eom.wikideck:/oauth/callback?code=c&state=forged'), /state mismatch/);
|
||||
assert.match(auth.authError(), /state mismatch/);
|
||||
assert.ok(events >= 1, 'subscribers are notified');
|
||||
auth.clearAuthError();
|
||||
assert.equal(auth.authError(), '');
|
||||
off();
|
||||
} finally { Object.assign(g, saved); }
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user