import { Box, Button, Icon, Icons, Spinner, Text, color, config } from 'folds'; import React, { useCallback, useEffect, useMemo, useRef } from 'react'; import { createClient } from 'matrix-js-sdk'; import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback'; import { setFallbackSession } from '../../../state/sessions'; import { completeOidcCodeGrant } from './oidcLoginUtil'; import { invalidateCachedClient, isStaleClientError, parseOidcCallbackParams, readStoredOidcIssuer, takePendingOidcLogin, } from './oidcState'; /** * Exchange the authorization code for a Matrix session and persist it. The * pending sign-in saved before the redirect must exist for this `state` * (CSRF check) and is consumed here. */ const completeOidcLogin = async (code: string, state: string): Promise => { const pending = takePendingOidcLogin(state); if (!pending) throw new Error('No pending sign-in for this state.'); const tokenResponse = await completeOidcCodeGrant(code, pending); // Derive Matrix user_id + device_id from the freshly-issued access token (the // device is owned by the authentication service under MSC3861). const tmp = createClient({ baseUrl: pending.homeserverUrl, accessToken: tokenResponse.access_token, }); const { user_id: userId, device_id: deviceId } = await tmp.whoami(); if (!userId || !deviceId) { throw new Error('Homeserver did not return a user/device for the OIDC session.'); } setFallbackSession(tokenResponse.access_token, deviceId, userId, pending.homeserverUrl, { refreshToken: tokenResponse.refresh_token, expiresInMs: tokenResponse.expires_in ? tokenResponse.expires_in * 1000 : undefined, oidc: { issuer: pending.issuer, clientId: pending.clientId, redirectUri: pending.redirectUri, }, }); }; function CallbackError({ message }: { message: string }) { return ( Sign-in failed {message} {/* Rendered outside the router, so use a plain navigation to the app root. */} ); } /** * Standalone page mounted by App.tsx for the OIDC redirect path (before the * router, since the redirect_uri must be a real non-hash path). */ export function OidcCallback() { // Parsed once: a fresh object per render would re-run the effects below on // every state change, and the code (and its pending sign-in) is single-use. const params = useMemo(() => parseOidcCallbackParams(window.location.search), []); const redeemed = useRef(false); const [state, complete] = useAsyncCallback( useCallback(completeOidcLogin, []), ); useEffect(() => { if (params.kind !== 'success' || redeemed.current) return; redeemed.current = true; complete(params.code, params.state); }, [params, complete]); useEffect(() => { // #102 β€” the login-start path (startOidcLogin) already evicts a cached // dynamic client id when the provider rejects it, but that only covers // failures raised before the redirect. A client id can just as well be // rejected on the way back (`?error=invalid_client` on this callback), // and until now that case never invalidated the cache β€” so the same // stale id gets retried, and rejected again, on every subsequent login. if (params.kind === 'error' && isStaleClientError(params) && params.state) { const issuer = readStoredOidcIssuer(params.state); if (issuer) invalidateCachedClient(issuer); } }, [params]); useEffect(() => { // Session persisted β€” full-page reload at the app root so it boots the // authenticated client (works for both hash and browser router configs). if (state.status === AsyncStatus.Success) { window.location.replace(import.meta.env.BASE_URL); } }, [state.status]); if (params.kind === 'error') { return ; } if (params.kind === 'invalid') { return ( ); } if (state.status === AsyncStatus.Error) { return ; } return ( Signing you in… ); }