Skip to content
Open
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
5 changes: 5 additions & 0 deletions .changeset/add-native-oidc-login.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
default: minor
---

Add Native OIDC (OAuth 2.0) login so you can sign in to and register on homeservers that use delegated authentication, such as continuwuity and Synapse with the Matrix Authentication Service. Sessions stay signed in through automatic token refresh, and signing out revokes the tokens on the server.
18 changes: 12 additions & 6 deletions src/app/components/AuthFlowsLoader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,14 @@ export function AuthFlowsLoader({ fallback, error, children }: AuthFlowsLoaderPr

const [state, load] = useAsyncCallback(
useCallback(async () => {
const result = await Promise.allSettled([mx.loginFlows(), mx.registerRequest({})]);
const result = await Promise.allSettled([
mx.loginFlows(),
mx.registerRequest({}),
mx.getAuthMetadata(),
]);
const loginFlows = promiseFulfilledResult(result[0]);
const registerResp = promiseRejectedResult(result[1]) as MatrixError | undefined;
const authMetadata = promiseFulfilledResult(result[2]);
let registerFlows: RegisterFlowsResponse = {
status: RegisterFlowStatus.InvalidRequest,
};
Expand All @@ -32,16 +37,17 @@ export function AuthFlowsLoader({ fallback, error, children }: AuthFlowsLoaderPr
registerFlows = parseRegisterErrResp(registerResp);
}

if (!loginFlows) {
const validLoginFlows = loginFlows && !('errcode' in loginFlows) ? loginFlows : undefined;

// OIDC-only servers reject GET /login; that is fine when the OAuth 2.0 API is available.
if (!validLoginFlows && !authMetadata) {
throw new Error('Missing auth flow!');
}
if ('errcode' in loginFlows) {
throw new Error('Failed to load auth flow!');
}

const authFlows: AuthFlows = {
loginFlows,
loginFlows: validLoginFlows ?? { flows: [] },
registerFlows,
authMetadata,
};

return authFlows;
Expand Down
18 changes: 16 additions & 2 deletions src/app/components/LogoutDialog.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { forwardRef, useCallback } from 'react';
import { Dialog, Header, config, Box, Text, Button, Spinner, color } from 'folds';
import { useAtomValue, useSetAtom } from 'jotai';
import { logoutClient } from '$client/initMatrix';
import { activeSessionIdAtom, sessionsAtom } from '$state/sessions';
import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback';
import { useMatrixClient } from '$hooks/useMatrixClient';
import { useCrossSigningActive } from '$hooks/useCrossSigning';
Expand All @@ -16,6 +18,11 @@ type LogoutDialogProps = {
export const LogoutDialog = forwardRef<HTMLDivElement, LogoutDialogProps>(
({ handleClose }, ref) => {
const mx = useMatrixClient();
const sessions = useAtomValue(sessionsAtom);
const activeSessionId = useAtomValue(activeSessionIdAtom);
const setSessions = useSetAtom(sessionsAtom);
const setActiveSessionId = useSetAtom(activeSessionIdAtom);
const activeSession = sessions.find((s) => s.userId === activeSessionId) ?? sessions[0];
const hasEncryptedRoom = !!mx.getRooms().find((room) => room.hasEncryptionStateEvent());
const crossSigningActive = useCrossSigningActive();
const verificationStatus = useDeviceVerificationStatus(
Expand All @@ -26,8 +33,15 @@ export const LogoutDialog = forwardRef<HTMLDivElement, LogoutDialogProps>(

const [logoutState, logout] = useAsyncCallback<void, Error, []>(
useCallback(async () => {
await logoutClient(mx);
}, [mx])
await logoutClient(mx, activeSession);
if (activeSession) {
setSessions({ type: 'DELETE', session: activeSession });
setActiveSessionId(
sessions.find((s) => s.userId !== activeSession.userId)?.userId ?? undefined
);
}
window.location.reload();
}, [mx, activeSession, sessions, setSessions, setActiveSessionId])
);

const ongoingLogout = logoutState.status === AsyncStatus.Loading;
Expand Down
8 changes: 3 additions & 5 deletions src/app/features/settings/general/General.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1393,11 +1393,9 @@ export function Sync() {
const handleSetSlidingSync = (value: boolean) => {
if (!activeSession) return;
setSessions({
type: 'PUT',
session: {
...activeSession,
slidingSyncOptIn: value,
},
type: 'UPDATE',
userId: activeSession.userId,
patch: { slidingSyncOptIn: value },
});
window.location.reload();
};
Expand Down
8 changes: 7 additions & 1 deletion src/app/hooks/useAuthFlows.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import { createContext, useContext } from 'react';
import type { IAuthData, MatrixError, ILoginFlowsResponse } from '$types/matrix-sdk';
import type {
IAuthData,
MatrixError,
ILoginFlowsResponse,
OidcClientConfig,
} from '$types/matrix-sdk';

export enum RegisterFlowStatus {
FlowRequired = 401,
Expand Down Expand Up @@ -43,6 +48,7 @@ export const parseRegisterErrResp = (matrixError: MatrixError): RegisterFlowsRes
export type AuthFlows = {
loginFlows: ILoginFlowsResponse;
registerFlows: RegisterFlowsResponse;
authMetadata?: OidcClientConfig;
};

const AuthFlowsContext = createContext<AuthFlows | null>(null);
Expand Down
26 changes: 26 additions & 0 deletions src/app/hooks/useParsedLoginFlows.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { describe, it, expect } from 'vitest';
import type { ISSOFlow } from '$types/matrix-sdk';
import { isOauthAwarePreferred } from './useParsedLoginFlows';

describe('isOauthAwarePreferred', () => {
it('is false for an undefined flow', () => {
expect(isOauthAwarePreferred(undefined)).toBe(false);
});

it('is false for a plain SSO flow', () => {
expect(isOauthAwarePreferred({ type: 'm.login.sso' } as ISSOFlow)).toBe(false);
});

it('reads the stable oauth_aware_preferred field', () => {
const flow = { type: 'm.login.sso', oauth_aware_preferred: true } as ISSOFlow;
expect(isOauthAwarePreferred(flow)).toBe(true);
});

it('reads the deprecated msc3824 field', () => {
const flow = {
type: 'm.login.sso',
'org.matrix.msc3824.delegated_oidc_compatibility': true,
} as ISSOFlow;
expect(isOauthAwarePreferred(flow)).toBe(true);
});
});
7 changes: 7 additions & 0 deletions src/app/hooks/useParsedLoginFlows.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
import { useMemo } from 'react';
import type { ILoginFlow, IPasswordFlow, ISSOFlow, LoginFlow } from '$types/matrix-sdk';
import { OAUTH_AWARE_PREFERRED_FLOW_FIELD } from '$types/matrix-sdk';

export const getSSOFlow = (loginFlows: LoginFlow[]): ISSOFlow | undefined =>
loginFlows.find((flow) => flow.type === 'm.login.sso' || flow.type === 'm.login.cas') as
| ISSOFlow
| undefined;

export const isOauthAwarePreferred = (ssoFlow: ISSOFlow | undefined): boolean =>
Boolean(
ssoFlow?.[OAUTH_AWARE_PREFERRED_FLOW_FIELD.name] ??
ssoFlow?.[OAUTH_AWARE_PREFERRED_FLOW_FIELD.altName]
);

export const getPasswordFlow = (loginFlows: LoginFlow[]): IPasswordFlow | undefined =>
loginFlows.find((flow) => flow.type === 'm.login.password') as IPasswordFlow;
export const getTokenFlow = (loginFlows: LoginFlow[]): LoginFlow | undefined =>
Expand Down
13 changes: 10 additions & 3 deletions src/app/hooks/usePathWithOrigin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,32 @@ import { useMemo } from 'react';
import { trimLeadingSlash, trimSlash, trimTrailingSlash } from '$utils/common';
import { useClientConfig } from './useClientConfig';

export const usePathWithOrigin = (path: string): string => {
export const usePathWithOrigin = (
path: string,
options?: {
/** OAuth redirect URIs must not contain a fragment (RFC 6749). */
ignoreHashRouter?: boolean;
}
): string => {
const { hashRouter } = useClientConfig();
const { origin } = window.location;
const ignoreHashRouter = options?.ignoreHashRouter ?? false;

const pathWithOrigin = useMemo(() => {
let url: string = trimSlash(origin);

url += `/${trimSlash(import.meta.env.BASE_URL ?? '')}`;
url = trimTrailingSlash(url);

if (hashRouter?.enabled) {
if (hashRouter?.enabled && !ignoreHashRouter) {
url += `/#/${trimSlash(hashRouter.basename ?? '')}`;
url = trimTrailingSlash(url);
}

url += `/${trimLeadingSlash(path)}`;

return url;
}, [path, hashRouter, origin]);
}, [path, hashRouter, origin, ignoreHashRouter]);

return pathWithOrigin;
};
6 changes: 5 additions & 1 deletion src/app/pages/Router.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -126,10 +126,14 @@ export const createRouter = (clientConfig: ClientConfig, screenSize: ScreenSize)
/>
<Route
loader={({ request }) => {
// Allow reaching the login page with ?addAccount=1 even when already logged in
// Allow reaching the login page even when already logged in:
// - ?addAccount=1 to add another account (multi-account)
// - ?loginToken=... (delegated / SSO login token)
// - ?code=...&state=... (OIDC authorization-code callback, e.g. adding a second account)
const url = new URL(request.url);
if (url.searchParams.get('addAccount') === '1') return null;
if (url.searchParams.has('loginToken')) return null;
if (url.searchParams.has('code') && url.searchParams.has('state')) return null;
if (hasStoredSession()) return redirect(getHomePath());
return null;
}}
Expand Down
74 changes: 55 additions & 19 deletions src/app/pages/auth/login/Login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import { Link, useSearchParams } from 'react-router-dom';
import { SSOAction } from '$types/matrix-sdk';
import { RegisterFlowStatus, useAuthFlows } from '$hooks/useAuthFlows';
import { useAuthServer } from '$hooks/useAuthServer';
import { useParsedLoginFlows } from '$hooks/useParsedLoginFlows';
import { useAutoDiscoveryInfo } from '$hooks/useAutoDiscoveryInfo';
import { isOauthAwarePreferred, useParsedLoginFlows } from '$hooks/useParsedLoginFlows';
import { getLoginPath, getRegisterPath, withSearchParam } from '$pages/pathUtils';
import { usePathWithOrigin } from '$hooks/usePathWithOrigin';
import type { LoginPathSearchParams } from '$pages/paths';
Expand All @@ -13,15 +14,18 @@ import { SSOLogin } from '$pages/auth/SSOLogin';
import { OrDivider } from '$pages/auth/OrDivider';
import { PasswordLoginForm } from './PasswordLoginForm';
import { TokenLogin } from './TokenLogin';
import { OidcLoginButton, OidcCallback } from './OidcLogin';

const getLoginTokenSearchParam = () => {
// when using hasRouter query params in existing route
// gets ignored by react-router, so we need to read it ourself
// we only need to read loginToken as it's the only param that
// is provided by external entity. example: SSO login
const parmas = new URLSearchParams(window.location.search);
const loginToken = parmas.get('loginToken');
return loginToken ?? undefined;
// react-router ignores the real query string in hashRouter mode, so read callback params direct.
const getExternalSearchParams = () => {
const params = new URLSearchParams(window.location.search);
return {
loginToken: params.get('loginToken') ?? undefined,
code: params.get('code') ?? undefined,
state: params.get('state') ?? undefined,
error: params.get('error') ?? undefined,
errorDescription: params.get('error_description') ?? undefined,
};
};

const useLoginSearchParams = (searchParams: URLSearchParams): LoginPathSearchParams =>
Expand All @@ -38,17 +42,21 @@ export function Login() {
const server = useAuthServer();
const { hashRouter } = useClientConfig();
const { hideUsernamePasswordFields } = useClientConfig();
const { loginFlows, registerFlows } = useAuthFlows();
const { loginFlows, registerFlows, authMetadata } = useAuthFlows();
const discovery = useAutoDiscoveryInfo();
const baseUrl = discovery['m.homeserver'].base_url;
const [searchParams] = useSearchParams();
const loginSearchParams = useLoginSearchParams(searchParams);
const ssoRedirectUrl = usePathWithOrigin(getLoginPath(server));
const loginTokenForHashRouter = getLoginTokenSearchParam();
const oidcRedirectUri = usePathWithOrigin(getLoginPath(server), { ignoreHashRouter: true });
const external = getExternalSearchParams();
const absoluteLoginPath = usePathWithOrigin(getLoginPath(server));

if (hashRouter?.enabled && loginTokenForHashRouter) {
if (hashRouter?.enabled && (external.loginToken || (external.code && external.state))) {
window.location.replace(
withSearchParam(absoluteLoginPath, {
loginToken: loginTokenForHashRouter,
...(external.loginToken ? { loginToken: external.loginToken } : {}),
...(external.code && external.state ? { code: external.code, state: external.state } : {}),
})
);
}
Expand All @@ -64,6 +72,22 @@ export function Login() {
const registrationUnavailable =
registerFlows.status === RegisterFlowStatus.RegistrationDisabled && !parsedFlows.sso;

const oidcCode = searchParams.get('code') ?? undefined;
const oidcState = searchParams.get('state') ?? undefined;
const oidcNotice = external.error
? (external.errorDescription ?? `Sign-in was not completed (${external.error}).`)
: undefined;

const showOidc = authMetadata !== undefined;
const hidePassword =
hideUsernamePasswordFields || (showOidc && isOauthAwarePreferred(parsedFlows.sso));
const showPassword = !hidePassword && parsedFlows.password !== undefined;
const showLegacySso = !showOidc && parsedFlows.sso !== undefined;

if (showOidc && oidcCode && oidcState) {
return <OidcCallback code={oidcCode} state={oidcState} />;
}

return (
<Box direction="Column" gap="500">
<Text size="H2" priority="400">
Expand All @@ -72,28 +96,40 @@ export function Login() {
{parsedFlows.token && loginSearchParams.loginToken && (
<TokenLogin token={loginSearchParams.loginToken} />
)}
{!hideUsernamePasswordFields && parsedFlows.password && (
{showPassword && (
<>
<PasswordLoginForm
defaultUsername={loginSearchParams.username}
defaultEmail={loginSearchParams.email}
/>
<span data-spacing-node />
{parsedFlows.sso && <OrDivider />}
{(showLegacySso || showOidc) && <OrDivider />}
</>
)}
{showOidc && (
<>
<OidcLoginButton
authMetadata={authMetadata}
homeserverUrl={baseUrl}
redirectUri={oidcRedirectUri}
label={`Continue with ${server}`}
notice={oidcNotice}
/>
<span data-spacing-node />
</>
)}
{parsedFlows.sso && (
{showLegacySso && (
<>
<SSOLogin
providers={parsedFlows.sso.identity_providers}
providers={parsedFlows.sso!.identity_providers}
redirectUrl={ssoRedirectUrl}
action={SSOAction.LOGIN}
saveScreenSpace={parsedFlows.password !== undefined}
saveScreenSpace={showPassword}
/>
<span data-spacing-node />
</>
)}
{!parsedFlows.password && !parsedFlows.sso && (
{!showPassword && !showLegacySso && !showOidc && (
<>
<Text style={{ color: color.Critical.Main }}>
{`This client does not support login on "${server}" homeserver. Password and SSO based login method not found.`}
Expand Down
Loading
Loading