Adapt OAuth2 implementation to Matrix Spec v1.18 (#34026)

* Adapt OAuth2 implementation to Matrix Spec v1.18

* Handle more cases of oidc->oauth

* Fix test

* Fix read back of oauth2 context

* Iterate

* Fix tests

* Discard changes to apps/web/playwright/e2e/settings/account-user-settings-tab.spec.ts

* Fix test

* Fix test

* Fix test

* Potential fix for pull request finding 'Unused variable, import, function or class'

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>

* Iterate

* Iterate

* Fix test

---------

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>
This commit is contained in:
Michael Telatynski
2026-07-08 09:02:25 +01:00
committed by GitHub
parent 38e29c51c4
commit 2bc9656957
69 changed files with 761 additions and 1738 deletions
@@ -18,17 +18,24 @@ import {
signInByGeneratingQR,
} from "matrix-js-sdk/src/rendezvous";
import { logger } from "matrix-js-sdk/src/logger";
import { AutoDiscovery, MatrixClient, OAuthGrantType, type OidcClientConfig, type XOR } from "matrix-js-sdk/src/matrix";
import {
AutoDiscovery,
MatrixClient,
OAuthGrantType,
type ValidatedAuthMetadata,
type XOR,
} from "matrix-js-sdk/src/matrix";
import { sleep } from "matrix-js-sdk/src/utils";
import { secureRandomString } from "matrix-js-sdk/src/randomstring";
import { Click, Mode, Phase } from "./LoginWithQR-types";
import LoginWithQRFlow from "./LoginWithQRFlow";
import { type CompleteOidcLoginResponse } from "../../../utils/oidc/authorize";
import { getOidcClientId } from "../../../utils/oidc/registerClient.ts";
import { type CompleteOAuthLoginResponse } from "../../../utils/oauth/authorize";
import { getOAuthClientId } from "../../../utils/oauth/registerClient.ts";
import SdkConfig from "../../../SdkConfig.ts";
import { type Context } from "../../../utils/oauth/persistOAuthSettings.ts";
export type QrLoginCredentials = Omit<CompleteOidcLoginResponse, "idTokenClaims"> &
export type QrLoginCredentials = CompleteOAuthLoginResponse &
Awaited<ReturnType<MSC4108SignInWithQR["shareSecrets"]>> & {
deviceId: string;
};
@@ -101,26 +108,10 @@ interface IState {
*/
failureReason?: FailureReason;
/**
* TODO
* Details of the server we are logging into, set after initial protocol negotiation.
*/
loginServerDetails?: {
/**
* TODO
*/
homeserverUrl: string;
/**
* TODO
*/
identityServerUrl?: string;
/**
* TODO
*/
metadata: OidcClientConfig;
/**
* TODO
*/
clientId: string;
};
loginServerDetails?: Pick<Context, "homeserverUrl" | "identityServerUrl" | "metadata"> &
Pick<Context["authContext"], "clientId">;
}
export enum LoginWithQRFailureReason {
@@ -141,7 +132,7 @@ export type FailureReason = RendezvousFailureReason | LoginWithQRFailureReason;
*/
async function resolveServerURLs(
serverNameOrBaseUrl: string,
): Promise<Pick<Partial<NonNullable<IState["loginServerDetails"]>>, "homeserverUrl" | "identityServerUrl">> {
): Promise<Pick<Partial<Context>, "homeserverUrl" | "identityServerUrl">> {
if (serverNameOrBaseUrl.startsWith("http://") || serverNameOrBaseUrl.startsWith("https://")) {
// treat as base URL and skip discovery
return {
@@ -262,7 +253,7 @@ export default class LoginWithQR extends React.Component<Props, IState> {
throw new Error("Failed to discover homeserver URL");
}
let metadata: OidcClientConfig;
let metadata: ValidatedAuthMetadata;
let clientId: string;
try {
// Create a new client as the homeserver URL may not be the same as we used for the secure channel
@@ -270,7 +261,7 @@ export default class LoginWithQR extends React.Component<Props, IState> {
if (!metadata.grant_types_supported.includes(OAuthGrantType.DeviceAuthorization)) {
throw new Error("Server does not support Device Authorization Grant");
}
clientId = await getOidcClientId(metadata, SdkConfig.get().oidc_static_clients);
clientId = await getOAuthClientId(metadata, SdkConfig.get().oidc_static_clients);
} catch (e) {
this.setState({
phase: Phase.Error,
@@ -355,8 +346,6 @@ export default class LoginWithQR extends React.Component<Props, IState> {
refreshToken: tokenResponse.refresh_token,
homeserverUrl,
clientId,
idToken: tokenResponse.id_token,
issuer: metadata!.issuer,
identityServerUrl,
secrets,
deviceId,
@@ -15,7 +15,7 @@ import {
type SSOFlow,
type SSOAction,
type IIdentityProvider,
DELEGATED_OIDC_COMPATIBILITY,
OAUTH_AWARE_PREFERRED_FLOW_FIELD,
} from "matrix-js-sdk/src/matrix";
import { type Signup } from "@matrix-org/analytics-events/types/typescript/Signup";
import { Button, Tooltip } from "@vector-im/compound-web";
@@ -90,7 +90,7 @@ const SSOButton: React.FC<ISSOButtonProps> = ({
let label: string;
if (idp) {
label = _t("auth|continue_with_idp", { provider: idp.name });
} else if (DELEGATED_OIDC_COMPATIBILITY.findIn<boolean>(flow)) {
} else if (OAUTH_AWARE_PREFERRED_FLOW_FIELD.findIn<boolean>(flow)) {
label = _t("action|continue");
} else {
label = _t("auth|sign_in_with_sso");
@@ -18,7 +18,7 @@ import ToggleSwitch from "../../elements/ToggleSwitch";
import { DeviceDetailHeading } from "./DeviceDetailHeading";
import { DeviceVerificationStatusCard } from "./DeviceVerificationStatusCard";
import { type ExtendedDevice } from "./types";
import { getManageDeviceUrl } from "../../../../utils/oidc/urls.ts";
import { getManageDeviceUrl } from "../../../../utils/oauth/urls.ts";
interface Props {
device: ExtendedDevice;
@@ -23,9 +23,8 @@ import ChangePassword from "../../ChangePassword";
import SettingsTab from "../SettingsTab";
import { SettingsSection } from "../../shared/SettingsSection";
import { SettingsSubsection, SettingsSubsectionText } from "../../shared/SettingsSubsection";
import { SDKContext } from "../../../../../contexts/SDKContext";
import { UserPersonalInfoSettings } from "../../UserPersonalInfoSettings";
import { useMatrixClientContext } from "../../../../../contexts/MatrixClientContext";
import { SDKContext } from "../../../../../contexts/SDKContext.ts";
interface IProps {
closeSettingsFn: () => void;
@@ -90,8 +89,8 @@ const AccountUserSettingsTab: React.FC<IProps> = ({ closeSettingsFn }) => {
const [canSetAvatar, setCanSetAvatar] = React.useState<boolean>(false);
const [canChangePassword, setCanChangePassword] = React.useState<boolean>(false);
const cli = useMatrixClientContext();
const sdkContext = useContext(SDKContext);
const cli = sdkContext.client!;
useEffect(() => {
(async () => {
@@ -103,8 +102,8 @@ const AccountUserSettingsTab: React.FC<IProps> = ({ closeSettingsFn }) => {
// the enabled flag value.
const canChangePassword = !changePasswordCap || changePasswordCap["enabled"] !== false;
await sdkContext.oidcClientStore.readyPromise; // wait for the store to be ready
const externalAccountManagementUrl = sdkContext.oidcClientStore.accountManagementEndpoint;
const authMetadata = await cli.getAuthMetadata().catch(() => {});
const externalAccountManagementUrl = authMetadata?.account_management_uri;
// https://spec.matrix.org/v1.7/client-server-api/#m3pid_changes-capability
// We support as far back as v1.1 which doesn't have m.3pid_changes
// so the behaviour for when it is missing has to be assume true
@@ -121,7 +120,7 @@ const AccountUserSettingsTab: React.FC<IProps> = ({ closeSettingsFn }) => {
setExternalAccountManagementUrl(externalAccountManagementUrl);
setCanChangePassword(canChangePassword);
})();
}, [cli, sdkContext.oidcClientStore]);
}, [cli]);
const onPasswordChangeError = useCallback((err: Error): void => {
logger.error("Failed to change password: " + err);
@@ -31,7 +31,7 @@ import QuestionDialog from "../../../dialogs/QuestionDialog";
import { type FilterVariation } from "../../devices/filter";
import { OtherSessionsSectionHeading } from "../../devices/OtherSessionsSectionHeading";
import { SettingsSection } from "../../shared/SettingsSection";
import { getManageDeviceUrl } from "../../../../../utils/oidc/urls.ts";
import { getManageDeviceUrl } from "../../../../../utils/oauth/urls.ts";
import { SDKContext } from "../../../../../contexts/SDKContext";
import Spinner from "../../../elements/Spinner";
@@ -154,12 +154,12 @@ const SessionManagerTab: React.FC<{
* See https://github.com/matrix-org/matrix-spec-proposals/pull/3824
*/
const accountManagement = useAsyncMemo(async () => {
await sdkContext.oidcClientStore.readyPromise; // wait for the store to be ready
const authMetadata = await matrixClient.getAuthMetadata().catch(() => {});
return {
endpoint: sdkContext.oidcClientStore.accountManagementEndpoint,
actionsSupported: sdkContext.oidcClientStore.accountManagementActionsSupported,
endpoint: authMetadata?.account_management_uri,
actionsSupported: authMetadata?.account_management_actions_supported,
};
}, [sdkContext.oidcClientStore]);
}, [matrixClient]);
const disableMultipleSignout = !!accountManagement?.endpoint;
const userId = matrixClient?.getUserId();
const currentUserMember = (userId && matrixClient?.getUser(userId)) || undefined;
@@ -82,7 +82,6 @@ import { KeyboardShortcut } from "../settings/KeyboardShortcut";
import { ModuleApi } from "../../../modules/Api.ts";
import { useModuleSpacePanelItems } from "../../../modules/ExtrasApi.ts";
import { UserMenuViewModel } from "../../../viewmodels/menus/UserMenuViewModel.ts";
import { useMatrixClientContext } from "../../../contexts/MatrixClientContext.tsx";
import { SDKContext } from "../../../contexts/SDKContext.ts";
import { OwnProfileStore } from "../../../stores/OwnProfileStore.ts";
@@ -390,7 +389,8 @@ const InnerSpacePanel = React.memo<IInnerSpacePanelProps>(
);
const SpacePanel: React.FC = () => {
const client = useMatrixClientContext();
const sdkContext = useContext(SDKContext);
const client = sdkContext.client!;
const [dragging, setDragging] = useState(false);
const [isPanelCollapsed, setPanelCollapsed] = useState(true);
const ref = useRef<HTMLDivElement>(null);
@@ -398,7 +398,6 @@ const SpacePanel: React.FC = () => {
if (ref.current) UIStore.instance.trackElementDimensions("SpacePanel", ref.current);
return () => UIStore.instance.stopTrackingElementDimensions("SpacePanel");
}, []);
const sdkContext = useContext(SDKContext);
useDispatcher(defaultDispatcher, (payload: ActionPayload) => {
if (payload.action === Action.ToggleSpacePanel) {
@@ -413,7 +412,6 @@ const SpacePanel: React.FC = () => {
defaultDispatcher,
client,
isPanelCollapsed,
sdkContext.oidcClientStore.accountManagementEndpoint,
),
);