Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

fix(oidc): stop the login page signing a user back in against their will

Maurice4854377603f2
diff --git a/client/src/App.tsx b/client/src/App.tsx
index 523e6150b..fd5b4caae 100644
--- a/client/src/App.tsx
+++ b/client/src/App.tsx
@@ -106,7 +106,7 @@ function ProtectedRoute({ children, adminRequired = false, addonId }: ProtectedR
// A session that ended on its own should come back to where it left off; a
// deliberate sign-out is a fresh start and gets no return ticket, so the
// startup destination decides where the next login lands.
- if (loggingOut) return <Navigate to="/login" replace />
+ if (loggingOut) return <Navigate to="/login" replace state={{ noRedirect: true }} />
const redirectParam = encodeURIComponent(location.pathname + location.search + location.hash)
return <Navigate to={`/login?redirect=${redirectParam}`} replace />
}
diff --git a/client/src/pages/LoginPage.tsx b/client/src/pages/LoginPage.tsx
index 1ac70517d..16d18311d 100644
--- a/client/src/pages/LoginPage.tsx
+++ b/client/src/pages/LoginPage.tsx
@@ -16,6 +16,7 @@ import ToggleSwitch from '../components/Settings/ToggleSwitch';
import { SUPPORTED_LANGUAGES, useTranslation } from '../i18n';
import { useLogin } from './login/useLogin';
import LoginWorld from './login/LoginWorld';
+import { clearSignedOut } from '../utils/signedOut'
/** Fixed so the sky does not reshuffle on every render. */
const STARFIELD = [
@@ -496,6 +497,7 @@ export default function LoginPage(): React.ReactElement {
</div>
)}
<a
+ onClick={clearSignedOut}
href={`/api/auth/oidc/login${inviteToken ? '?invite=' + encodeURIComponent(inviteToken) : ''}`}
style={{
width: '100%',
@@ -1097,6 +1099,7 @@ export default function LoginPage(): React.ReactElement {
<div style={{ flex: 1, height: 1, background: '#e5e7eb' }} />
</div>
<a
+ onClick={clearSignedOut}
href={`/api/auth/oidc/login${
inviteToken ? '?invite=' + encodeURIComponent(inviteToken) : ''
}${
diff --git a/client/src/pages/login/useLogin.test.tsx b/client/src/pages/login/useLogin.test.tsx
index 3db9a55b7..1ec430c37 100644
--- a/client/src/pages/login/useLogin.test.tsx
+++ b/client/src/pages/login/useLogin.test.tsx
@@ -7,6 +7,7 @@ import { http, HttpResponse } from 'msw';
import { server } from '../../../tests/helpers/msw/server';
import { resetAllStores } from '../../../tests/helpers/store';
import { buildAppConfig } from '../../../tests/helpers/factories';
+import { markSignedOut, clearSignedOut, wasSignedOut } from '../../utils/signedOut';
import { TranslationProvider } from '../../i18n/TranslationContext';
import { useAuthStore, type LoginResult } from '../../store/authStore';
import { useSettingsStore } from '../../store/settingsStore';
@@ -968,3 +969,86 @@ describe('useLogin — register visibility rules', () => {
expect(result.current.showRegisterOption).toBe(true);
});
});
+
+/*
+ * OIDC-only: the two ways the login page used to sign a user back in against
+ * their will. Both need `password_login: false`, because that is what arms the
+ * automatic bounce to the provider at useLogin's config probe.
+ */
+describe('OIDC-only auto-redirect suppression', () => {
+ function oidcOnly() {
+ server.use(
+ http.get('/api/auth/app-config', () =>
+ HttpResponse.json(buildAppConfig({ password_login: false, oidc_login: true, oidc_configured: true, has_users: true }))),
+ );
+ }
+
+ // #2126. The exchange strips oidc_code from the URL before it navigates away,
+ // so a re-run of the effect during that window used to read an empty search,
+ // miss the guard that sat inside the oidc_code branch, and reach the bounce.
+ it('FE-LOGIN-HOOK-200: an exchange in flight suppresses the bounce even after it stripped oidc_code', async () => {
+ oidcOnly();
+ let release: (v: unknown) => void = () => {};
+ server.use(
+ http.get('/api/auth/oidc/exchange', async () => {
+ await new Promise(r => { release = r; });
+ return HttpResponse.json({ token: 'tok' });
+ }),
+ );
+ setSearch('?oidc_code=CODE-1');
+ renderLogin();
+
+ // The exchange has not answered yet. Strip the parameter the way its own
+ // `.then` does, then re-run the effect the way the real page does: `t` is
+ // one of the effect's dependencies and changes identity whenever the
+ // language does, which happens on every non-English install (the login page
+ // sets a transient language, and the locale chunk resolves asynchronously).
+ setSearch('');
+ await act(async () => {
+ useSettingsStore.getState().setLanguageTransient('fr');
+ await new Promise(r => setTimeout(r, 20));
+ });
+
+ expect(window.location.href).not.toContain('/api/auth/oidc/login');
+ release(null);
+ });
+
+ // #2123. A deliberate sign-out loses its location state to ProtectedRoute's
+ // stateless <Navigate replace>, and to any full document load, so the brake
+ // has to live somewhere that survives both.
+ it('FE-LOGIN-HOOK-201: a tab that just signed out does not bounce to the provider', async () => {
+ oidcOnly();
+ markSignedOut();
+ const { result } = renderLogin();
+ await ready(result);
+ expect(window.location.href).not.toContain('/api/auth/oidc/login');
+ });
+
+ it('FE-LOGIN-HOOK-202: the marker is per tab, so a fresh tab still auto-SSOs', async () => {
+ oidcOnly();
+ clearSignedOut();
+ const { result } = renderLogin();
+ await ready(result);
+ expect(window.location.href).toContain('/api/auth/oidc/login');
+ });
+
+ it('FE-LOGIN-HOOK-203: signing back in clears the marker, so the next visit auto-SSOs again', async () => {
+ markSignedOut();
+ expect(wasSignedOut()).toBe(true);
+ clearSignedOut();
+ expect(wasSignedOut()).toBe(false);
+ });
+
+ it('FE-LOGIN-HOOK-204: password installs are untouched by the marker', async () => {
+ server.use(
+ http.get('/api/auth/app-config', () =>
+ HttpResponse.json(buildAppConfig({ password_login: true, oidc_login: true, oidc_configured: true, has_users: true }))),
+ );
+ markSignedOut();
+ const { result } = renderLogin();
+ await ready(result);
+ // Never redirected in the first place: the bounce requires password_login false.
+ expect(window.location.href).not.toContain('/api/auth/oidc/login');
+ expect(result.current.appConfig?.password_login).toBe(true);
+ });
+});
diff --git a/client/src/pages/login/useLogin.ts b/client/src/pages/login/useLogin.ts
index 7e8d9dc1b..76454d337 100644
--- a/client/src/pages/login/useLogin.ts
+++ b/client/src/pages/login/useLogin.ts
@@ -4,6 +4,7 @@ import { useAuthStore } from '../../store/authStore'
import { useSettingsStore, hasStoredLanguage } from '../../store/settingsStore'
import { useTranslation, detectBrowserLanguage } from '../../i18n'
import { startAuthentication } from '@simplewebauthn/browser'
+import { wasSignedOut } from '../../utils/signedOut'
import { authApi, configApi } from '../../api/client'
import { getApiErrorMessage } from '../../types'
import { START_DESTINATION_ROUTE } from '../../utils/startDestination'
@@ -66,7 +67,10 @@ export function useLogin() {
const { setLanguageLocal, setLanguageTransient, loadSettings } = useSettingsStore()
const navigate = useNavigate()
const location = useLocation()
- const noRedirect = !!(location.state as { noRedirect?: boolean } | null)?.noRedirect
+ // Location state alone is not enough: a deliberate sign-out loses it to
+ // ProtectedRoute's stateless <Navigate replace>, and to any full document
+ // load. The per-tab marker survives both — see utils/signedOut (#2123).
+ const noRedirect = !!(location.state as { noRedirect?: boolean } | null)?.noRedirect || wasSignedOut()
const redirectTarget = useMemo(() => {
const params = new URLSearchParams(window.location.search)
@@ -99,6 +103,16 @@ export function useLogin() {
}
useEffect(() => {
+ // Hoisted out of the `oidcCode` branch below (#2126). An exchange in flight
+ // owns this page, but it strips `oidc_code` from the URL before it navigates
+ // away — so while it waits on /api/auth/me and IndexedDB, a re-run of this
+ // effect read an empty search, fell past the branch that used to hold the
+ // guard, and reached the auto-redirect at the bottom. That bounced to the
+ // IdP, which answered silently, which landed back here: the loop the
+ // reporter saw flashing. Guarding on the ref alone closes it whatever
+ // re-triggers the effect.
+ if (exchangeInitiated.current) return
+
const params = new URLSearchParams(window.location.search)
const invite = params.get('invite')
@@ -117,7 +131,6 @@ export function useLogin() {
}
if (oidcCode) {
- if (exchangeInitiated.current) return
exchangeInitiated.current = true
setIsLoading(true)
fetch('/api/auth/oidc/exchange?code=' + encodeURIComponent(oidcCode), { credentials: 'include' })
diff --git a/client/src/store/authStore.ts b/client/src/store/authStore.ts
index 224f67fa1..f9960e8bc 100644
--- a/client/src/store/authStore.ts
+++ b/client/src/store/authStore.ts
@@ -12,6 +12,7 @@ import { useSystemNoticeStore } from './systemNoticeStore.js'
import { clearAppearanceSnapshot } from '../theme/applyAppearance'
import { clearAllPluginSessions } from './pluginStore'
import { forgetStartDestination } from '../utils/startDestination'
+import { markSignedOut, clearSignedOut } from '../utils/signedOut'
interface AuthResponse {
user: User
@@ -90,6 +91,10 @@ let authSequence = 0
*/
async function onAuthSuccess(userId: number): Promise<void> {
setAuthed(true)
+ // Whatever brought them back in - password, SSO, MFA, demo, a restored
+ // session - the tab is no longer "just signed out", so the login page may
+ // auto-SSO again next time.
+ clearSignedOut()
try {
await reopenForUser(userId)
} catch (err) {
@@ -212,6 +217,11 @@ export const useAuthStore = create<AuthState>()(
// this it would stamp a ?redirect= back to it — which then beats the user's
// startup destination on the next login.
set({ isAuthenticated: false, loggingOut: true })
+ // The same fact, in the one place that survives ProtectedRoute's stateless
+ // <Navigate replace> and a full document load — without it an OIDC-only
+ // install silently signs the user straight back in (#2123). Set here rather
+ // than at the call sites so all seven are covered at once.
+ markSignedOut()
// 2. Stop background sync triggers (30s interval, WS pre-reconnect hook, listeners).
unregisterSyncTriggers()
// 3. Tear down the live connection.
diff --git a/client/src/utils/signedOut.ts b/client/src/utils/signedOut.ts
new file mode 100644
index 000000000..0f4b9eef7
--- /dev/null
+++ b/client/src/utils/signedOut.ts
@@ -0,0 +1,58 @@
+/**
+ * "This tab just signed out" — a fact that has to survive more than a render.
+ *
+ * On an OIDC-only install the login page bounces to the provider on its own
+ * (`useLogin`), which is what makes signing out impossible: the provider still
+ * has a live session, answers the silent authorize immediately, and the user is
+ * back in TREK without having asked to be (#2123).
+ *
+ * The brake for that bounce used to be `noRedirect` in react-router location
+ * state, and it does not survive the trip. `authStore.logout()` flips
+ * `isAuthenticated` on a synchronous lane while BrowserRouter defers its own
+ * location update, so React commits one render still on the old route;
+ * ProtectedRoute sees a logged-out user and emits `<Navigate to="/login"
+ * replace />` with no state, which overwrites the history entry the logout
+ * handler had just pushed. Location state also cannot cross a full document
+ * load, and `api/client.ts` performs one on any 401.
+ *
+ * sessionStorage is the right lifetime for it: it outlives both, and it is gone
+ * when the tab is. A brand-new tab should auto-SSO again — that is the point of
+ * single sign-on. What must not happen is auto-SSO in the tab where somebody
+ * just pressed "Sign out".
+ *
+ * Every accessor is wrapped: Safari in private mode throws on sessionStorage,
+ * and losing the brake must degrade to today's behaviour rather than to a blank
+ * page.
+ */
+const KEY = 'trek_signed_out'
+
+/** Called from `authStore.logout()`, so all seven sign-out call sites are covered at once. */
+export function markSignedOut(): void {
+ try {
+ sessionStorage.setItem(KEY, '1')
+ } catch {
+ /* private mode — the location-state brake still covers the common path */
+ }
+}
+
+/**
+ * Cleared the moment the user asks to come back: any successful authentication,
+ * and the click on the manual "Sign in with SSO" link. Without that, an
+ * OIDC-only user would be stranded on a login page that refuses to auto-SSO for
+ * the life of the tab.
+ */
+export function clearSignedOut(): void {
+ try {
+ sessionStorage.removeItem(KEY)
+ } catch {
+ /* ignore */
+ }
+}
+
+export function wasSignedOut(): boolean {
+ try {
+ return sessionStorage.getItem(KEY) === '1'
+ } catch {
+ return false
+ }
+}