Support Matrix 1.1 (drop legacy r0 versions) (#9819)

Co-authored-by: Michael Telatynski <7t3chguy@gmail.com>
This commit is contained in:
Travis Ralston 2023-08-14 02:25:13 -06:00 committed by GitHub
parent f9e79fd5d6
commit 180fcaa70f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
32 changed files with 712 additions and 440 deletions

View file

@ -288,7 +288,7 @@ describe("Read receipts", () => {
cy.intercept({
method: "POST",
url: new RegExp(
`http://localhost:\\d+/_matrix/client/r0/rooms/${uriEncodedOtherRoomId}/receipt/m\\.read/.+`,
`http://localhost:\\d+/_matrix/client/v3/rooms/${uriEncodedOtherRoomId}/receipt/m\\.read/.+`,
),
}).as("receiptRequest");
@ -321,7 +321,7 @@ describe("Read receipts", () => {
cy.intercept({
method: "POST",
url: new RegExp(`http://localhost:\\d+/_matrix/client/r0/rooms/${uriEncodedOtherRoomId}/read_markers`),
url: new RegExp(`http://localhost:\\d+/_matrix/client/v3/rooms/${uriEncodedOtherRoomId}/read_markers`),
}).as("readMarkersRequest");
cy.findByRole("button", { name: "Jump to first unread message." }).click();
@ -341,7 +341,7 @@ describe("Read receipts", () => {
cy.intercept({
method: "POST",
url: new RegExp(`http://localhost:\\d+/_matrix/client/r0/rooms/${uriEncodedOtherRoomId}/read_markers`),
url: new RegExp(`http://localhost:\\d+/_matrix/client/v3/rooms/${uriEncodedOtherRoomId}/read_markers`),
}).as("readMarkersRequest");
cy.findByRole("button", { name: "Scroll to most recent messages" }).click();

View file

@ -704,14 +704,14 @@ describe("Timeline", () => {
});
it("should render url previews", () => {
cy.intercept("**/_matrix/media/r0/thumbnail/matrix.org/2022-08-16_yaiSVSRIsNFfxDnV?*", {
cy.intercept("**/_matrix/media/v3/thumbnail/matrix.org/2022-08-16_yaiSVSRIsNFfxDnV?*", {
statusCode: 200,
fixture: "riot.png",
headers: {
"Content-Type": "image/png",
},
}).as("mxc");
cy.intercept("**/_matrix/media/r0/preview_url?url=https%3A%2F%2Fcall.element.io%2F&ts=*", {
cy.intercept("**/_matrix/media/v3/preview_url?url=https%3A%2F%2Fcall.element.io%2F&ts=*", {
statusCode: 200,
body: {
"og:title": "Element Call",

View file

@ -62,7 +62,7 @@ declare global {
Cypress.Commands.add(
"loginUser",
(homeserver: HomeserverInstance, username: string, password: string): Chainable<UserCredentials> => {
const url = `${homeserver.baseUrl}/_matrix/client/r0/login`;
const url = `${homeserver.baseUrl}/_matrix/client/v3/login`;
return cy
.request<{
access_token: string;

View file

@ -100,7 +100,6 @@ export default class AddThreepid {
*/
public async bindEmailAddress(emailAddress: string): Promise<IRequestTokenResponse> {
this.bind = true;
if (await this.matrixClient.doesServerSupportSeparateAddAndBind()) {
// For separate bind, request a token directly from the IS.
const authClient = new IdentityAuthClient();
const identityAccessToken = (await authClient.getAccessToken()) ?? undefined;
@ -121,10 +120,6 @@ export default class AddThreepid {
// Otherwise, just blurt out the same error
throw err;
}
} else {
// For tangled bind, request a token via the HS.
return this.addEmailAddress(emailAddress);
}
}
/**
@ -163,7 +158,6 @@ export default class AddThreepid {
*/
public async bindMsisdn(phoneCountry: string, phoneNumber: string): Promise<IRequestMsisdnTokenResponse> {
this.bind = true;
if (await this.matrixClient.doesServerSupportSeparateAddAndBind()) {
// For separate bind, request a token directly from the IS.
const authClient = new IdentityAuthClient();
const identityAccessToken = (await authClient.getAccessToken()) ?? undefined;
@ -185,10 +179,6 @@ export default class AddThreepid {
// Otherwise, just blurt out the same error
throw err;
}
} else {
// For tangled bind, request a token via the HS.
return this.addMsisdn(phoneCountry, phoneNumber);
}
}
/**
@ -199,7 +189,6 @@ export default class AddThreepid {
*/
public async checkEmailLinkClicked(): Promise<[success?: boolean, result?: IAuthData | Error | null]> {
try {
if (await this.matrixClient.doesServerSupportSeparateAddAndBind()) {
if (this.bind) {
const authClient = new IdentityAuthClient();
const identityAccessToken = await authClient.getAccessToken();
@ -254,16 +243,6 @@ export default class AddThreepid {
return finished;
}
}
} else {
await this.matrixClient.addThreePid(
{
sid: this.sessionId!,
client_secret: this.clientSecret,
id_server: getIdServerDomain(this.matrixClient),
},
this.bind,
);
}
} catch (err) {
if (err instanceof HTTPError && err.httpStatus === 401) {
throw new UserFriendlyError(
@ -301,7 +280,6 @@ export default class AddThreepid {
msisdnToken: string,
): Promise<[success?: boolean, result?: IAuthData | Error | null] | undefined> {
const authClient = new IdentityAuthClient();
const supportsSeparateAddAndBind = await this.matrixClient.doesServerSupportSeparateAddAndBind();
let result: { success: boolean } | MatrixError;
if (this.submitUrl) {
@ -311,7 +289,7 @@ export default class AddThreepid {
this.clientSecret,
msisdnToken,
);
} else if (this.bind || !supportsSeparateAddAndBind) {
} else if (this.bind) {
result = await this.matrixClient.submitMsisdnToken(
this.sessionId!,
this.clientSecret,
@ -325,7 +303,6 @@ export default class AddThreepid {
throw result;
}
if (supportsSeparateAddAndBind) {
if (this.bind) {
await this.matrixClient.bindThreePid({
sid: this.sessionId!,
@ -349,9 +326,7 @@ export default class AddThreepid {
const dialogAesthetics = {
[SSOAuthEntry.PHASE_PREAUTH]: {
title: _t("Use Single Sign On to continue"),
body: _t(
"Confirm adding this phone number by using Single Sign On to prove your identity.",
),
body: _t("Confirm adding this phone number by using Single Sign On to prove your identity."),
continueText: _t("Single Sign On"),
continueKind: "primary",
},
@ -375,15 +350,5 @@ export default class AddThreepid {
return finished;
}
}
} else {
await this.matrixClient.addThreePid(
{
sid: this.sessionId!,
client_secret: this.clientSecret,
id_server: getIdServerDomain(this.matrixClient),
},
this.bind,
);
}
}
}

View file

@ -24,6 +24,7 @@ import { decryptAES, encryptAES, IEncryptedPayload } from "matrix-js-sdk/src/cry
import { QueryDict } from "matrix-js-sdk/src/utils";
import { logger } from "matrix-js-sdk/src/logger";
import { SSOAction } from "matrix-js-sdk/src/@types/auth";
import { MINIMUM_MATRIX_VERSION } from "matrix-js-sdk/src/version-support";
import { IMatrixClientCreds, MatrixClientPeg } from "./MatrixClientPeg";
import SecurityCustomisations from "./customisations/Security";
@ -66,6 +67,7 @@ import { SdkContextClass } from "./contexts/SDKContext";
import { messageForLoginError } from "./utils/ErrorUtils";
import { completeOidcLogin } from "./utils/oidc/authorize";
import { persistOidcAuthenticatedSettings } from "./utils/oidc/persistOidcSettings";
import GenericToast from "./components/views/toasts/GenericToast";
const HOMESERVER_URL_KEY = "mx_hs_url";
const ID_SERVER_URL_KEY = "mx_is_url";
@ -584,6 +586,7 @@ export async function restoreFromLocalStorage(opts?: { ignoreGuest?: boolean }):
},
false,
);
checkServerVersions();
return true;
} else {
logger.log("No previous session found.");
@ -591,6 +594,35 @@ export async function restoreFromLocalStorage(opts?: { ignoreGuest?: boolean }):
}
}
async function checkServerVersions(): Promise<void> {
MatrixClientPeg.get()
?.getVersions()
.then((response) => {
if (!response.versions.includes(MINIMUM_MATRIX_VERSION)) {
const toastKey = "LEGACY_SERVER";
ToastStore.sharedInstance().addOrReplaceToast({
key: toastKey,
title: _t("Your server is unsupported"),
props: {
description: _t(
"This server is using an older version of Matrix. Upgrade to Matrix %(version)s to use %(brand)s without errors.",
{
version: MINIMUM_MATRIX_VERSION,
brand: SdkConfig.get().brand,
},
),
acceptLabel: _t("OK"),
onAccept: () => {
ToastStore.sharedInstance().dismissToast(toastKey);
},
},
component: GenericToast,
priority: 98,
});
}
});
}
async function handleLoadSessionFailure(e: unknown): Promise<boolean> {
logger.error("Unable to load session", e);

View file

@ -18,7 +18,6 @@ limitations under the License.
import React, { ReactNode } from "react";
import { logger } from "matrix-js-sdk/src/logger";
import { createClient } from "matrix-js-sdk/src/matrix";
import { sleep } from "matrix-js-sdk/src/utils";
import { _t, _td } from "../../../languageHandler";
@ -81,7 +80,6 @@ interface State {
serverIsAlive: boolean;
serverDeadError: string;
serverSupportsControlOfDevicesLogout: boolean;
logoutDevices: boolean;
}
@ -104,16 +102,11 @@ export default class ForgotPassword extends React.Component<Props, State> {
// be seeing.
serverIsAlive: true,
serverDeadError: "",
serverSupportsControlOfDevicesLogout: false,
logoutDevices: false,
};
this.reset = new PasswordReset(this.props.serverConfig.hsUrl, this.props.serverConfig.isUrl);
}
public componentDidMount(): void {
this.checkServerCapabilities(this.props.serverConfig);
}
public componentDidUpdate(prevProps: Readonly<Props>): void {
if (
prevProps.serverConfig.hsUrl !== this.props.serverConfig.hsUrl ||
@ -121,9 +114,6 @@ export default class ForgotPassword extends React.Component<Props, State> {
) {
// Do a liveliness check on the new URLs
this.checkServerLiveliness(this.props.serverConfig);
// Do capabilities check on new URLs
this.checkServerCapabilities(this.props.serverConfig);
}
}
@ -146,19 +136,6 @@ export default class ForgotPassword extends React.Component<Props, State> {
}
}
private async checkServerCapabilities(serverConfig: ValidatedServerConfig): Promise<void> {
const tempClient = createClient({
baseUrl: serverConfig.hsUrl,
});
const serverSupportsControlOfDevicesLogout = await tempClient.doesServerSupportLogoutDevices();
this.setState({
logoutDevices: !serverSupportsControlOfDevicesLogout,
serverSupportsControlOfDevicesLogout,
});
}
private async onPhaseEmailInputSubmit(): Promise<void> {
this.phase = Phase.SendingEmail;
@ -376,13 +353,7 @@ export default class ForgotPassword extends React.Component<Props, State> {
description: (
<div>
<p>
{!this.state.serverSupportsControlOfDevicesLogout
? _t(
"Resetting your password on this homeserver will cause all of your devices to be " +
"signed out. This will delete the message encryption keys stored on them, " +
"making encrypted chat history unreadable.",
)
: _t(
{_t(
"Signing out your devices will delete the message encryption keys stored on them, " +
"making encrypted chat history unreadable.",
)}
@ -446,7 +417,6 @@ export default class ForgotPassword extends React.Component<Props, State> {
autoComplete="new-password"
/>
</div>
{this.state.serverSupportsControlOfDevicesLogout ? (
<div className="mx_AuthBody_fieldRow">
<StyledCheckbox
onChange={() => this.setState({ logoutDevices: !this.state.logoutDevices })}
@ -455,7 +425,6 @@ export default class ForgotPassword extends React.Component<Props, State> {
{_t("Sign out of all devices")}
</StyledCheckbox>
</div>
) : null}
{this.state.errorText && <ErrorMessage message={this.state.errorText} />}
<button type="submit" className="mx_Login_submit">
{submitButtonChild}

View file

@ -18,7 +18,6 @@ limitations under the License.
import React from "react";
import { MatrixClient } from "matrix-js-sdk/src/matrix";
import type ExportE2eKeysDialog from "../../../async-components/views/dialogs/security/ExportE2eKeysDialog";
import Field from "../elements/Field";
import { MatrixClientPeg } from "../../../MatrixClientPeg";
import AccessibleButton from "../elements/AccessibleButton";
@ -29,7 +28,6 @@ import Modal from "../../../Modal";
import PassphraseField from "../auth/PassphraseField";
import { PASSWORD_MIN_SCORE } from "../auth/RegistrationForm";
import SetEmailDialog from "../dialogs/SetEmailDialog";
import QuestionDialog from "../dialogs/QuestionDialog";
const FIELD_OLD_PASSWORD = "field_old_password";
const FIELD_NEW_PASSWORD = "field_new_password";
@ -43,11 +41,7 @@ enum Phase {
}
interface IProps {
onFinished: (outcome: {
didSetEmail?: boolean;
/** Was one or more other devices logged out whilst changing the password */
didLogoutOutOtherDevices: boolean;
}) => void;
onFinished: (outcome: { didSetEmail?: boolean }) => void;
onError: (error: Error) => void;
rowClassName?: string;
buttonClassName?: string;
@ -95,58 +89,10 @@ export default class ChangePassword extends React.Component<IProps, IState> {
private async onChangePassword(oldPassword: string, newPassword: string): Promise<void> {
const cli = MatrixClientPeg.safeGet();
// if the server supports it then don't sign user out of all devices
const serverSupportsControlOfDevicesLogout = await cli.doesServerSupportLogoutDevices();
const userHasOtherDevices = (await cli.getDevices()).devices.length > 1;
if (userHasOtherDevices && !serverSupportsControlOfDevicesLogout && this.props.confirm) {
// warn about logging out all devices
const { finished } = Modal.createDialog(QuestionDialog, {
title: _t("Warning!"),
description: (
<div>
<p>
{_t(
"Changing your password on this homeserver will cause all of your other devices to be " +
"signed out. This will delete the message encryption keys stored on them, and may make " +
"encrypted chat history unreadable.",
)}
</p>
<p>
{_t(
"If you want to retain access to your chat history in encrypted rooms you should first " +
"export your room keys and re-import them afterwards.",
)}
</p>
<p>
{_t(
"You can also ask your homeserver admin to upgrade the server to change this behaviour.",
)}
</p>
</div>
),
button: _t("Continue"),
extraButtons: [
<button key="exportRoomKeys" className="mx_Dialog_primary" onClick={this.onExportE2eKeysClicked}>
{_t("Export E2E room keys")}
</button>,
],
});
const [confirmed] = await finished;
if (!confirmed) return;
this.changePassword(cli, oldPassword, newPassword);
}
this.changePassword(cli, oldPassword, newPassword, serverSupportsControlOfDevicesLogout, userHasOtherDevices);
}
private changePassword(
cli: MatrixClient,
oldPassword: string,
newPassword: string,
serverSupportsControlOfDevicesLogout: boolean,
userHasOtherDevices: boolean,
): void {
private changePassword(cli: MatrixClient, oldPassword: string, newPassword: string): void {
const authDict = {
type: "m.login.password",
identifier: {
@ -163,23 +109,17 @@ export default class ChangePassword extends React.Component<IProps, IState> {
phase: Phase.Uploading,
});
const logoutDevices = serverSupportsControlOfDevicesLogout ? false : undefined;
// undefined or true mean all devices signed out
const didLogoutOutOtherDevices = !serverSupportsControlOfDevicesLogout && userHasOtherDevices;
cli.setPassword(authDict, newPassword, logoutDevices)
cli.setPassword(authDict, newPassword, false)
.then(
() => {
if (this.props.shouldAskForEmail) {
return this.optionallySetEmail().then((confirmed) => {
this.props.onFinished({
didSetEmail: confirmed,
didLogoutOutOtherDevices,
});
});
} else {
this.props.onFinished({ didLogoutOutOtherDevices });
this.props.onFinished({});
}
},
(err) => {
@ -229,17 +169,6 @@ export default class ChangePassword extends React.Component<IProps, IState> {
return modal.finished.then(([confirmed]) => !!confirmed);
}
private onExportE2eKeysClicked = (): void => {
Modal.createDialogAsync(
import("../../../async-components/views/dialogs/security/ExportE2eKeysDialog") as unknown as Promise<
typeof ExportE2eKeysDialog
>,
{
matrixClient: MatrixClientPeg.safeGet(),
},
);
};
private markFieldValid(fieldID: FieldType, valid?: boolean): void {
const { fieldValid } = this.state;
fieldValid[fieldID] = valid;

View file

@ -210,7 +210,7 @@ export default class PhoneNumbers extends React.Component<IProps, IState> {
?.haveMsisdnToken(token)
.then(([finished] = []) => {
let newPhoneNumber = this.state.newPhoneNumber;
if (finished) {
if (finished !== false) {
const msisdns = [...this.props.msisdns, { address, medium: ThreepidMedium.Phone }];
this.props.onMsisdnsChange(msisdns);
newPhoneNumber = "";

View file

@ -77,10 +77,6 @@ export class EmailAddress extends React.Component<IEmailAddressProps, IEmailAddr
}
private async changeBinding({ bind, label, errorTitle }: Binding): Promise<void> {
if (!(await MatrixClientPeg.safeGet().doesServerSupportSeparateAddAndBind())) {
return this.changeBindingTangledAddBind({ bind, label, errorTitle });
}
const { medium, address } = this.props.email;
try {
@ -113,41 +109,6 @@ export class EmailAddress extends React.Component<IEmailAddressProps, IEmailAddr
}
}
private async changeBindingTangledAddBind({ bind, label, errorTitle }: Binding): Promise<void> {
const { medium, address } = this.props.email;
const task = new AddThreepid(MatrixClientPeg.safeGet());
this.setState({
verifying: true,
continueDisabled: true,
addTask: task,
});
try {
await MatrixClientPeg.safeGet().deleteThreePid(medium, address);
if (bind) {
await task.bindEmailAddress(address);
} else {
await task.addEmailAddress(address);
}
this.setState({
continueDisabled: false,
bound: bind,
});
} catch (err) {
logger.error(`changeBindingTangledAddBind: Unable to ${label} email address ${address}`, err);
this.setState({
verifying: false,
continueDisabled: false,
addTask: null,
});
Modal.createDialog(ErrorDialog, {
title: errorTitle,
description: extractErrorMessageFromError(err, _t("Operation failed")),
});
}
}
private onRevokeClick = (e: ButtonEvent): void => {
e.stopPropagation();
e.preventDefault();

View file

@ -73,10 +73,6 @@ export class PhoneNumber extends React.Component<IPhoneNumberProps, IPhoneNumber
}
private async changeBinding({ bind, label, errorTitle }: Binding): Promise<void> {
if (!(await MatrixClientPeg.safeGet().doesServerSupportSeparateAddAndBind())) {
return this.changeBindingTangledAddBind({ bind, label, errorTitle });
}
const { medium, address } = this.props.msisdn;
try {
@ -114,47 +110,6 @@ export class PhoneNumber extends React.Component<IPhoneNumberProps, IPhoneNumber
}
}
private async changeBindingTangledAddBind({ bind, label, errorTitle }: Binding): Promise<void> {
const { medium, address } = this.props.msisdn;
const task = new AddThreepid(MatrixClientPeg.safeGet());
this.setState({
verifying: true,
continueDisabled: true,
addTask: task,
});
try {
await MatrixClientPeg.safeGet().deleteThreePid(medium, address);
// XXX: Sydent will accept a number without country code if you add
// a leading plus sign to a number in E.164 format (which the 3PID
// address is), but this goes against the spec.
// See https://github.com/matrix-org/matrix-doc/issues/2222
if (bind) {
// @ts-ignore
await task.bindMsisdn(null, `+${address}`);
} else {
// @ts-ignore
await task.addMsisdn(null, `+${address}`);
}
this.setState({
continueDisabled: false,
bound: bind,
});
} catch (err) {
logger.error(`changeBindingTangledAddBind: Unable to ${label} phone number ${address}`, err);
this.setState({
verifying: false,
continueDisabled: false,
addTask: null,
});
Modal.createDialog(ErrorDialog, {
title: errorTitle,
description: extractErrorMessageFromError(err, _t("Operation failed")),
});
}
}
private onRevokeClick = (e: ButtonEvent): void => {
e.stopPropagation();
e.preventDefault();

View file

@ -37,7 +37,6 @@ import { Service, ServicePolicyPair, startTermsFlow } from "../../../../../Terms
import IdentityAuthClient from "../../../../../IdentityAuthClient";
import { abbreviateUrl } from "../../../../../utils/UrlUtils";
import { getThreepidsWithBindStatus } from "../../../../../boundThreepids";
import Spinner from "../../../elements/Spinner";
import { SettingLevel } from "../../../../../settings/SettingLevel";
import { UIFeature } from "../../../../../settings/UIFeature";
import { ActionPayload } from "../../../../../dispatcher/payloads";
@ -70,7 +69,6 @@ interface IState {
spellCheckEnabled?: boolean;
spellCheckLanguages: string[];
haveIdServer: boolean;
serverSupportsSeparateAddAndBind?: boolean;
idServerHasUnsignedTerms: boolean;
requiredPolicyInfo:
| {
@ -166,8 +164,6 @@ export default class GeneralUserSettingsTab extends React.Component<IProps, ISta
private async getCapabilities(): Promise<void> {
const cli = this.context;
const serverSupportsSeparateAddAndBind = await cli.doesServerSupportSeparateAddAndBind();
const capabilities = await cli.getCapabilities(); // this is cached
const changePasswordCap = capabilities["m.change_password"];
@ -179,7 +175,7 @@ export default class GeneralUserSettingsTab extends React.Component<IProps, ISta
const delegatedAuthConfig = M_AUTHENTICATION.findIn<IDelegatedAuthConfig | undefined>(cli.getClientWellKnown());
const externalAccountManagementUrl = delegatedAuthConfig?.account;
this.setState({ serverSupportsSeparateAddAndBind, canChangePassword, externalAccountManagementUrl });
this.setState({ canChangePassword, externalAccountManagementUrl });
}
private async getThreepidState(): Promise<void> {
@ -303,12 +299,8 @@ export default class GeneralUserSettingsTab extends React.Component<IProps, ISta
});
};
private onPasswordChanged = ({ didLogoutOutOtherDevices }: { didLogoutOutOtherDevices: boolean }): void => {
let description = _t("Your password was successfully changed.");
if (didLogoutOutOtherDevices) {
description +=
" " + _t("You will not receive push notifications on other devices until you sign back in to them.");
}
private onPasswordChanged = (): void => {
const description = _t("Your password was successfully changed.");
// TODO: Figure out a design that doesn't involve replacing the current dialog
Modal.createDialog(ErrorDialog, {
title: _t("Success"),
@ -327,15 +319,7 @@ export default class GeneralUserSettingsTab extends React.Component<IProps, ISta
private renderAccountSection(): JSX.Element {
let threepidSection: ReactNode = null;
// For older homeservers without separate 3PID add and bind methods (MSC2290),
// we use a combo add with bind option API which requires an identity server to
// validate 3PID ownership even if we're just adding to the homeserver only.
// For newer homeservers with separate 3PID add and bind methods (MSC2290),
// there is no such concern, so we can always show the HS account 3PIDs.
if (
SettingsStore.getValue(UIFeature.ThirdPartyID) &&
(this.state.haveIdServer || this.state.serverSupportsSeparateAddAndBind === true)
) {
if (SettingsStore.getValue(UIFeature.ThirdPartyID)) {
const emails = this.state.loading3pids ? (
<InlineSpinner />
) : (
@ -365,8 +349,6 @@ export default class GeneralUserSettingsTab extends React.Component<IProps, ISta
</SettingsSubsection>
</>
);
} else if (this.state.serverSupportsSeparateAddAndBind === null) {
threepidSection = <Spinner />;
}
let passwordChangeSection: ReactNode = null;

View file

@ -105,6 +105,8 @@
"We asked the browser to remember which homeserver you use to let you sign in, but unfortunately your browser has forgotten it. Go to the sign in page and try again.": "We asked the browser to remember which homeserver you use to let you sign in, but unfortunately your browser has forgotten it. Go to the sign in page and try again.",
"We couldn't log you in": "We couldn't log you in",
"Try again": "Try again",
"Your server is unsupported": "Your server is unsupported",
"This server is using an older version of Matrix. Upgrade to Matrix %(version)s to use %(brand)s without errors.": "This server is using an older version of Matrix. Upgrade to Matrix %(version)s to use %(brand)s without errors.",
"User is not logged in": "User is not logged in",
"Database unexpectedly closed": "Database unexpectedly closed",
"This may be caused by having the app open in multiple tabs or due to clearing browser data.": "This may be caused by having the app open in multiple tabs or due to clearing browser data.",
@ -690,6 +692,7 @@
"No homeserver URL provided": "No homeserver URL provided",
"Unexpected error resolving homeserver configuration": "Unexpected error resolving homeserver configuration",
"Unexpected error resolving identity server configuration": "Unexpected error resolving identity server configuration",
"Your homeserver is too old and does not support the minimum API version required. Please contact your server owner, or upgrade your server.": "Your homeserver is too old and does not support the minimum API version required. Please contact your server owner, or upgrade your server.",
"This homeserver has hit its Monthly Active User limit.": "This homeserver has hit its Monthly Active User limit.",
"This homeserver has been blocked by its administrator.": "This homeserver has been blocked by its administrator.",
"This homeserver has exceeded one of its resource limits.": "This homeserver has exceeded one of its resource limits.",
@ -1354,11 +1357,6 @@
"Workspace: <networkLink/>": "Workspace: <networkLink/>",
"Channel: <channelLink/>": "Channel: <channelLink/>",
"No display name": "No display name",
"Warning!": "Warning!",
"Changing your password on this homeserver will cause all of your other devices to be signed out. This will delete the message encryption keys stored on them, and may make encrypted chat history unreadable.": "Changing your password on this homeserver will cause all of your other devices to be signed out. This will delete the message encryption keys stored on them, and may make encrypted chat history unreadable.",
"If you want to retain access to your chat history in encrypted rooms you should first export your room keys and re-import them afterwards.": "If you want to retain access to your chat history in encrypted rooms you should first export your room keys and re-import them afterwards.",
"You can also ask your homeserver admin to upgrade the server to change this behaviour.": "You can also ask your homeserver admin to upgrade the server to change this behaviour.",
"Export E2E room keys": "Export E2E room keys",
"Error while changing password: %(error)s": "Error while changing password: %(error)s",
"New passwords don't match": "New passwords don't match",
"Passwords can't be empty": "Passwords can't be empty",
@ -1388,6 +1386,7 @@
"Homeserver feature support:": "Homeserver feature support:",
"exists": "exists",
"<not supported>": "<not supported>",
"Export E2E room keys": "Export E2E room keys",
"Import E2E room keys": "Import E2E room keys",
"Cryptography": "Cryptography",
"Session ID:": "Session ID:",
@ -1545,7 +1544,6 @@
"%(errorMessage)s (HTTP status %(httpStatus)s)": "%(errorMessage)s (HTTP status %(httpStatus)s)",
"Error changing password": "Error changing password",
"Your password was successfully changed.": "Your password was successfully changed.",
"You will not receive push notifications on other devices until you sign back in to them.": "You will not receive push notifications on other devices until you sign back in to them.",
"Success": "Success",
"Email addresses": "Email addresses",
"Phone numbers": "Phone numbers",
@ -2315,6 +2313,7 @@
"Failed to mute user": "Failed to mute user",
"Unmute": "Unmute",
"Mute": "Mute",
"Warning!": "Warning!",
"You will not be able to undo this change as you are promoting the user to have the same power level as yourself.": "You will not be able to undo this change as you are promoting the user to have the same power level as yourself.",
"Are you sure?": "Are you sure?",
"Deactivate user?": "Deactivate user?",
@ -3561,7 +3560,6 @@
"Skip verification for now": "Skip verification for now",
"Too many attempts in a short time. Wait some time before trying again.": "Too many attempts in a short time. Wait some time before trying again.",
"Too many attempts in a short time. Retry after %(timeout)s.": "Too many attempts in a short time. Retry after %(timeout)s.",
"Resetting your password on this homeserver will cause all of your devices to be signed out. This will delete the message encryption keys stored on them, making encrypted chat history unreadable.": "Resetting your password on this homeserver will cause all of your devices to be signed out. This will delete the message encryption keys stored on them, making encrypted chat history unreadable.",
"Signing out your devices will delete the message encryption keys stored on them, making encrypted chat history unreadable.": "Signing out your devices will delete the message encryption keys stored on them, making encrypted chat history unreadable.",
"If you want to retain access to your chat history in encrypted rooms, set up Key Backup or export your message keys from one of your other devices before proceeding.": "If you want to retain access to your chat history in encrypted rooms, set up Key Backup or export your message keys from one of your other devices before proceeding.",
"Reset password": "Reset password",

View file

@ -236,6 +236,11 @@ export default class AutoDiscoveryUtils {
if (AutoDiscovery.ALL_ERRORS.indexOf(hsResult.error as string) !== -1) {
throw new UserFriendlyError(String(hsResult.error));
}
if (hsResult.error === AutoDiscovery.ERROR_HOMESERVER_TOO_OLD) {
throw new UserFriendlyError(
"Your homeserver is too old and does not support the minimum API version required. Please contact your server owner, or upgrade your server.",
);
}
throw new UserFriendlyError("Unexpected error resolving homeserver configuration");
} // else the error is not related to syntax - continue anyways.
}

View file

@ -26,6 +26,7 @@ import { MatrixClientPeg } from "../src/MatrixClientPeg";
import Modal from "../src/Modal";
import * as StorageManager from "../src/utils/StorageManager";
import { getMockClientWithEventEmitter, mockPlatformPeg } from "./test-utils";
import ToastStore from "../src/stores/ToastStore";
const webCrypto = new Crypto();
@ -50,6 +51,7 @@ describe("Lifecycle", () => {
store: {
destroy: jest.fn(),
},
getVersions: jest.fn().mockResolvedValue({ versions: ["v1.1"] }),
});
beforeEach(() => {
@ -343,6 +345,22 @@ describe("Lifecycle", () => {
});
});
});
it("should show a toast if the matrix server version is unsupported", async () => {
const toastSpy = jest.spyOn(ToastStore.sharedInstance(), "addOrReplaceToast");
mockClient.getVersions.mockResolvedValue({
versions: ["r0.6.0"],
unstable_features: {},
});
initLocalStorageMock({ ...localStorageSession });
expect(await restoreFromLocalStorage()).toEqual(true);
expect(toastSpy).toHaveBeenCalledWith(
expect.objectContaining({
title: "Your server is unsupported",
}),
);
});
});
});

View file

@ -59,6 +59,7 @@ describe("<MatrixChat />", () => {
// reused in createClient mock below
const getMockClientMethods = () => ({
...mockClientMethodsUser(userId),
getVersions: jest.fn().mockResolvedValue({ versions: ["v1.1"] }),
startClient: jest.fn(),
stopClient: jest.fn(),
setCanResetTimelineCallback: jest.fn(),
@ -178,7 +179,7 @@ describe("<MatrixChat />", () => {
mockClient = getMockClientWithEventEmitter(getMockClientMethods());
fetchMock.get("https://test.com/_matrix/client/versions", {
unstable_features: {},
versions: [],
versions: ["v1.1"],
});
localStorageSetSpy = jest.spyOn(localStorage.__proto__, "setItem");
localStorageGetSpy = jest.spyOn(localStorage.__proto__, "getItem").mockReturnValue(undefined);

View file

@ -71,7 +71,7 @@ describe("Login", function () {
fetchMock.resetHistory();
fetchMock.get("https://matrix.org/_matrix/client/versions", {
unstable_features: {},
versions: [],
versions: ["v1.1"],
});
platform = mockPlatformPeg({
startSingleSignOn: jest.fn(),
@ -209,7 +209,7 @@ describe("Login", function () {
fetchMock.get("https://server2/_matrix/client/versions", {
unstable_features: {},
versions: [],
versions: ["v1.1"],
});
rerender(getRawComponent("https://server2"));
await waitForElementToBeRemoved(() => screen.queryAllByLabelText("Loading…"));
@ -359,7 +359,7 @@ describe("Login", function () {
// but server2 is
fetchMock.get("https://server2/_matrix/client/versions", {
unstable_features: {},
versions: [],
versions: ["v1.1"],
});
const { rerender } = render(getRawComponent());
await waitForElementToBeRemoved(() => screen.queryAllByLabelText("Loading…"));

View file

@ -36,6 +36,7 @@ describe("Registration", function () {
const mockClient = mocked({
registerRequest,
loginFlows: jest.fn(),
getVersions: jest.fn().mockResolvedValue({ versions: ["v1.1"] }),
} as unknown as MatrixClient);
beforeEach(function () {
@ -59,7 +60,7 @@ describe("Registration", function () {
});
fetchMock.get("https://matrix.org/_matrix/client/versions", {
unstable_features: {},
versions: [],
versions: ["v1.1"],
});
mockPlatformPeg({
startSingleSignOn: jest.fn(),
@ -125,7 +126,7 @@ describe("Registration", function () {
fetchMock.get("https://server2/_matrix/client/versions", {
unstable_features: {},
versions: [],
versions: ["v1.1"],
});
rerender(getRawComponent("https://server2"));
await waitForElementToBeRemoved(() => screen.queryAllByLabelText("Loading…"));

View file

@ -112,7 +112,7 @@ describe("<ServerPickerDialog />", () => {
it("should allow user to revert from a custom server to the default", async () => {
fetchMock.get(`https://custom.org/_matrix/client/versions`, {
unstable_features: {},
versions: [],
versions: ["v1.1"],
});
const onFinished = jest.fn();
@ -142,7 +142,7 @@ describe("<ServerPickerDialog />", () => {
const homeserver = "https://myhomeserver.site";
fetchMock.get(`${homeserver}/_matrix/client/versions`, {
unstable_features: {},
versions: [],
versions: ["v1.1"],
});
const onFinished = jest.fn();
getComponent({ onFinished });
@ -195,7 +195,7 @@ describe("<ServerPickerDialog />", () => {
fetchMock.getOnce(wellKnownUrl, validWellKnown);
fetchMock.getOnce(versionsUrl, {
versions: [],
versions: ["v1.1"],
});
fetchMock.getOnce(isWellKnownUrl, {});
const onFinished = jest.fn();
@ -231,7 +231,7 @@ describe("<ServerPickerDialog />", () => {
const wellKnownUrl = `https://${homeserver}/.well-known/matrix/client`;
fetchMock.get(wellKnownUrl, { status: 404 });
// but is otherwise live (happy versions response)
fetchMock.get(`https://${homeserver}/_matrix/client/versions`, { versions: ["1"] });
fetchMock.get(`https://${homeserver}/_matrix/client/versions`, { versions: ["v1.1"] });
const onFinished = jest.fn();
getComponent({ onFinished });

View file

@ -56,7 +56,7 @@ describe("<MImageBody/>", () => {
},
}),
});
const url = "https://server/_matrix/media/r0/download/server/encrypted-image";
const url = "https://server/_matrix/media/v3/download/server/encrypted-image";
// eslint-disable-next-line no-restricted-properties
cli.mxcUrlToHttp.mockImplementation(
(mxcUrl: string, width?: number, height?: number, resizeMethod?: string, allowDirectLinks?: boolean) => {
@ -179,8 +179,8 @@ describe("<MImageBody/>", () => {
});
it("should fall back to /download/ if /thumbnail/ fails", async () => {
const thumbUrl = "https://server/_matrix/media/r0/thumbnail/server/image?width=800&height=600&method=scale";
const downloadUrl = "https://server/_matrix/media/r0/download/server/image";
const thumbUrl = "https://server/_matrix/media/v3/thumbnail/server/image?width=800&height=600&method=scale";
const downloadUrl = "https://server/_matrix/media/v3/download/server/image";
const event = new MatrixEvent({
room_id: "!room:server",
@ -227,7 +227,7 @@ describe("<MImageBody/>", () => {
mocked(global.URL.createObjectURL).mockReturnValue("blob:generated-thumb");
fetchMock.getOnce(
"https://server/_matrix/media/r0/download/server/image",
"https://server/_matrix/media/v3/download/server/image",
{
body: fs.readFileSync(path.resolve(__dirname, "..", "..", "..", "images", "animated-logo.webp")),
},

View file

@ -57,7 +57,7 @@ describe("MVideoBody", () => {
},
}),
});
const thumbUrl = "https://server/_matrix/media/r0/download/server/encrypted-poster";
const thumbUrl = "https://server/_matrix/media/v3/download/server/encrypted-poster";
fetchMock.getOnce(thumbUrl, { status: 200 });
// eslint-disable-next-line no-restricted-properties

View file

@ -6,7 +6,7 @@ exports[`<MImageBody/> should generate a thumbnail if one isn't included for ani
class="mx_MImageBody"
>
<a
href="https://server/_matrix/media/r0/download/server/image"
href="https://server/_matrix/media/v3/download/server/image"
>
<div
class="mx_MImageBody_thumbnail_container"

View file

@ -37,7 +37,7 @@ exports[`MVideoBody should show poster for encrypted media before downloading it
class="mx_MVideoBody"
controls=""
controlslist="nodownload"
poster="https://server/_matrix/media/r0/download/server/encrypted-poster"
poster="https://server/_matrix/media/v3/download/server/encrypted-poster"
preload="none"
title="alt for a test video"
/>

View file

@ -0,0 +1,86 @@
/*
Copyright 2023 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import React from "react";
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { mocked } from "jest-mock";
import ChangePassword from "../../../../src/components/views/settings/ChangePassword";
import { stubClient } from "../../../test-utils";
describe("<ChangePassword />", () => {
it("renders expected fields", () => {
const onFinished = jest.fn();
const onError = jest.fn();
const { asFragment } = render(<ChangePassword onFinished={onFinished} onError={onError} />);
expect(asFragment()).toMatchSnapshot();
});
it("should show validation tooltip if passwords do not match", async () => {
const onFinished = jest.fn();
const onError = jest.fn();
const { getByLabelText, getByText } = render(<ChangePassword onFinished={onFinished} onError={onError} />);
const currentPasswordField = getByLabelText("Current password");
await userEvent.type(currentPasswordField, "CurrentPassword1234");
const newPasswordField = getByLabelText("New Password");
await userEvent.type(newPasswordField, "$%newPassword1234");
const confirmPasswordField = getByLabelText("Confirm password");
await userEvent.type(confirmPasswordField, "$%newPassword1235");
await userEvent.click(getByText("Change Password"));
await expect(screen.findByText("Passwords don't match")).resolves.toBeInTheDocument();
});
it("should call MatrixClient::setPassword with expected parameters", async () => {
const cli = stubClient();
mocked(cli.setPassword).mockResolvedValue({});
const onFinished = jest.fn();
const onError = jest.fn();
const { getByLabelText, getByText } = render(<ChangePassword onFinished={onFinished} onError={onError} />);
const currentPasswordField = getByLabelText("Current password");
await userEvent.type(currentPasswordField, "CurrentPassword1234");
const newPasswordField = getByLabelText("New Password");
await userEvent.type(newPasswordField, "$%newPassword1234");
const confirmPasswordField = getByLabelText("Confirm password");
await userEvent.type(confirmPasswordField, "$%newPassword1234");
await userEvent.click(getByText("Change Password"));
await waitFor(() => {
expect(cli.setPassword).toHaveBeenCalledWith(
expect.objectContaining({
type: "m.login.password",
identifier: {
type: "m.id.user",
user: cli.getUserId(),
},
password: "CurrentPassword1234",
}),
"$%newPassword1234",
false,
);
});
expect(onFinished).toHaveBeenCalled();
});
});

View file

@ -0,0 +1,71 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`<ChangePassword /> renders expected fields 1`] = `
<DocumentFragment>
<form>
<div>
<div
class="mx_Field mx_Field_input"
>
<input
id="mx_Field_1"
label="Current password"
placeholder="Current password"
type="password"
value=""
/>
<label
for="mx_Field_1"
>
Current password
</label>
</div>
</div>
<div>
<div
class="mx_Field mx_Field_input mx_PassphraseField"
>
<input
autocomplete="new-password"
id="mx_Field_2"
label="New Password"
placeholder="New Password"
type="password"
value=""
/>
<label
for="mx_Field_2"
>
New Password
</label>
</div>
</div>
<div>
<div
class="mx_Field mx_Field_input"
>
<input
autocomplete="new-password"
id="mx_Field_3"
label="Confirm password"
placeholder="Confirm password"
type="password"
value=""
/>
<label
for="mx_Field_3"
>
Confirm password
</label>
</div>
</div>
<div
class="mx_AccessibleButton"
role="button"
tabindex="0"
>
Change Password
</div>
</form>
</DocumentFragment>
`;

View file

@ -0,0 +1,67 @@
/*
Copyright 2023 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import React from "react";
import { render } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { mocked } from "jest-mock";
import PhoneNumbers from "../../../../../src/components/views/settings/account/PhoneNumbers";
import { stubClient } from "../../../../test-utils";
import SdkConfig from "../../../../../src/SdkConfig";
describe("<PhoneNumbers />", () => {
it("should allow a phone number to be added", async () => {
SdkConfig.add({
default_country_code: "GB",
});
const cli = stubClient();
const onMsisdnsChange = jest.fn();
const { asFragment, getByLabelText, getByText } = render(
<PhoneNumbers msisdns={[]} onMsisdnsChange={onMsisdnsChange} />,
);
mocked(cli.requestAdd3pidMsisdnToken).mockResolvedValue({
sid: "SID",
msisdn: "447900111222",
submit_url: "https://server.url",
success: true,
intl_fmt: "no-clue",
});
mocked(cli.submitMsisdnTokenOtherUrl).mockResolvedValue({ success: true });
mocked(cli.addThreePidOnly).mockResolvedValue({});
const phoneNumberField = getByLabelText("Phone Number");
await userEvent.type(phoneNumberField, "7900111222");
await userEvent.click(getByText("Add"));
expect(cli.requestAdd3pidMsisdnToken).toHaveBeenCalledWith("GB", "7900111222", "t35tcl1Ent5ECr3T", 1);
expect(asFragment()).toMatchSnapshot();
const verificationCodeField = getByLabelText("Verification code");
await userEvent.type(verificationCodeField, "123666");
await userEvent.click(getByText("Continue"));
expect(cli.submitMsisdnTokenOtherUrl).toHaveBeenCalledWith(
"https://server.url",
"SID",
"t35tcl1Ent5ECr3T",
"123666",
);
expect(onMsisdnsChange).toHaveBeenCalledWith([{ address: "447900111222", medium: "msisdn" }]);
});
});

View file

@ -0,0 +1,110 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`<PhoneNumbers /> should allow a phone number to be added 1`] = `
<DocumentFragment>
<form
autocomplete="off"
class="mx_PhoneNumbers_new"
novalidate=""
>
<div
class="mx_PhoneNumbers_input"
>
<div
class="mx_Field mx_Field_input mx_Field_labelAlwaysTopLeft"
>
<span
class="mx_Field_prefix"
>
<div
class="mx_Dropdown mx_PhoneNumbers_country mx_CountryDropdown mx_Dropdown_disabled"
>
<div
aria-describedby="mx_CountryDropdown_value"
aria-disabled="true"
aria-expanded="false"
aria-haspopup="listbox"
aria-label="Country Dropdown"
aria-owns="mx_CountryDropdown_input"
class="mx_AccessibleButton mx_Dropdown_input mx_no_textinput mx_AccessibleButton_disabled"
disabled=""
role="button"
tabindex="0"
>
<div
class="mx_Dropdown_option"
id="mx_CountryDropdown_value"
>
<span
class="mx_CountryDropdown_shortOption"
>
<div
class="mx_Dropdown_option_emoji"
>
🇬🇧
</div>
+44
</span>
</div>
<span
class="mx_Dropdown_arrow"
/>
</div>
</div>
</span>
<input
autocomplete="tel-national"
disabled=""
id="mx_Field_1"
label="Phone Number"
placeholder="Phone Number"
type="text"
value="7900111222"
/>
<label
for="mx_Field_1"
>
Phone Number
</label>
</div>
</div>
</form>
<div>
<div>
A text message has been sent to +447900111222. Please enter the verification code it contains.
<br />
</div>
<form
autocomplete="off"
novalidate=""
>
<div
class="mx_Field mx_Field_input"
>
<input
autocomplete="off"
id="mx_Field_2"
label="Verification code"
placeholder="Verification code"
type="text"
value=""
/>
<label
for="mx_Field_2"
>
Verification code
</label>
</div>
<div
aria-disabled="true"
class="mx_AccessibleButton mx_AccessibleButton_hasKind mx_AccessibleButton_kind_primary mx_AccessibleButton_disabled"
disabled=""
role="button"
tabindex="0"
>
Continue
</div>
</form>
</div>
</DocumentFragment>
`;

View file

@ -42,7 +42,6 @@ describe("<EmailAddress/>", () => {
const mockClient = getMockClientWithEventEmitter({
getIdentityServerUrl: jest.fn().mockReturnValue("https://fake-identity-server"),
generateClientSecret: jest.fn(),
doesServerSupportSeparateAddAndBind: jest.fn(),
requestEmailToken: jest.fn(),
bindThreePid: jest.fn(),
});
@ -74,7 +73,6 @@ describe("<EmailAddress/>", () => {
describe("Email verification share phase", () => {
it("shows translated error message", async () => {
render(<EmailAddress email={emailThreepidFixture} />);
mockClient.doesServerSupportSeparateAddAndBind.mockResolvedValue(true);
mockClient.requestEmailToken.mockRejectedValue(
new MatrixError(
{ errcode: "M_THREEPID_IN_USE", error: "Some fake MatrixError occured" },
@ -94,7 +92,6 @@ describe("<EmailAddress/>", () => {
// Start these tests out at the "Complete" phase
render(<EmailAddress email={emailThreepidFixture} />);
mockClient.requestEmailToken.mockResolvedValue({ sid: "123-fake-sid" } satisfies IRequestTokenResponse);
mockClient.doesServerSupportSeparateAddAndBind.mockResolvedValue(true);
fireEvent.click(screen.getByText("Share"));
// Then wait for the completion screen to come up
await screen.findByText("Complete");

View file

@ -15,38 +15,47 @@ limitations under the License.
*/
import React from "react";
import { render, screen } from "@testing-library/react";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { IThreepid, ThreepidMedium } from "matrix-js-sdk/src/@types/threepids";
import userEvent from "@testing-library/user-event";
import { mocked } from "jest-mock";
import PhoneNumbers, { PhoneNumber } from "../../../../../src/components/views/settings/discovery/PhoneNumbers";
import { stubClient } from "../../../../test-utils";
const msisdn: IThreepid = {
medium: ThreepidMedium.Phone,
address: "+441111111111",
address: "441111111111",
validated_at: 12345,
added_at: 12342,
bound: false,
};
describe("<PhoneNumber/>", () => {
it("should track props.msisdn.bound changes", async () => {
const { rerender } = render(<PhoneNumber msisdn={msisdn} />);
const { rerender } = render(<PhoneNumber msisdn={{ ...msisdn }} />);
await screen.findByText("Share");
msisdn.bound = true;
rerender(<PhoneNumber msisdn={{ ...msisdn }} />);
rerender(<PhoneNumber msisdn={{ ...msisdn, bound: true }} />);
await screen.findByText("Revoke");
});
});
const mockGetAccessToken = jest.fn().mockResolvedValue("$$getAccessToken");
jest.mock("../../../../../src/IdentityAuthClient", () =>
jest.fn().mockImplementation(() => ({
getAccessToken: mockGetAccessToken,
})),
);
describe("<PhoneNumbers />", () => {
it("should render a loader while loading", async () => {
const { container } = render(<PhoneNumbers msisdns={[msisdn]} isLoading={true} />);
const { container } = render(<PhoneNumbers msisdns={[{ ...msisdn }]} isLoading={true} />);
expect(container).toMatchSnapshot();
});
it("should render phone numbers", async () => {
const { container } = render(<PhoneNumbers msisdns={[msisdn]} isLoading={false} />);
const { container } = render(<PhoneNumbers msisdns={[{ ...msisdn }]} isLoading={false} />);
expect(container).toMatchSnapshot();
});
@ -56,4 +65,37 @@ describe("<PhoneNumbers />", () => {
expect(container).toMatchSnapshot();
});
it("should allow binding msisdn", async () => {
const cli = stubClient();
const { getByText, getByLabelText, asFragment } = render(
<PhoneNumbers msisdns={[{ ...msisdn }]} isLoading={false} />,
);
mocked(cli.requestMsisdnToken).mockResolvedValue({
sid: "SID",
msisdn: "+447900111222",
submit_url: "https://server.url",
success: true,
intl_fmt: "no-clue",
});
fireEvent.click(getByText("Share"));
await waitFor(() =>
expect(cli.requestMsisdnToken).toHaveBeenCalledWith(
null,
"+441111111111",
"t35tcl1Ent5ECr3T",
1,
undefined,
"$$getAccessToken",
),
);
expect(asFragment()).toMatchSnapshot();
const verificationCodeField = getByLabelText("Verification code");
await userEvent.type(verificationCodeField, "123666{Enter}");
expect(cli.submitMsisdnToken).toHaveBeenCalledWith("SID", "t35tcl1Ent5ECr3T", "123666", "$$getAccessToken");
});
});

View file

@ -1,5 +1,67 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`<PhoneNumbers /> should allow binding msisdn 1`] = `
<DocumentFragment>
<div
class="mx_SettingsSubsection"
data-testid="mx_DiscoveryPhoneNumbers"
>
<div
class="mx_SettingsSubsectionHeading"
>
<h3
class="mx_Heading_h4 mx_SettingsSubsectionHeading_heading"
>
Phone numbers
</h3>
</div>
<div
class="mx_SettingsSubsection_content mx_SettingsSubsection_contentStretch"
>
<div
class="mx_GeneralUserSettingsTab_section--discovery_existing"
>
<span
class="mx_GeneralUserSettingsTab_section--discovery_existing_address"
>
+441111111111
</span>
<span
class="mx_GeneralUserSettingsTab_section--discovery_existing_verification"
>
<span>
Please enter verification code sent via text.
<br />
</span>
<form
autocomplete="off"
novalidate=""
>
<div
class="mx_Field mx_Field_input"
>
<input
autocomplete="off"
id="mx_Field_1"
label="Verification code"
placeholder="Verification code"
type="text"
value=""
/>
<label
for="mx_Field_1"
>
Verification code
</label>
</div>
</form>
</span>
</div>
</div>
</div>
</DocumentFragment>
`;
exports[`<PhoneNumbers /> should handle no numbers 1`] = `
<div>
<div
@ -85,14 +147,14 @@ exports[`<PhoneNumbers /> should render phone numbers 1`] = `
class="mx_GeneralUserSettingsTab_section--discovery_existing_address"
>
+
+441111111111
441111111111
</span>
<div
class="mx_AccessibleButton mx_GeneralUserSettingsTab_section--discovery_existing_button mx_AccessibleButton_hasKind mx_AccessibleButton_kind_danger_sm"
class="mx_AccessibleButton mx_GeneralUserSettingsTab_section--discovery_existing_button mx_AccessibleButton_hasKind mx_AccessibleButton_kind_primary_sm"
role="button"
tabindex="0"
>
Revoke
Share
</div>
</div>
</div>

View file

@ -126,7 +126,6 @@ export const mockClientMethodsEvents = () => ({
* Returns basic mocked client methods related to server support
*/
export const mockClientMethodsServer = (): Partial<Record<MethodLikeKeys<MatrixClient>, unknown>> => ({
doesServerSupportSeparateAddAndBind: jest.fn(),
getIdentityServerUrl: jest.fn(),
getHomeserverUrl: jest.fn(),
getCapabilities: jest.fn().mockReturnValue({}),

View file

@ -217,7 +217,6 @@ export function createTestClient(): MatrixClient {
uploadContent: jest.fn(),
getEventMapper: (_options?: MapperOpts) => (event: Partial<IEvent>) => new MatrixEvent(event),
leaveRoomChain: jest.fn((roomId) => ({ [roomId]: null })),
doesServerSupportLogoutDevices: jest.fn().mockReturnValue(true),
requestPasswordEmailToken: jest.fn().mockRejectedValue({}),
setPassword: jest.fn().mockRejectedValue({}),
groupCallEventHandler: { groupCalls: new Map<string, GroupCall>() },
@ -244,6 +243,12 @@ export function createTestClient(): MatrixClient {
exportRoomKeys: jest.fn(),
knockRoom: jest.fn(),
leave: jest.fn(),
getVersions: jest.fn().mockResolvedValue({ versions: ["v1.1"] }),
requestAdd3pidMsisdnToken: jest.fn(),
submitMsisdnTokenOtherUrl: jest.fn(),
addThreePidOnly: jest.fn(),
requestMsisdnToken: jest.fn(),
submitMsisdnToken: jest.fn(),
} as unknown as MatrixClient;
client.reEmitter = new ReEmitter(client);

View file

@ -232,5 +232,22 @@ describe("AutoDiscoveryUtils", () => {
warning: undefined,
});
});
it("handles homeserver too old error", () => {
const discoveryResult: ClientConfig = {
...validIsConfig,
"m.homeserver": {
state: AutoDiscoveryAction.FAIL_ERROR,
error: AutoDiscovery.ERROR_HOMESERVER_TOO_OLD,
base_url: "https://matrix.org",
},
};
const syntaxOnly = true;
expect(() =>
AutoDiscoveryUtils.buildValidatedConfigFromDiscovery(serverName, discoveryResult, syntaxOnly),
).toThrow(
"Your homeserver is too old and does not support the minimum API version required. Please contact your server owner, or upgrade your server.",
);
});
});
});