import { createClient, OAuth2, ValidatedAuthMetadata } from 'matrix-js-sdk'; import { getOidcCallbackUrl, getOidcClientMetadata } from './oidcConfig'; import { cacheClientId, getCachedClientId, invalidateCachedClient, isStaleClientError, PendingOidcLogin, savePendingOidcLogin, } from './oidcState'; /** * The homeserver's OAuth 2.0 metadata (`GET /_matrix/client/v1/auth_metadata`). * This is also how the SDK finds the auth server for token refresh and logout, * so login uses the same source. */ export const discoverAuthMetadata = (homeserverBaseUrl: string): Promise => createClient({ baseUrl: homeserverBaseUrl }).getAuthMetadata(); export const getOrRegisterClientId = async ( metadata: ValidatedAuthMetadata, redirectUri: string, ): Promise => { const cached = getCachedClientId(metadata.issuer, redirectUri); if (cached) return cached; const clientId = await OAuth2.registerClient(metadata, getOidcClientMetadata()); cacheClientId(metadata.issuer, clientId, redirectUri); return clientId; }; /** * Begin the OAuth authorization-code flow: discover the auth server through * the homeserver, (re)register a client, remember the PKCE verifier + device * under a fresh `state` (oidcState), then redirect. `prompt: 'create'` opens * the auth server's sign-up page instead, where supported. The callback reads the * result from the query string (`response_mode=query`). */ export const startOidcLogin = async ( homeserverBaseUrl: string, prompt?: 'create', ): Promise => { const redirectUri = getOidcCallbackUrl(); let issuer: string | undefined; try { const metadata = await discoverAuthMetadata(homeserverBaseUrl); issuer = metadata.issuer; const clientId = await getOrRegisterClientId(metadata, redirectUri); const oauth = new OAuth2(metadata, { clientId }); const state = crypto.randomUUID(); const pending: PendingOidcLogin = { issuer, clientId, deviceId: oauth.context.deviceId, codeVerifier: oauth.context.codeVerifier, homeserverUrl: homeserverBaseUrl, redirectUri, }; savePendingOidcLogin(state, pending); // `prompt=create` asks the auth server for its sign-up page (Register), // only where it says it supports that. const usePrompt = prompt && metadata.prompt_values_supported?.includes(prompt) ? prompt : undefined; window.location.assign( await oauth.generateAuthorizationCodeGrantUrl(state, redirectUri, 'query', usePrompt), ); } catch (e) { // #67 — drop the cached client so the next attempt re-registers, but ONLY // when the failure says the client id itself was rejected. Network and // discovery failures keep the cache, otherwise each retry would register // yet another throwaway dynamic client at the provider. if (issuer && isStaleClientError(e)) invalidateCachedClient(issuer); throw e; } }; /** * Exchange the authorization code using the pending sign-in saved before the * redirect. The metadata is fetched again (it isn't stored). */ export const completeOidcCodeGrant = async (code: string, pending: PendingOidcLogin) => { const metadata = await discoverAuthMetadata(pending.homeserverUrl); const oauth = new OAuth2(metadata, { clientId: pending.clientId, deviceId: pending.deviceId, codeVerifier: pending.codeVerifier, }); return oauth.completeAuthorizationCodeGrant(code, pending.redirectUri); };