From 7f6cab0e643b0a67b856c690f2d345781caf6f13 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 26 Oct 2026 18:37:31 +0000 Subject: [PATCH] Sign out when a Plain login has no workspace Continuing past Plain's workspace step issues a token that cannot load the app, and the next sign-in replays that session. Drop the local user and OIDC state, and send prompt=login on the next attempt so the workspace step is shown again. Do the same when the callback bounces back to the sign-in page. Co-authored-by: Mathias Vagni --- README.md | 7 ++- src/auth.ts | 86 ++++++++++++++++++++++++++++++++++++- src/authSession.ts | 36 ++++++++++++++++ src/components/AppShell.tsx | 30 ++++++++++--- src/plain/hooks.ts | 3 +- src/routes/Callback.tsx | 32 ++++++++++---- src/routes/RequireAuth.tsx | 3 +- src/routes/SignIn.tsx | 20 +++++++-- 8 files changed, 192 insertions(+), 25 deletions(-) create mode 100644 src/authSession.ts diff --git a/README.md b/README.md index 0695401..7ad28de 100644 --- a/README.md +++ b/README.md @@ -58,7 +58,7 @@ Vite bundles every `VITE_` variable into the JavaScript it sends to the browser, | File | What it shows | | --- | --- | -| [`src/auth.ts`](src/auth.ts) | The whole OAuth configuration: authority, client ID, redirect URL, scopes, refresh and nonce. | +| [`src/auth.ts`](src/auth.ts) | The whole OAuth configuration: authority, client ID, redirect URL, scopes, refresh, nonce, and clearing a sign-in that bounced or has no workspace. | | [`src/main.tsx`](src/main.tsx) | `AuthProvider` wiring. It completes the sign-in when Plain redirects back. | | [`src/routes/RequireAuth.tsx`](src/routes/RequireAuth.tsx) | Protecting pages, and refreshing a token that expired while the tab was asleep. | | [`src/components/AppShell.tsx`](src/components/AppShell.tsx) | Loading the signed-in person and workspace with `myUser` and `myWorkspace`, and signing out. | @@ -91,12 +91,15 @@ sequenceDiagram - `oidc-client-ts` creates a random `state` and a PKCE code verifier, and stores both in `sessionStorage`. - It sends the browser to `/oauth2/authorize` with `scope=openid offline_access`. `offline_access` is what gets you a refresh token. - Plain requires a `nonce`, which we generate with `crypto.randomUUID()`. + - Plain's sign-in screen asks which workspace to use, but it does not require an answer. Continuing without one issues a token that has no workspace. 2. **Callback.** Plain redirects back to `/callback?code=...&state=...`. - `AuthProvider` checks `state` and exchanges the code at `/oauth2/token` with the PKCE verifier. No client secret is involved. - It rejects an ID token whose `nonce` doesn't match. + - If that fails and the person would land back on the sign-in page, the app signs them out and clears stored OIDC state first. The next sign-in sends `prompt=login` so Plain does not replay the session that just failed. 3. **Calling the API.** Every GraphQL request sends `Authorization: Bearer `, exactly like an API key. Plain runs the call as the person who signed in. 4. **Staying signed in.** Shortly before the access token expires, `automaticSilentRenew` swaps the refresh token for a new access token. If the tab slept past expiry, [`RequireAuth`](src/routes/RequireAuth.tsx) refreshes it once on the next page load. -5. **Signing out.** Sign-out deletes the tokens from this browser. Plain's authorization server has no revocation or end-session endpoint, so the deleted access token would keep working until it expires. +5. **Signing out.** Sign-out deletes the user and any in-flight PKCE state from this browser (`sessionStorage` and any older `localStorage` keys). Plain's authorization server has no revocation or end-session endpoint, so the deleted access token would keep working until it expires. +6. **No workspace.** If `myWorkspace` is null, the sign-in is not usable. The app signs the person out, clears the saved session, and the next "Sign in" uses `prompt=login` so they get the workspace step again instead of the same token. If Plain rejects a token (it expired, or the OAuth app was turned off or deleted), the app drops the local session and asks you to sign in again. Turning an OAuth app off in Plain rejects every token it holds until you turn it back on. diff --git a/src/auth.ts b/src/auth.ts index 99749ca..431b6c9 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -1,6 +1,14 @@ import { WebStorageStateStore, type User } from "oidc-client-ts"; import type { AuthContextProps, AuthProviderProps } from "react-oidc-context"; +import { + clearSignInRecovery, + readSignInRecovery, + wipeOidcStorage, + writeSignInRecovery, + type SignInRecovery, +} from "./authSession.ts"; + /** * Everything this app needs to sign in with Plain. * @@ -26,9 +34,11 @@ export const oidcConfig: AuthProviderProps = { scope: "openid offline_access", // Refreshes the access token with the refresh token shortly before it expires. automaticSilentRenew: true, - // sessionStorage is per tab and is cleared when the tab closes. See the README - // for the trade-offs of keeping tokens in the browser. + // sessionStorage is per tab and is cleared when the tab closes. The user and + // the in-flight PKCE state both live here. See the README for the trade-offs + // of keeping tokens in the browser. userStore: new WebStorageStateStore({ store: window.sessionStorage }), + stateStore: new WebStorageStateStore({ store: window.sessionStorage }), // Remove ?code=...&state=... from the address bar once they have been used. onSigninCallback: () => { window.history.replaceState({}, document.title, window.location.pathname); @@ -40,14 +50,86 @@ type SignInState = { returnTo: string }; /** Sends the browser to Plain's sign-in page. */ export function signIn(auth: AuthContextProps, returnTo = "/threads") { const state: SignInState = { returnTo }; + // A skipped workspace, or a sign-in that bounced back here, leaves a Plain + // session that the next visit silently reuses. `prompt=login` starts a new + // one so the workspace step is shown again. There is no end-session endpoint. + const forceFreshLogin = currentSignInRecovery() != null; return auth.signinRedirect({ // Plain requires a nonce. oidc-client-ts stores it and rejects an ID token // whose nonce doesn't match. nonce: crypto.randomUUID(), state, + ...(forceFreshLogin ? { prompt: "login", max_age: 0 } : {}), }); } +function storageIfAvailable(kind: "local" | "session"): Storage | null { + try { + const storage = kind === "local" ? window.localStorage : window.sessionStorage; + const probe = "plain.storageProbe"; + storage.setItem(probe, "1"); + storage.removeItem(probe); + return storage; + } catch { + return null; + } +} + +/** Where a broken sign-in is remembered. localStorage survives closing the tab. */ +function recoveryStorage(): Storage | null { + return storageIfAvailable("local") ?? storageIfAvailable("session"); +} + +export function currentSignInRecovery(): SignInRecovery | null { + const storage = recoveryStorage(); + return storage ? readSignInRecovery(storage) : null; +} + +export function rememberSignInRecovery(reason: SignInRecovery): void { + const storage = recoveryStorage(); + if (storage) writeSignInRecovery(storage, reason); +} + +export function forgetSignInRecovery(): void { + const local = storageIfAvailable("local"); + const session = storageIfAvailable("session"); + if (local) clearSignInRecovery(local); + if (session) clearSignInRecovery(session); +} + +/** + * Drop every local trace of the Plain session: the user, in-flight PKCE state, + * and any oidc keys left in either storage. `clearStaleState` only removes + * entries older than 15 minutes, which is too slow to break a login loop. + */ +export async function clearLocalSignIn(auth: AuthContextProps): Promise { + try { + auth.stopSilentRenew(); + } catch { + // Silent renew was never started. + } + try { + await auth.removeUser(); + } catch { + // The user was already gone. + } + try { + await auth.clearStaleState(); + } catch { + // Best-effort. The wipe below removes fresh state too. + } + const session = storageIfAvailable("session"); + const local = storageIfAvailable("local"); + if (session) wipeOidcStorage(session); + if (local) wipeOidcStorage(local); +} + +/** Sign out for good and make the next "Sign in" start a new Plain session. */ +export async function recoverFromBrokenSignIn(auth: AuthContextProps, reason: SignInRecovery): Promise { + rememberSignInRecovery(reason); + await clearLocalSignIn(auth); +} + /** Where to go after signing in: the page the user was on when we sent them to Plain. */ export function returnToAfterSignIn(user: User | null | undefined): string { const state = user?.state as Partial | undefined; diff --git a/src/authSession.ts b/src/authSession.ts new file mode 100644 index 0000000..03a100c --- /dev/null +++ b/src/authSession.ts @@ -0,0 +1,36 @@ +/** + * Local bookkeeping for a sign-in that must not be reused. + * + * Plain lets someone continue without choosing a workspace. The resulting + * session has no workspace, and the next visit to "Sign in" replays it and + * lands back on this page. Remembering that here survives a reload; oidc + * tokens themselves are wiped separately. + */ + +export const OIDC_STORAGE_PREFIX = "oidc."; + +export const SIGN_IN_RECOVERY_KEY = "plain.signInRecovery"; + +export type SignInRecovery = "workspace" | "bounced"; + +export function wipeOidcStorage(storage: Storage): void { + const keys: string[] = []; + for (let index = 0; index < storage.length; index += 1) { + const key = storage.key(index); + if (key?.startsWith(OIDC_STORAGE_PREFIX)) keys.push(key); + } + for (const key of keys) storage.removeItem(key); +} + +export function readSignInRecovery(storage: Storage): SignInRecovery | null { + const value = storage.getItem(SIGN_IN_RECOVERY_KEY); + return value === "workspace" || value === "bounced" ? value : null; +} + +export function writeSignInRecovery(storage: Storage, reason: SignInRecovery): void { + storage.setItem(SIGN_IN_RECOVERY_KEY, reason); +} + +export function clearSignInRecovery(storage: Storage): void { + storage.removeItem(SIGN_IN_RECOVERY_KEY); +} diff --git a/src/components/AppShell.tsx b/src/components/AppShell.tsx index dc92a0e..6343f0e 100644 --- a/src/components/AppShell.tsx +++ b/src/components/AppShell.tsx @@ -1,7 +1,8 @@ -import { createContext, useContext } from "react"; +import { createContext, useContext, useEffect, useRef } from "react"; import { useAuth } from "react-oidc-context"; import { Link, Outlet, useNavigate } from "react-router"; +import { clearLocalSignIn, forgetSignInRecovery, recoverFromBrokenSignIn } from "../auth.ts"; import { usePlainQuery } from "../plain/hooks.ts"; import { getViewer, type Viewer } from "../plain/operations.ts"; import { Avatar } from "./Avatar.tsx"; @@ -28,21 +29,36 @@ export function AppShell() { const auth = useAuth(); const navigate = useNavigate(); const viewer = usePlainQuery(getViewer, []); + const signedOut = useRef(false); + + const user = viewer.data?.myUser; + const workspace = viewer.data?.myWorkspace; + // Plain does not require a workspace on the sign-in screen. Continuing + // without one yields a token that can never load this app, and the next + // login replays it. Sign out before that loop starts. + const missingWorkspace = !viewer.isLoading && !viewer.error && !!viewer.data && (!user || !workspace); + + useEffect(() => { + if (user && workspace) forgetSignInRecovery(); + }, [user, workspace]); + + useEffect(() => { + if (!missingWorkspace || signedOut.current) return; + signedOut.current = true; + void recoverFromBrokenSignIn(auth, "workspace"); + }, [auth, missingWorkspace]); // There is no token revocation endpoint, so signing out forgets the tokens // in this browser. They stop working when they expire. async function signOut() { - await auth.removeUser(); + await clearLocalSignIn(auth); navigate("/", { replace: true }); } - if (viewer.isLoading) { - return ; + if (viewer.isLoading || missingWorkspace) { + return ; } - const user = viewer.data?.myUser; - const workspace = viewer.data?.myWorkspace; - if (viewer.error || !user || !workspace) { return ( diff --git a/src/plain/hooks.ts b/src/plain/hooks.ts index c045449..7b02215 100644 --- a/src/plain/hooks.ts +++ b/src/plain/hooks.ts @@ -2,6 +2,7 @@ import { useCallback, useEffect, useState, type DependencyList } from "react"; import { useAuth } from "react-oidc-context"; import { useNavigate } from "react-router"; +import { clearLocalSignIn } from "../auth.ts"; import type { SignInLocationState } from "../routes/SignIn.tsx"; import { PlainAuthError } from "./client.ts"; @@ -10,7 +11,7 @@ function useEndExpiredSession() { const auth = useAuth(); const navigate = useNavigate(); return useCallback(async () => { - await auth.removeUser(); + await clearLocalSignIn(auth); const state: SignInLocationState = { sessionExpired: true }; navigate("/", { replace: true, state }); }, [auth, navigate]); diff --git a/src/routes/Callback.tsx b/src/routes/Callback.tsx index 281c783..9fd0552 100644 --- a/src/routes/Callback.tsx +++ b/src/routes/Callback.tsx @@ -1,25 +1,39 @@ +import { useEffect, useRef } from "react"; import { useAuth } from "react-oidc-context"; -import { Navigate } from "react-router"; +import { Navigate, useNavigate } from "react-router"; -import { returnToAfterSignIn } from "../auth.ts"; +import { recoverFromBrokenSignIn, returnToAfterSignIn } from "../auth.ts"; import { LoadingScreen } from "../components/CenteredCard.tsx"; /** * Plain redirects here after sign-in. AuthProvider has already spotted the * `code` and `state` in the URL and is exchanging the code for tokens; this * page waits for that to finish. + * + * If that exchange fails, the person is about to land back on the sign-in + * page. Sign them out and clear stored OIDC state first, or the next click + * replays the same broken attempt. */ export function Callback() { const auth = useAuth(); + const navigate = useNavigate(); + const started = useRef(false); - if (auth.isLoading) { - return ; - } + useEffect(() => { + if (auth.isLoading || auth.isAuthenticated || started.current) return; + started.current = true; + if (!auth.error) { + navigate("/", { replace: true }); + return; + } + void recoverFromBrokenSignIn(auth, "bounced").finally(() => { + navigate("/", { replace: true }); + }); + }, [auth, auth.error, auth.isAuthenticated, auth.isLoading, navigate]); - if (auth.isAuthenticated) { - return ; + if (auth.isLoading || !auth.isAuthenticated) { + return ; } - // Sign-in failed or was cancelled. The sign-in page shows `auth.error`. - return ; + return ; } diff --git a/src/routes/RequireAuth.tsx b/src/routes/RequireAuth.tsx index 9300512..2056889 100644 --- a/src/routes/RequireAuth.tsx +++ b/src/routes/RequireAuth.tsx @@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from "react"; import { useAuth } from "react-oidc-context"; import { Navigate, Outlet, useLocation } from "react-router"; +import { clearLocalSignIn } from "../auth.ts"; import { LoadingScreen } from "../components/CenteredCard.tsx"; import type { SignInLocationState } from "./SignIn.tsx"; @@ -20,7 +21,7 @@ export function RequireAuth() { if (!canRenew || renewStarted.current) return; renewStarted.current = true; auth.signinSilent().catch(async () => { - await auth.removeUser(); + await clearLocalSignIn(auth); setRenewFailed(true); }); }, [auth, canRenew]); diff --git a/src/routes/SignIn.tsx b/src/routes/SignIn.tsx index a411749..a800288 100644 --- a/src/routes/SignIn.tsx +++ b/src/routes/SignIn.tsx @@ -1,7 +1,7 @@ import { useAuth } from "react-oidc-context"; import { Navigate, useLocation } from "react-router"; -import { signIn } from "../auth.ts"; +import { currentSignInRecovery, signIn } from "../auth.ts"; import { Button } from "../components/Button.tsx"; import { CenteredCard, LoadingScreen } from "../components/CenteredCard.tsx"; import { Notice } from "../components/Notice.tsx"; @@ -25,6 +25,8 @@ export function SignIn() { return ; } + const recovery = currentSignInRecovery(); + return (
@@ -44,12 +46,24 @@ export function SignIn() {

- {state.sessionExpired && ( + {recovery === "workspace" && ( + + You continued without choosing a workspace, so you were signed out and the saved session was cleared. Sign in + again and pick a workspace before continuing. + + )} + {recovery === "bounced" && ( + + That sign-in brought you back here, so you were signed out and the saved session was cleared. Sign in again + and choose a workspace when asked. + + )} + {state.sessionExpired && !recovery && ( Sign in again to continue. )} - {auth.error && !state.sessionExpired && ( + {auth.error && !state.sessionExpired && !recovery && ( {auth.error.message}