Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down Expand Up @@ -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 <access_token>`, 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.

Expand Down
86 changes: 84 additions & 2 deletions src/auth.ts
Original file line number Diff line number Diff line change
@@ -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.
*
Expand All @@ -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);
Expand All @@ -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<void> {
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<void> {
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<SignInState> | undefined;
Expand Down
36 changes: 36 additions & 0 deletions src/authSession.ts
Original file line number Diff line number Diff line change
@@ -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);
}
30 changes: 23 additions & 7 deletions src/components/AppShell.tsx
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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 <LoadingScreen label="Loading your workspace…" />;
if (viewer.isLoading || missingWorkspace) {
return <LoadingScreen label={missingWorkspace ? "Signing you out…" : "Loading your workspace…"} />;
}

const user = viewer.data?.myUser;
const workspace = viewer.data?.myWorkspace;

if (viewer.error || !user || !workspace) {
return (
<CenteredCard>
Expand Down
3 changes: 2 additions & 1 deletion src/plain/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand All @@ -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]);
Expand Down
32 changes: 23 additions & 9 deletions src/routes/Callback.tsx
Original file line number Diff line number Diff line change
@@ -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 <LoadingScreen label="Signing you in…" />;
}
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 <Navigate to={returnToAfterSignIn(auth.user)} replace />;
if (auth.isLoading || !auth.isAuthenticated) {
return <LoadingScreen label={auth.error ? "Signing you out…" : "Signing you in…"} />;
}

// Sign-in failed or was cancelled. The sign-in page shows `auth.error`.
return <Navigate to="/" replace />;
return <Navigate to={returnToAfterSignIn(auth.user)} replace />;
}
3 changes: 2 additions & 1 deletion src/routes/RequireAuth.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand All @@ -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]);
Expand Down
20 changes: 17 additions & 3 deletions src/routes/SignIn.tsx
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -25,6 +25,8 @@ export function SignIn() {
return <Navigate to="/threads" replace />;
}

const recovery = currentSignInRecovery();

return (
<CenteredCard>
<div className={styles.logo} aria-hidden>
Expand All @@ -44,12 +46,24 @@ export function SignIn() {
</p>
</div>

{state.sessionExpired && (
{recovery === "workspace" && (
<Notice tone="warning" title="Choose a 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.
</Notice>
)}
{recovery === "bounced" && (
<Notice tone="warning" title="Sign-in was reset">
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.
</Notice>
)}
{state.sessionExpired && !recovery && (
<Notice tone="warning" title="Your session expired">
Sign in again to continue.
</Notice>
)}
{auth.error && !state.sessionExpired && (
{auth.error && !state.sessionExpired && !recovery && (
<Notice tone="error" title="Sign-in failed">
{auth.error.message}
</Notice>
Expand Down
Loading