Files
TREK/client/src/pages/nativeHandoff/useNativeHandoff.ts
T
Maurice 434baaf6fd fix(native-auth): send the app's SSO sign-in through the identity provider every time
The app signs in through a browser sheet that shares the system browser's
cookies. When that browser still held a TREK session from an earlier
sign-in, the hand-off page skipped the identity provider and offered to
continue at once, so a provider set to demand re-authentication (Pocket ID's
"requires re-authentication") was never asked, and signing out of the app
and in again with SSO asked for nothing.

The SSO button now always goes through the identity provider. It decides as
before: a provider with a running session lets the user through, one that
demands re-authentication asks for it. A sign-in with a password or passkey
still continues with the browser's session after the explicit tap.

Refs #3014
2026-11-25 10:52:34 +01:00

105 lines
3.9 KiB
TypeScript

import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router';
import { useShallow } from 'zustand/react/shallow';
import { HANDOFF_PATH, rememberHandoffReturn, requestHandoffCode, signInWithPasskey } from '../../native/browserSignIn';
import { endBrowserSignIn } from '../../native/browserSignInFlag';
import { APP_URL_SCHEME } from '../../native/trekShell';
import { useAuthStore } from '../../store/authStore';
const CHALLENGE = /^[0-9a-f]{64}$/;
/**
* The system-browser end of the app's sign-in (see native/browserSignIn.ts).
* Signs the user in here if needed, then hands the session to the app only
* after an explicit tap: a link to this page with somebody else's challenge
* must not be able to pass a session on silently.
*/
export function useNativeHandoff() {
const navigate = useNavigate();
const { isAuthenticated, isLoading, userName, logout, loadUser } = useAuthStore(
useShallow((s) => ({
isAuthenticated: s.isAuthenticated,
isLoading: s.isLoading,
userName: s.user?.username ?? '',
logout: s.logout,
loadUser: s.loadUser,
}))
);
const [params] = useState(() => new URLSearchParams(window.location.search));
const challenge = params.get('challenge') ?? '';
const valid = CHALLENGE.test(challenge);
const [status, setStatus] = useState<'idle' | 'sending' | 'failed'>('idle');
// The app asked for a passkey: this page asks for it itself instead of showing
// the whole login a second time, until the user picks another way to sign in.
const [passkeyStep, setPasskeyStep] = useState(() => params.get('start') === 'passkey');
// Back here once signed in, without `start`, so an SSO round trip cannot loop.
const returnPath = `${HANDOFF_PATH}?challenge=${challenge}`;
// The app's SSO button always goes through the identity provider, even when this
// browser still holds a TREK session from an earlier sign-in. That session would
// otherwise skip the provider, and with it a re-authentication it demands.
const startOidc = valid && params.get('start') === 'oidc';
useEffect(() => {
if (!valid || isLoading || passkeyStep) return;
if (startOidc) {
sessionStorage.setItem('oidc_redirect', returnPath);
rememberHandoffReturn(returnPath);
window.location.replace('/api/auth/oidc/login?remember=1');
return;
}
if (isAuthenticated) return;
void navigate(`/login?redirect=${encodeURIComponent(returnPath)}`, { replace: true });
}, [valid, isLoading, isAuthenticated, passkeyStep, startOidc, returnPath, navigate]);
const openApp = async (): Promise<void> => {
setStatus('sending');
try {
const code = await requestHandoffCode(challenge);
endBrowserSignIn();
window.location.href = `${APP_URL_SCHEME}://auth?code=${encodeURIComponent(code)}`;
} catch {
setStatus('failed');
}
};
/**
* The passkey prompt, then straight back to the app: the tap that started it
* is the explicit consent the handoff asks for, so no second page follows.
*/
const continueWithPasskey = async (): Promise<void> => {
setStatus('sending');
try {
await signInWithPasskey();
await loadUser({ silent: true });
} catch (err: unknown) {
const name = (err as { name?: string })?.name;
setStatus(name === 'NotAllowedError' || name === 'AbortError' ? 'idle' : 'failed');
return;
}
await openApp();
};
const otherSignIn = (): void => {
setStatus('idle');
setPasskeyStep(false);
};
const switchAccount = async (): Promise<void> => {
await logout();
void navigate(`/login?redirect=${encodeURIComponent(returnPath)}`, { replace: true });
};
return {
valid,
passkeyStep: valid && !isLoading && !isAuthenticated && passkeyStep,
continueWithPasskey,
otherSignIn,
ready: valid && !isLoading && isAuthenticated && !startOidc,
userName,
status,
openApp,
switchAccount,
};
}