Files
cinny/src/app/pages/auth/oidc/OidcCallback.tsx
T
Lotus CIandClaude Opus 5.5 70206d6033
CI / Build & Quality Checks (push) Skipped
CI / Secret scan (gitleaks) (push) Skipped
CI / Playwright smoke (e2e) (push) Skipped
CI / Build & Quality Checks (pull_request) Successful in 3m24s
CI / Trigger Desktop Build (pull_request) Skipped
CI / Docker image build & smoke test (pull_request) Skipped
CI / Secret scan (gitleaks) (pull_request) Successful in 10s
CI / Playwright smoke (e2e) (pull_request) Successful in 16m50s
chore(deps): matrix-js-sdk 41.7 -> 44.0 (#201)
Picks up three releases of MatrixRTC / delayed-event fixes and
matrix-sdk-crypto-wasm 18.3.1 -> 18.9.0.

SDK 43 moved OAuth (MSC3861) into the SDK and dropped oidc-client-ts, so
the native-OAuth sign-in is ported:
- login discovers the auth server via /auth_metadata, registers with
  OAuth2.registerClient, and keeps the PKCE verifier + device in its own
  sessionStorage entry keyed by `state` (single use; CSRF check);
- refresh is done by the SDK (oauthClientId + onTokenRefresh); the #16
  cross-tab protection is kept by a narrow guard on refresh-token grants
  (the SDK calls the global fetch for OAuth, not fetchFn), which
  serialises them with a Web Lock and adopts a sibling tab's tokens;
- logout and forced logout revoke via mx.logout() (the SDK revokes at
  the auth server for OAuth sessions);
- the callback page parsed its params on every render, re-running the
  single-use code exchange in a loop; parsed once now.

Also: notification_type is deprecated in MSC4075 (ring in DMs, notify
elsewhere when omitted), _onRTCSessionMemberUpdate ->
ensureRecalculateSessionMembers, precache limit 6 -> 10 MB for the
7.8 MB crypto wasm.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017PCb59uY3UKqDqt7B6hzd5
2026-10-24 00:32:13 -04:00

139 lines
5.0 KiB
TypeScript

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<void> => {
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 (
<Box
direction="Column"
gap="400"
alignItems="Center"
justifyContent="Center"
style={{ height: '100dvh', padding: config.space.S700, textAlign: 'center' }}
>
<Icon size="600" filled src={Icons.Warning} style={{ color: color.Critical.Main }} />
<Text size="H3">Sign-in failed</Text>
<Text size="T300" priority="300">
{message}
</Text>
{/* Rendered outside the router, so use a plain navigation to the app root. */}
<Button variant="Primary" onClick={() => window.location.assign(import.meta.env.BASE_URL)}>
<Text as="span" size="B400">
Back to login
</Text>
</Button>
</Box>
);
}
/**
* 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<void, unknown, [string, string]>(
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 <CallbackError message={params.errorDescription || params.error} />;
}
if (params.kind === 'invalid') {
return (
<CallbackError message="This sign-in link is invalid or has expired. Please start over." />
);
}
if (state.status === AsyncStatus.Error) {
return <CallbackError message="Failed to complete sign-in. Please try again." />;
}
return (
<Box
direction="Column"
gap="400"
alignItems="Center"
justifyContent="Center"
style={{ height: '100dvh' }}
>
<Spinner size="600" variant="Secondary" />
<Text size="T300" priority="300">
Signing you in…
</Text>
</Box>
);
}