Support Matrix 1.1 (drop legacy r0 versions) (#9819)
Co-authored-by: Michael Telatynski <7t3chguy@gmail.com>
This commit is contained in:
parent
f9e79fd5d6
commit
180fcaa70f
32 changed files with 712 additions and 440 deletions
|
@ -288,7 +288,7 @@ describe("Read receipts", () => {
|
||||||
cy.intercept({
|
cy.intercept({
|
||||||
method: "POST",
|
method: "POST",
|
||||||
url: new RegExp(
|
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");
|
}).as("receiptRequest");
|
||||||
|
|
||||||
|
@ -321,7 +321,7 @@ describe("Read receipts", () => {
|
||||||
|
|
||||||
cy.intercept({
|
cy.intercept({
|
||||||
method: "POST",
|
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");
|
}).as("readMarkersRequest");
|
||||||
|
|
||||||
cy.findByRole("button", { name: "Jump to first unread message." }).click();
|
cy.findByRole("button", { name: "Jump to first unread message." }).click();
|
||||||
|
@ -341,7 +341,7 @@ describe("Read receipts", () => {
|
||||||
|
|
||||||
cy.intercept({
|
cy.intercept({
|
||||||
method: "POST",
|
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");
|
}).as("readMarkersRequest");
|
||||||
|
|
||||||
cy.findByRole("button", { name: "Scroll to most recent messages" }).click();
|
cy.findByRole("button", { name: "Scroll to most recent messages" }).click();
|
||||||
|
|
|
@ -704,14 +704,14 @@ describe("Timeline", () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should render url previews", () => {
|
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,
|
statusCode: 200,
|
||||||
fixture: "riot.png",
|
fixture: "riot.png",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "image/png",
|
"Content-Type": "image/png",
|
||||||
},
|
},
|
||||||
}).as("mxc");
|
}).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,
|
statusCode: 200,
|
||||||
body: {
|
body: {
|
||||||
"og:title": "Element Call",
|
"og:title": "Element Call",
|
||||||
|
|
|
@ -62,7 +62,7 @@ declare global {
|
||||||
Cypress.Commands.add(
|
Cypress.Commands.add(
|
||||||
"loginUser",
|
"loginUser",
|
||||||
(homeserver: HomeserverInstance, username: string, password: string): Chainable<UserCredentials> => {
|
(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
|
return cy
|
||||||
.request<{
|
.request<{
|
||||||
access_token: string;
|
access_token: string;
|
||||||
|
|
|
@ -100,30 +100,25 @@ export default class AddThreepid {
|
||||||
*/
|
*/
|
||||||
public async bindEmailAddress(emailAddress: string): Promise<IRequestTokenResponse> {
|
public async bindEmailAddress(emailAddress: string): Promise<IRequestTokenResponse> {
|
||||||
this.bind = true;
|
this.bind = true;
|
||||||
if (await this.matrixClient.doesServerSupportSeparateAddAndBind()) {
|
// For separate bind, request a token directly from the IS.
|
||||||
// For separate bind, request a token directly from the IS.
|
const authClient = new IdentityAuthClient();
|
||||||
const authClient = new IdentityAuthClient();
|
const identityAccessToken = (await authClient.getAccessToken()) ?? undefined;
|
||||||
const identityAccessToken = (await authClient.getAccessToken()) ?? undefined;
|
try {
|
||||||
try {
|
const res = await this.matrixClient.requestEmailToken(
|
||||||
const res = await this.matrixClient.requestEmailToken(
|
emailAddress,
|
||||||
emailAddress,
|
this.clientSecret,
|
||||||
this.clientSecret,
|
1,
|
||||||
1,
|
undefined,
|
||||||
undefined,
|
identityAccessToken,
|
||||||
identityAccessToken,
|
);
|
||||||
);
|
this.sessionId = res.sid;
|
||||||
this.sessionId = res.sid;
|
return res;
|
||||||
return res;
|
} catch (err) {
|
||||||
} catch (err) {
|
if (err instanceof MatrixError && err.errcode === "M_THREEPID_IN_USE") {
|
||||||
if (err instanceof MatrixError && err.errcode === "M_THREEPID_IN_USE") {
|
throw new UserFriendlyError("This email address is already in use", { cause: err });
|
||||||
throw new UserFriendlyError("This email address is already in use", { cause: err });
|
|
||||||
}
|
|
||||||
// Otherwise, just blurt out the same error
|
|
||||||
throw err;
|
|
||||||
}
|
}
|
||||||
} else {
|
// Otherwise, just blurt out the same error
|
||||||
// For tangled bind, request a token via the HS.
|
throw err;
|
||||||
return this.addEmailAddress(emailAddress);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -163,31 +158,26 @@ export default class AddThreepid {
|
||||||
*/
|
*/
|
||||||
public async bindMsisdn(phoneCountry: string, phoneNumber: string): Promise<IRequestMsisdnTokenResponse> {
|
public async bindMsisdn(phoneCountry: string, phoneNumber: string): Promise<IRequestMsisdnTokenResponse> {
|
||||||
this.bind = true;
|
this.bind = true;
|
||||||
if (await this.matrixClient.doesServerSupportSeparateAddAndBind()) {
|
// For separate bind, request a token directly from the IS.
|
||||||
// For separate bind, request a token directly from the IS.
|
const authClient = new IdentityAuthClient();
|
||||||
const authClient = new IdentityAuthClient();
|
const identityAccessToken = (await authClient.getAccessToken()) ?? undefined;
|
||||||
const identityAccessToken = (await authClient.getAccessToken()) ?? undefined;
|
try {
|
||||||
try {
|
const res = await this.matrixClient.requestMsisdnToken(
|
||||||
const res = await this.matrixClient.requestMsisdnToken(
|
phoneCountry,
|
||||||
phoneCountry,
|
phoneNumber,
|
||||||
phoneNumber,
|
this.clientSecret,
|
||||||
this.clientSecret,
|
1,
|
||||||
1,
|
undefined,
|
||||||
undefined,
|
identityAccessToken,
|
||||||
identityAccessToken,
|
);
|
||||||
);
|
this.sessionId = res.sid;
|
||||||
this.sessionId = res.sid;
|
return res;
|
||||||
return res;
|
} catch (err) {
|
||||||
} catch (err) {
|
if (err instanceof MatrixError && err.errcode === "M_THREEPID_IN_USE") {
|
||||||
if (err instanceof MatrixError && err.errcode === "M_THREEPID_IN_USE") {
|
throw new UserFriendlyError("This phone number is already in use", { cause: err });
|
||||||
throw new UserFriendlyError("This phone number is already in use", { cause: err });
|
|
||||||
}
|
|
||||||
// Otherwise, just blurt out the same error
|
|
||||||
throw err;
|
|
||||||
}
|
}
|
||||||
} else {
|
// Otherwise, just blurt out the same error
|
||||||
// For tangled bind, request a token via the HS.
|
throw err;
|
||||||
return this.addMsisdn(phoneCountry, phoneNumber);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -199,70 +189,59 @@ export default class AddThreepid {
|
||||||
*/
|
*/
|
||||||
public async checkEmailLinkClicked(): Promise<[success?: boolean, result?: IAuthData | Error | null]> {
|
public async checkEmailLinkClicked(): Promise<[success?: boolean, result?: IAuthData | Error | null]> {
|
||||||
try {
|
try {
|
||||||
if (await this.matrixClient.doesServerSupportSeparateAddAndBind()) {
|
if (this.bind) {
|
||||||
if (this.bind) {
|
const authClient = new IdentityAuthClient();
|
||||||
const authClient = new IdentityAuthClient();
|
const identityAccessToken = await authClient.getAccessToken();
|
||||||
const identityAccessToken = await authClient.getAccessToken();
|
if (!identityAccessToken) {
|
||||||
if (!identityAccessToken) {
|
throw new UserFriendlyError("No identity access token found");
|
||||||
throw new UserFriendlyError("No identity access token found");
|
|
||||||
}
|
|
||||||
await this.matrixClient.bindThreePid({
|
|
||||||
sid: this.sessionId!,
|
|
||||||
client_secret: this.clientSecret,
|
|
||||||
id_server: getIdServerDomain(this.matrixClient),
|
|
||||||
id_access_token: identityAccessToken,
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
try {
|
|
||||||
await this.makeAddThreepidOnlyRequest();
|
|
||||||
|
|
||||||
// The spec has always required this to use UI auth but synapse briefly
|
|
||||||
// implemented it without, so this may just succeed and that's OK.
|
|
||||||
return [true];
|
|
||||||
} catch (err) {
|
|
||||||
if (!(err instanceof MatrixError) || err.httpStatus !== 401 || !err.data || !err.data.flows) {
|
|
||||||
// doesn't look like an interactive-auth failure
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
|
|
||||||
const dialogAesthetics = {
|
|
||||||
[SSOAuthEntry.PHASE_PREAUTH]: {
|
|
||||||
title: _t("Use Single Sign On to continue"),
|
|
||||||
body: _t(
|
|
||||||
"Confirm adding this email address by using Single Sign On to prove your identity.",
|
|
||||||
),
|
|
||||||
continueText: _t("Single Sign On"),
|
|
||||||
continueKind: "primary",
|
|
||||||
},
|
|
||||||
[SSOAuthEntry.PHASE_POSTAUTH]: {
|
|
||||||
title: _t("Confirm adding email"),
|
|
||||||
body: _t("Click the button below to confirm adding this email address."),
|
|
||||||
continueText: _t("Confirm"),
|
|
||||||
continueKind: "primary",
|
|
||||||
},
|
|
||||||
};
|
|
||||||
const { finished } = Modal.createDialog(InteractiveAuthDialog<{}>, {
|
|
||||||
title: _t("Add Email Address"),
|
|
||||||
matrixClient: this.matrixClient,
|
|
||||||
authData: err.data,
|
|
||||||
makeRequest: this.makeAddThreepidOnlyRequest,
|
|
||||||
aestheticsForStagePhases: {
|
|
||||||
[SSOAuthEntry.LOGIN_TYPE]: dialogAesthetics,
|
|
||||||
[SSOAuthEntry.UNSTABLE_LOGIN_TYPE]: dialogAesthetics,
|
|
||||||
},
|
|
||||||
} as InteractiveAuthDialogProps<IAddThreePidOnlyBody>);
|
|
||||||
return finished;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
await this.matrixClient.bindThreePid({
|
||||||
|
sid: this.sessionId!,
|
||||||
|
client_secret: this.clientSecret,
|
||||||
|
id_server: getIdServerDomain(this.matrixClient),
|
||||||
|
id_access_token: identityAccessToken,
|
||||||
|
});
|
||||||
} else {
|
} else {
|
||||||
await this.matrixClient.addThreePid(
|
try {
|
||||||
{
|
await this.makeAddThreepidOnlyRequest();
|
||||||
sid: this.sessionId!,
|
|
||||||
client_secret: this.clientSecret,
|
// The spec has always required this to use UI auth but synapse briefly
|
||||||
id_server: getIdServerDomain(this.matrixClient),
|
// implemented it without, so this may just succeed and that's OK.
|
||||||
},
|
return [true];
|
||||||
this.bind,
|
} catch (err) {
|
||||||
);
|
if (!(err instanceof MatrixError) || err.httpStatus !== 401 || !err.data || !err.data.flows) {
|
||||||
|
// doesn't look like an interactive-auth failure
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
|
||||||
|
const dialogAesthetics = {
|
||||||
|
[SSOAuthEntry.PHASE_PREAUTH]: {
|
||||||
|
title: _t("Use Single Sign On to continue"),
|
||||||
|
body: _t(
|
||||||
|
"Confirm adding this email address by using Single Sign On to prove your identity.",
|
||||||
|
),
|
||||||
|
continueText: _t("Single Sign On"),
|
||||||
|
continueKind: "primary",
|
||||||
|
},
|
||||||
|
[SSOAuthEntry.PHASE_POSTAUTH]: {
|
||||||
|
title: _t("Confirm adding email"),
|
||||||
|
body: _t("Click the button below to confirm adding this email address."),
|
||||||
|
continueText: _t("Confirm"),
|
||||||
|
continueKind: "primary",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const { finished } = Modal.createDialog(InteractiveAuthDialog<{}>, {
|
||||||
|
title: _t("Add Email Address"),
|
||||||
|
matrixClient: this.matrixClient,
|
||||||
|
authData: err.data,
|
||||||
|
makeRequest: this.makeAddThreepidOnlyRequest,
|
||||||
|
aestheticsForStagePhases: {
|
||||||
|
[SSOAuthEntry.LOGIN_TYPE]: dialogAesthetics,
|
||||||
|
[SSOAuthEntry.UNSTABLE_LOGIN_TYPE]: dialogAesthetics,
|
||||||
|
},
|
||||||
|
} as InteractiveAuthDialogProps<IAddThreePidOnlyBody>);
|
||||||
|
return finished;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err instanceof HTTPError && err.httpStatus === 401) {
|
if (err instanceof HTTPError && err.httpStatus === 401) {
|
||||||
|
@ -301,7 +280,6 @@ export default class AddThreepid {
|
||||||
msisdnToken: string,
|
msisdnToken: string,
|
||||||
): Promise<[success?: boolean, result?: IAuthData | Error | null] | undefined> {
|
): Promise<[success?: boolean, result?: IAuthData | Error | null] | undefined> {
|
||||||
const authClient = new IdentityAuthClient();
|
const authClient = new IdentityAuthClient();
|
||||||
const supportsSeparateAddAndBind = await this.matrixClient.doesServerSupportSeparateAddAndBind();
|
|
||||||
|
|
||||||
let result: { success: boolean } | MatrixError;
|
let result: { success: boolean } | MatrixError;
|
||||||
if (this.submitUrl) {
|
if (this.submitUrl) {
|
||||||
|
@ -311,7 +289,7 @@ export default class AddThreepid {
|
||||||
this.clientSecret,
|
this.clientSecret,
|
||||||
msisdnToken,
|
msisdnToken,
|
||||||
);
|
);
|
||||||
} else if (this.bind || !supportsSeparateAddAndBind) {
|
} else if (this.bind) {
|
||||||
result = await this.matrixClient.submitMsisdnToken(
|
result = await this.matrixClient.submitMsisdnToken(
|
||||||
this.sessionId!,
|
this.sessionId!,
|
||||||
this.clientSecret,
|
this.clientSecret,
|
||||||
|
@ -325,65 +303,52 @@ export default class AddThreepid {
|
||||||
throw result;
|
throw result;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (supportsSeparateAddAndBind) {
|
if (this.bind) {
|
||||||
if (this.bind) {
|
await this.matrixClient.bindThreePid({
|
||||||
await this.matrixClient.bindThreePid({
|
sid: this.sessionId!,
|
||||||
sid: this.sessionId!,
|
client_secret: this.clientSecret,
|
||||||
client_secret: this.clientSecret,
|
id_server: getIdServerDomain(this.matrixClient),
|
||||||
id_server: getIdServerDomain(this.matrixClient),
|
id_access_token: await authClient.getAccessToken(),
|
||||||
id_access_token: await authClient.getAccessToken(),
|
});
|
||||||
});
|
|
||||||
} else {
|
|
||||||
try {
|
|
||||||
await this.makeAddThreepidOnlyRequest();
|
|
||||||
|
|
||||||
// The spec has always required this to use UI auth but synapse briefly
|
|
||||||
// implemented it without, so this may just succeed and that's OK.
|
|
||||||
return;
|
|
||||||
} catch (err) {
|
|
||||||
if (!(err instanceof MatrixError) || err.httpStatus !== 401 || !err.data || !err.data.flows) {
|
|
||||||
// doesn't look like an interactive-auth failure
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
|
|
||||||
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.",
|
|
||||||
),
|
|
||||||
continueText: _t("Single Sign On"),
|
|
||||||
continueKind: "primary",
|
|
||||||
},
|
|
||||||
[SSOAuthEntry.PHASE_POSTAUTH]: {
|
|
||||||
title: _t("Confirm adding phone number"),
|
|
||||||
body: _t("Click the button below to confirm adding this phone number."),
|
|
||||||
continueText: _t("Confirm"),
|
|
||||||
continueKind: "primary",
|
|
||||||
},
|
|
||||||
};
|
|
||||||
const { finished } = Modal.createDialog(InteractiveAuthDialog<{}>, {
|
|
||||||
title: _t("Add Phone Number"),
|
|
||||||
matrixClient: this.matrixClient,
|
|
||||||
authData: err.data,
|
|
||||||
makeRequest: this.makeAddThreepidOnlyRequest,
|
|
||||||
aestheticsForStagePhases: {
|
|
||||||
[SSOAuthEntry.LOGIN_TYPE]: dialogAesthetics,
|
|
||||||
[SSOAuthEntry.UNSTABLE_LOGIN_TYPE]: dialogAesthetics,
|
|
||||||
},
|
|
||||||
} as InteractiveAuthDialogProps<IAddThreePidOnlyBody>);
|
|
||||||
return finished;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
await this.matrixClient.addThreePid(
|
try {
|
||||||
{
|
await this.makeAddThreepidOnlyRequest();
|
||||||
sid: this.sessionId!,
|
|
||||||
client_secret: this.clientSecret,
|
// The spec has always required this to use UI auth but synapse briefly
|
||||||
id_server: getIdServerDomain(this.matrixClient),
|
// implemented it without, so this may just succeed and that's OK.
|
||||||
},
|
return;
|
||||||
this.bind,
|
} catch (err) {
|
||||||
);
|
if (!(err instanceof MatrixError) || err.httpStatus !== 401 || !err.data || !err.data.flows) {
|
||||||
|
// doesn't look like an interactive-auth failure
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
|
||||||
|
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."),
|
||||||
|
continueText: _t("Single Sign On"),
|
||||||
|
continueKind: "primary",
|
||||||
|
},
|
||||||
|
[SSOAuthEntry.PHASE_POSTAUTH]: {
|
||||||
|
title: _t("Confirm adding phone number"),
|
||||||
|
body: _t("Click the button below to confirm adding this phone number."),
|
||||||
|
continueText: _t("Confirm"),
|
||||||
|
continueKind: "primary",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const { finished } = Modal.createDialog(InteractiveAuthDialog<{}>, {
|
||||||
|
title: _t("Add Phone Number"),
|
||||||
|
matrixClient: this.matrixClient,
|
||||||
|
authData: err.data,
|
||||||
|
makeRequest: this.makeAddThreepidOnlyRequest,
|
||||||
|
aestheticsForStagePhases: {
|
||||||
|
[SSOAuthEntry.LOGIN_TYPE]: dialogAesthetics,
|
||||||
|
[SSOAuthEntry.UNSTABLE_LOGIN_TYPE]: dialogAesthetics,
|
||||||
|
},
|
||||||
|
} as InteractiveAuthDialogProps<IAddThreePidOnlyBody>);
|
||||||
|
return finished;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -24,6 +24,7 @@ import { decryptAES, encryptAES, IEncryptedPayload } from "matrix-js-sdk/src/cry
|
||||||
import { QueryDict } from "matrix-js-sdk/src/utils";
|
import { QueryDict } from "matrix-js-sdk/src/utils";
|
||||||
import { logger } from "matrix-js-sdk/src/logger";
|
import { logger } from "matrix-js-sdk/src/logger";
|
||||||
import { SSOAction } from "matrix-js-sdk/src/@types/auth";
|
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 { IMatrixClientCreds, MatrixClientPeg } from "./MatrixClientPeg";
|
||||||
import SecurityCustomisations from "./customisations/Security";
|
import SecurityCustomisations from "./customisations/Security";
|
||||||
|
@ -66,6 +67,7 @@ import { SdkContextClass } from "./contexts/SDKContext";
|
||||||
import { messageForLoginError } from "./utils/ErrorUtils";
|
import { messageForLoginError } from "./utils/ErrorUtils";
|
||||||
import { completeOidcLogin } from "./utils/oidc/authorize";
|
import { completeOidcLogin } from "./utils/oidc/authorize";
|
||||||
import { persistOidcAuthenticatedSettings } from "./utils/oidc/persistOidcSettings";
|
import { persistOidcAuthenticatedSettings } from "./utils/oidc/persistOidcSettings";
|
||||||
|
import GenericToast from "./components/views/toasts/GenericToast";
|
||||||
|
|
||||||
const HOMESERVER_URL_KEY = "mx_hs_url";
|
const HOMESERVER_URL_KEY = "mx_hs_url";
|
||||||
const ID_SERVER_URL_KEY = "mx_is_url";
|
const ID_SERVER_URL_KEY = "mx_is_url";
|
||||||
|
@ -584,6 +586,7 @@ export async function restoreFromLocalStorage(opts?: { ignoreGuest?: boolean }):
|
||||||
},
|
},
|
||||||
false,
|
false,
|
||||||
);
|
);
|
||||||
|
checkServerVersions();
|
||||||
return true;
|
return true;
|
||||||
} else {
|
} else {
|
||||||
logger.log("No previous session found.");
|
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> {
|
async function handleLoadSessionFailure(e: unknown): Promise<boolean> {
|
||||||
logger.error("Unable to load session", e);
|
logger.error("Unable to load session", e);
|
||||||
|
|
||||||
|
|
|
@ -18,7 +18,6 @@ limitations under the License.
|
||||||
|
|
||||||
import React, { ReactNode } from "react";
|
import React, { ReactNode } from "react";
|
||||||
import { logger } from "matrix-js-sdk/src/logger";
|
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 { sleep } from "matrix-js-sdk/src/utils";
|
||||||
|
|
||||||
import { _t, _td } from "../../../languageHandler";
|
import { _t, _td } from "../../../languageHandler";
|
||||||
|
@ -81,7 +80,6 @@ interface State {
|
||||||
serverIsAlive: boolean;
|
serverIsAlive: boolean;
|
||||||
serverDeadError: string;
|
serverDeadError: string;
|
||||||
|
|
||||||
serverSupportsControlOfDevicesLogout: boolean;
|
|
||||||
logoutDevices: boolean;
|
logoutDevices: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -104,16 +102,11 @@ export default class ForgotPassword extends React.Component<Props, State> {
|
||||||
// be seeing.
|
// be seeing.
|
||||||
serverIsAlive: true,
|
serverIsAlive: true,
|
||||||
serverDeadError: "",
|
serverDeadError: "",
|
||||||
serverSupportsControlOfDevicesLogout: false,
|
|
||||||
logoutDevices: false,
|
logoutDevices: false,
|
||||||
};
|
};
|
||||||
this.reset = new PasswordReset(this.props.serverConfig.hsUrl, this.props.serverConfig.isUrl);
|
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 {
|
public componentDidUpdate(prevProps: Readonly<Props>): void {
|
||||||
if (
|
if (
|
||||||
prevProps.serverConfig.hsUrl !== this.props.serverConfig.hsUrl ||
|
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
|
// Do a liveliness check on the new URLs
|
||||||
this.checkServerLiveliness(this.props.serverConfig);
|
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> {
|
private async onPhaseEmailInputSubmit(): Promise<void> {
|
||||||
this.phase = Phase.SendingEmail;
|
this.phase = Phase.SendingEmail;
|
||||||
|
|
||||||
|
@ -376,16 +353,10 @@ export default class ForgotPassword extends React.Component<Props, State> {
|
||||||
description: (
|
description: (
|
||||||
<div>
|
<div>
|
||||||
<p>
|
<p>
|
||||||
{!this.state.serverSupportsControlOfDevicesLogout
|
{_t(
|
||||||
? _t(
|
"Signing out your devices will delete the message encryption keys stored on them, " +
|
||||||
"Resetting your password on this homeserver will cause all of your devices to be " +
|
"making encrypted chat history unreadable.",
|
||||||
"signed out. This will delete the message encryption keys stored on them, " +
|
)}
|
||||||
"making encrypted chat history unreadable.",
|
|
||||||
)
|
|
||||||
: _t(
|
|
||||||
"Signing out your devices will delete the message encryption keys stored on them, " +
|
|
||||||
"making encrypted chat history unreadable.",
|
|
||||||
)}
|
|
||||||
</p>
|
</p>
|
||||||
<p>
|
<p>
|
||||||
{_t(
|
{_t(
|
||||||
|
@ -446,16 +417,14 @@ export default class ForgotPassword extends React.Component<Props, State> {
|
||||||
autoComplete="new-password"
|
autoComplete="new-password"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
{this.state.serverSupportsControlOfDevicesLogout ? (
|
<div className="mx_AuthBody_fieldRow">
|
||||||
<div className="mx_AuthBody_fieldRow">
|
<StyledCheckbox
|
||||||
<StyledCheckbox
|
onChange={() => this.setState({ logoutDevices: !this.state.logoutDevices })}
|
||||||
onChange={() => this.setState({ logoutDevices: !this.state.logoutDevices })}
|
checked={this.state.logoutDevices}
|
||||||
checked={this.state.logoutDevices}
|
>
|
||||||
>
|
{_t("Sign out of all devices")}
|
||||||
{_t("Sign out of all devices")}
|
</StyledCheckbox>
|
||||||
</StyledCheckbox>
|
</div>
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
{this.state.errorText && <ErrorMessage message={this.state.errorText} />}
|
{this.state.errorText && <ErrorMessage message={this.state.errorText} />}
|
||||||
<button type="submit" className="mx_Login_submit">
|
<button type="submit" className="mx_Login_submit">
|
||||||
{submitButtonChild}
|
{submitButtonChild}
|
||||||
|
|
|
@ -18,7 +18,6 @@ limitations under the License.
|
||||||
import React from "react";
|
import React from "react";
|
||||||
import { MatrixClient } from "matrix-js-sdk/src/matrix";
|
import { MatrixClient } from "matrix-js-sdk/src/matrix";
|
||||||
|
|
||||||
import type ExportE2eKeysDialog from "../../../async-components/views/dialogs/security/ExportE2eKeysDialog";
|
|
||||||
import Field from "../elements/Field";
|
import Field from "../elements/Field";
|
||||||
import { MatrixClientPeg } from "../../../MatrixClientPeg";
|
import { MatrixClientPeg } from "../../../MatrixClientPeg";
|
||||||
import AccessibleButton from "../elements/AccessibleButton";
|
import AccessibleButton from "../elements/AccessibleButton";
|
||||||
|
@ -29,7 +28,6 @@ import Modal from "../../../Modal";
|
||||||
import PassphraseField from "../auth/PassphraseField";
|
import PassphraseField from "../auth/PassphraseField";
|
||||||
import { PASSWORD_MIN_SCORE } from "../auth/RegistrationForm";
|
import { PASSWORD_MIN_SCORE } from "../auth/RegistrationForm";
|
||||||
import SetEmailDialog from "../dialogs/SetEmailDialog";
|
import SetEmailDialog from "../dialogs/SetEmailDialog";
|
||||||
import QuestionDialog from "../dialogs/QuestionDialog";
|
|
||||||
|
|
||||||
const FIELD_OLD_PASSWORD = "field_old_password";
|
const FIELD_OLD_PASSWORD = "field_old_password";
|
||||||
const FIELD_NEW_PASSWORD = "field_new_password";
|
const FIELD_NEW_PASSWORD = "field_new_password";
|
||||||
|
@ -43,11 +41,7 @@ enum Phase {
|
||||||
}
|
}
|
||||||
|
|
||||||
interface IProps {
|
interface IProps {
|
||||||
onFinished: (outcome: {
|
onFinished: (outcome: { didSetEmail?: boolean }) => void;
|
||||||
didSetEmail?: boolean;
|
|
||||||
/** Was one or more other devices logged out whilst changing the password */
|
|
||||||
didLogoutOutOtherDevices: boolean;
|
|
||||||
}) => void;
|
|
||||||
onError: (error: Error) => void;
|
onError: (error: Error) => void;
|
||||||
rowClassName?: string;
|
rowClassName?: string;
|
||||||
buttonClassName?: 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> {
|
private async onChangePassword(oldPassword: string, newPassword: string): Promise<void> {
|
||||||
const cli = MatrixClientPeg.safeGet();
|
const cli = MatrixClientPeg.safeGet();
|
||||||
|
|
||||||
// if the server supports it then don't sign user out of all devices
|
this.changePassword(cli, oldPassword, newPassword);
|
||||||
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, serverSupportsControlOfDevicesLogout, userHasOtherDevices);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private changePassword(
|
private changePassword(cli: MatrixClient, oldPassword: string, newPassword: string): void {
|
||||||
cli: MatrixClient,
|
|
||||||
oldPassword: string,
|
|
||||||
newPassword: string,
|
|
||||||
serverSupportsControlOfDevicesLogout: boolean,
|
|
||||||
userHasOtherDevices: boolean,
|
|
||||||
): void {
|
|
||||||
const authDict = {
|
const authDict = {
|
||||||
type: "m.login.password",
|
type: "m.login.password",
|
||||||
identifier: {
|
identifier: {
|
||||||
|
@ -163,23 +109,17 @@ export default class ChangePassword extends React.Component<IProps, IState> {
|
||||||
phase: Phase.Uploading,
|
phase: Phase.Uploading,
|
||||||
});
|
});
|
||||||
|
|
||||||
const logoutDevices = serverSupportsControlOfDevicesLogout ? false : undefined;
|
cli.setPassword(authDict, newPassword, false)
|
||||||
|
|
||||||
// undefined or true mean all devices signed out
|
|
||||||
const didLogoutOutOtherDevices = !serverSupportsControlOfDevicesLogout && userHasOtherDevices;
|
|
||||||
|
|
||||||
cli.setPassword(authDict, newPassword, logoutDevices)
|
|
||||||
.then(
|
.then(
|
||||||
() => {
|
() => {
|
||||||
if (this.props.shouldAskForEmail) {
|
if (this.props.shouldAskForEmail) {
|
||||||
return this.optionallySetEmail().then((confirmed) => {
|
return this.optionallySetEmail().then((confirmed) => {
|
||||||
this.props.onFinished({
|
this.props.onFinished({
|
||||||
didSetEmail: confirmed,
|
didSetEmail: confirmed,
|
||||||
didLogoutOutOtherDevices,
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
this.props.onFinished({ didLogoutOutOtherDevices });
|
this.props.onFinished({});
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
(err) => {
|
(err) => {
|
||||||
|
@ -229,17 +169,6 @@ export default class ChangePassword extends React.Component<IProps, IState> {
|
||||||
return modal.finished.then(([confirmed]) => !!confirmed);
|
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 {
|
private markFieldValid(fieldID: FieldType, valid?: boolean): void {
|
||||||
const { fieldValid } = this.state;
|
const { fieldValid } = this.state;
|
||||||
fieldValid[fieldID] = valid;
|
fieldValid[fieldID] = valid;
|
||||||
|
|
|
@ -210,7 +210,7 @@ export default class PhoneNumbers extends React.Component<IProps, IState> {
|
||||||
?.haveMsisdnToken(token)
|
?.haveMsisdnToken(token)
|
||||||
.then(([finished] = []) => {
|
.then(([finished] = []) => {
|
||||||
let newPhoneNumber = this.state.newPhoneNumber;
|
let newPhoneNumber = this.state.newPhoneNumber;
|
||||||
if (finished) {
|
if (finished !== false) {
|
||||||
const msisdns = [...this.props.msisdns, { address, medium: ThreepidMedium.Phone }];
|
const msisdns = [...this.props.msisdns, { address, medium: ThreepidMedium.Phone }];
|
||||||
this.props.onMsisdnsChange(msisdns);
|
this.props.onMsisdnsChange(msisdns);
|
||||||
newPhoneNumber = "";
|
newPhoneNumber = "";
|
||||||
|
|
|
@ -77,10 +77,6 @@ export class EmailAddress extends React.Component<IEmailAddressProps, IEmailAddr
|
||||||
}
|
}
|
||||||
|
|
||||||
private async changeBinding({ bind, label, errorTitle }: Binding): Promise<void> {
|
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;
|
const { medium, address } = this.props.email;
|
||||||
|
|
||||||
try {
|
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 => {
|
private onRevokeClick = (e: ButtonEvent): void => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
|
|
@ -73,10 +73,6 @@ export class PhoneNumber extends React.Component<IPhoneNumberProps, IPhoneNumber
|
||||||
}
|
}
|
||||||
|
|
||||||
private async changeBinding({ bind, label, errorTitle }: Binding): Promise<void> {
|
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;
|
const { medium, address } = this.props.msisdn;
|
||||||
|
|
||||||
try {
|
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 => {
|
private onRevokeClick = (e: ButtonEvent): void => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
|
|
@ -37,7 +37,6 @@ import { Service, ServicePolicyPair, startTermsFlow } from "../../../../../Terms
|
||||||
import IdentityAuthClient from "../../../../../IdentityAuthClient";
|
import IdentityAuthClient from "../../../../../IdentityAuthClient";
|
||||||
import { abbreviateUrl } from "../../../../../utils/UrlUtils";
|
import { abbreviateUrl } from "../../../../../utils/UrlUtils";
|
||||||
import { getThreepidsWithBindStatus } from "../../../../../boundThreepids";
|
import { getThreepidsWithBindStatus } from "../../../../../boundThreepids";
|
||||||
import Spinner from "../../../elements/Spinner";
|
|
||||||
import { SettingLevel } from "../../../../../settings/SettingLevel";
|
import { SettingLevel } from "../../../../../settings/SettingLevel";
|
||||||
import { UIFeature } from "../../../../../settings/UIFeature";
|
import { UIFeature } from "../../../../../settings/UIFeature";
|
||||||
import { ActionPayload } from "../../../../../dispatcher/payloads";
|
import { ActionPayload } from "../../../../../dispatcher/payloads";
|
||||||
|
@ -70,7 +69,6 @@ interface IState {
|
||||||
spellCheckEnabled?: boolean;
|
spellCheckEnabled?: boolean;
|
||||||
spellCheckLanguages: string[];
|
spellCheckLanguages: string[];
|
||||||
haveIdServer: boolean;
|
haveIdServer: boolean;
|
||||||
serverSupportsSeparateAddAndBind?: boolean;
|
|
||||||
idServerHasUnsignedTerms: boolean;
|
idServerHasUnsignedTerms: boolean;
|
||||||
requiredPolicyInfo:
|
requiredPolicyInfo:
|
||||||
| {
|
| {
|
||||||
|
@ -166,8 +164,6 @@ export default class GeneralUserSettingsTab extends React.Component<IProps, ISta
|
||||||
private async getCapabilities(): Promise<void> {
|
private async getCapabilities(): Promise<void> {
|
||||||
const cli = this.context;
|
const cli = this.context;
|
||||||
|
|
||||||
const serverSupportsSeparateAddAndBind = await cli.doesServerSupportSeparateAddAndBind();
|
|
||||||
|
|
||||||
const capabilities = await cli.getCapabilities(); // this is cached
|
const capabilities = await cli.getCapabilities(); // this is cached
|
||||||
const changePasswordCap = capabilities["m.change_password"];
|
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 delegatedAuthConfig = M_AUTHENTICATION.findIn<IDelegatedAuthConfig | undefined>(cli.getClientWellKnown());
|
||||||
const externalAccountManagementUrl = delegatedAuthConfig?.account;
|
const externalAccountManagementUrl = delegatedAuthConfig?.account;
|
||||||
|
|
||||||
this.setState({ serverSupportsSeparateAddAndBind, canChangePassword, externalAccountManagementUrl });
|
this.setState({ canChangePassword, externalAccountManagementUrl });
|
||||||
}
|
}
|
||||||
|
|
||||||
private async getThreepidState(): Promise<void> {
|
private async getThreepidState(): Promise<void> {
|
||||||
|
@ -303,12 +299,8 @@ export default class GeneralUserSettingsTab extends React.Component<IProps, ISta
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
private onPasswordChanged = ({ didLogoutOutOtherDevices }: { didLogoutOutOtherDevices: boolean }): void => {
|
private onPasswordChanged = (): void => {
|
||||||
let description = _t("Your password was successfully changed.");
|
const 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.");
|
|
||||||
}
|
|
||||||
// TODO: Figure out a design that doesn't involve replacing the current dialog
|
// TODO: Figure out a design that doesn't involve replacing the current dialog
|
||||||
Modal.createDialog(ErrorDialog, {
|
Modal.createDialog(ErrorDialog, {
|
||||||
title: _t("Success"),
|
title: _t("Success"),
|
||||||
|
@ -327,15 +319,7 @@ export default class GeneralUserSettingsTab extends React.Component<IProps, ISta
|
||||||
private renderAccountSection(): JSX.Element {
|
private renderAccountSection(): JSX.Element {
|
||||||
let threepidSection: ReactNode = null;
|
let threepidSection: ReactNode = null;
|
||||||
|
|
||||||
// For older homeservers without separate 3PID add and bind methods (MSC2290),
|
if (SettingsStore.getValue(UIFeature.ThirdPartyID)) {
|
||||||
// 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)
|
|
||||||
) {
|
|
||||||
const emails = this.state.loading3pids ? (
|
const emails = this.state.loading3pids ? (
|
||||||
<InlineSpinner />
|
<InlineSpinner />
|
||||||
) : (
|
) : (
|
||||||
|
@ -365,8 +349,6 @@ export default class GeneralUserSettingsTab extends React.Component<IProps, ISta
|
||||||
</SettingsSubsection>
|
</SettingsSubsection>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
} else if (this.state.serverSupportsSeparateAddAndBind === null) {
|
|
||||||
threepidSection = <Spinner />;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let passwordChangeSection: ReactNode = null;
|
let passwordChangeSection: ReactNode = null;
|
||||||
|
|
|
@ -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 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",
|
"We couldn't log you in": "We couldn't log you in",
|
||||||
"Try again": "Try again",
|
"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",
|
"User is not logged in": "User is not logged in",
|
||||||
"Database unexpectedly closed": "Database unexpectedly closed",
|
"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.",
|
"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",
|
"No homeserver URL provided": "No homeserver URL provided",
|
||||||
"Unexpected error resolving homeserver configuration": "Unexpected error resolving homeserver configuration",
|
"Unexpected error resolving homeserver configuration": "Unexpected error resolving homeserver configuration",
|
||||||
"Unexpected error resolving identity server configuration": "Unexpected error resolving identity server 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 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 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.",
|
"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/>",
|
"Workspace: <networkLink/>": "Workspace: <networkLink/>",
|
||||||
"Channel: <channelLink/>": "Channel: <channelLink/>",
|
"Channel: <channelLink/>": "Channel: <channelLink/>",
|
||||||
"No display name": "No display name",
|
"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",
|
"Error while changing password: %(error)s": "Error while changing password: %(error)s",
|
||||||
"New passwords don't match": "New passwords don't match",
|
"New passwords don't match": "New passwords don't match",
|
||||||
"Passwords can't be empty": "Passwords can't be empty",
|
"Passwords can't be empty": "Passwords can't be empty",
|
||||||
|
@ -1388,6 +1386,7 @@
|
||||||
"Homeserver feature support:": "Homeserver feature support:",
|
"Homeserver feature support:": "Homeserver feature support:",
|
||||||
"exists": "exists",
|
"exists": "exists",
|
||||||
"<not supported>": "<not supported>",
|
"<not supported>": "<not supported>",
|
||||||
|
"Export E2E room keys": "Export E2E room keys",
|
||||||
"Import E2E room keys": "Import E2E room keys",
|
"Import E2E room keys": "Import E2E room keys",
|
||||||
"Cryptography": "Cryptography",
|
"Cryptography": "Cryptography",
|
||||||
"Session ID:": "Session ID:",
|
"Session ID:": "Session ID:",
|
||||||
|
@ -1545,7 +1544,6 @@
|
||||||
"%(errorMessage)s (HTTP status %(httpStatus)s)": "%(errorMessage)s (HTTP status %(httpStatus)s)",
|
"%(errorMessage)s (HTTP status %(httpStatus)s)": "%(errorMessage)s (HTTP status %(httpStatus)s)",
|
||||||
"Error changing password": "Error changing password",
|
"Error changing password": "Error changing password",
|
||||||
"Your password was successfully changed.": "Your password was successfully changed.",
|
"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",
|
"Success": "Success",
|
||||||
"Email addresses": "Email addresses",
|
"Email addresses": "Email addresses",
|
||||||
"Phone numbers": "Phone numbers",
|
"Phone numbers": "Phone numbers",
|
||||||
|
@ -2315,6 +2313,7 @@
|
||||||
"Failed to mute user": "Failed to mute user",
|
"Failed to mute user": "Failed to mute user",
|
||||||
"Unmute": "Unmute",
|
"Unmute": "Unmute",
|
||||||
"Mute": "Mute",
|
"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.",
|
"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?",
|
"Are you sure?": "Are you sure?",
|
||||||
"Deactivate user?": "Deactivate user?",
|
"Deactivate user?": "Deactivate user?",
|
||||||
|
@ -3561,7 +3560,6 @@
|
||||||
"Skip verification for now": "Skip verification for now",
|
"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. 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.",
|
"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.",
|
"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.",
|
"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",
|
"Reset password": "Reset password",
|
||||||
|
|
|
@ -236,6 +236,11 @@ export default class AutoDiscoveryUtils {
|
||||||
if (AutoDiscovery.ALL_ERRORS.indexOf(hsResult.error as string) !== -1) {
|
if (AutoDiscovery.ALL_ERRORS.indexOf(hsResult.error as string) !== -1) {
|
||||||
throw new UserFriendlyError(String(hsResult.error));
|
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");
|
throw new UserFriendlyError("Unexpected error resolving homeserver configuration");
|
||||||
} // else the error is not related to syntax - continue anyways.
|
} // else the error is not related to syntax - continue anyways.
|
||||||
}
|
}
|
||||||
|
|
|
@ -26,6 +26,7 @@ import { MatrixClientPeg } from "../src/MatrixClientPeg";
|
||||||
import Modal from "../src/Modal";
|
import Modal from "../src/Modal";
|
||||||
import * as StorageManager from "../src/utils/StorageManager";
|
import * as StorageManager from "../src/utils/StorageManager";
|
||||||
import { getMockClientWithEventEmitter, mockPlatformPeg } from "./test-utils";
|
import { getMockClientWithEventEmitter, mockPlatformPeg } from "./test-utils";
|
||||||
|
import ToastStore from "../src/stores/ToastStore";
|
||||||
|
|
||||||
const webCrypto = new Crypto();
|
const webCrypto = new Crypto();
|
||||||
|
|
||||||
|
@ -50,6 +51,7 @@ describe("Lifecycle", () => {
|
||||||
store: {
|
store: {
|
||||||
destroy: jest.fn(),
|
destroy: jest.fn(),
|
||||||
},
|
},
|
||||||
|
getVersions: jest.fn().mockResolvedValue({ versions: ["v1.1"] }),
|
||||||
});
|
});
|
||||||
|
|
||||||
beforeEach(() => {
|
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",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
|
@ -59,6 +59,7 @@ describe("<MatrixChat />", () => {
|
||||||
// reused in createClient mock below
|
// reused in createClient mock below
|
||||||
const getMockClientMethods = () => ({
|
const getMockClientMethods = () => ({
|
||||||
...mockClientMethodsUser(userId),
|
...mockClientMethodsUser(userId),
|
||||||
|
getVersions: jest.fn().mockResolvedValue({ versions: ["v1.1"] }),
|
||||||
startClient: jest.fn(),
|
startClient: jest.fn(),
|
||||||
stopClient: jest.fn(),
|
stopClient: jest.fn(),
|
||||||
setCanResetTimelineCallback: jest.fn(),
|
setCanResetTimelineCallback: jest.fn(),
|
||||||
|
@ -178,7 +179,7 @@ describe("<MatrixChat />", () => {
|
||||||
mockClient = getMockClientWithEventEmitter(getMockClientMethods());
|
mockClient = getMockClientWithEventEmitter(getMockClientMethods());
|
||||||
fetchMock.get("https://test.com/_matrix/client/versions", {
|
fetchMock.get("https://test.com/_matrix/client/versions", {
|
||||||
unstable_features: {},
|
unstable_features: {},
|
||||||
versions: [],
|
versions: ["v1.1"],
|
||||||
});
|
});
|
||||||
localStorageSetSpy = jest.spyOn(localStorage.__proto__, "setItem");
|
localStorageSetSpy = jest.spyOn(localStorage.__proto__, "setItem");
|
||||||
localStorageGetSpy = jest.spyOn(localStorage.__proto__, "getItem").mockReturnValue(undefined);
|
localStorageGetSpy = jest.spyOn(localStorage.__proto__, "getItem").mockReturnValue(undefined);
|
||||||
|
|
|
@ -71,7 +71,7 @@ describe("Login", function () {
|
||||||
fetchMock.resetHistory();
|
fetchMock.resetHistory();
|
||||||
fetchMock.get("https://matrix.org/_matrix/client/versions", {
|
fetchMock.get("https://matrix.org/_matrix/client/versions", {
|
||||||
unstable_features: {},
|
unstable_features: {},
|
||||||
versions: [],
|
versions: ["v1.1"],
|
||||||
});
|
});
|
||||||
platform = mockPlatformPeg({
|
platform = mockPlatformPeg({
|
||||||
startSingleSignOn: jest.fn(),
|
startSingleSignOn: jest.fn(),
|
||||||
|
@ -209,7 +209,7 @@ describe("Login", function () {
|
||||||
|
|
||||||
fetchMock.get("https://server2/_matrix/client/versions", {
|
fetchMock.get("https://server2/_matrix/client/versions", {
|
||||||
unstable_features: {},
|
unstable_features: {},
|
||||||
versions: [],
|
versions: ["v1.1"],
|
||||||
});
|
});
|
||||||
rerender(getRawComponent("https://server2"));
|
rerender(getRawComponent("https://server2"));
|
||||||
await waitForElementToBeRemoved(() => screen.queryAllByLabelText("Loading…"));
|
await waitForElementToBeRemoved(() => screen.queryAllByLabelText("Loading…"));
|
||||||
|
@ -359,7 +359,7 @@ describe("Login", function () {
|
||||||
// but server2 is
|
// but server2 is
|
||||||
fetchMock.get("https://server2/_matrix/client/versions", {
|
fetchMock.get("https://server2/_matrix/client/versions", {
|
||||||
unstable_features: {},
|
unstable_features: {},
|
||||||
versions: [],
|
versions: ["v1.1"],
|
||||||
});
|
});
|
||||||
const { rerender } = render(getRawComponent());
|
const { rerender } = render(getRawComponent());
|
||||||
await waitForElementToBeRemoved(() => screen.queryAllByLabelText("Loading…"));
|
await waitForElementToBeRemoved(() => screen.queryAllByLabelText("Loading…"));
|
||||||
|
|
|
@ -36,6 +36,7 @@ describe("Registration", function () {
|
||||||
const mockClient = mocked({
|
const mockClient = mocked({
|
||||||
registerRequest,
|
registerRequest,
|
||||||
loginFlows: jest.fn(),
|
loginFlows: jest.fn(),
|
||||||
|
getVersions: jest.fn().mockResolvedValue({ versions: ["v1.1"] }),
|
||||||
} as unknown as MatrixClient);
|
} as unknown as MatrixClient);
|
||||||
|
|
||||||
beforeEach(function () {
|
beforeEach(function () {
|
||||||
|
@ -59,7 +60,7 @@ describe("Registration", function () {
|
||||||
});
|
});
|
||||||
fetchMock.get("https://matrix.org/_matrix/client/versions", {
|
fetchMock.get("https://matrix.org/_matrix/client/versions", {
|
||||||
unstable_features: {},
|
unstable_features: {},
|
||||||
versions: [],
|
versions: ["v1.1"],
|
||||||
});
|
});
|
||||||
mockPlatformPeg({
|
mockPlatformPeg({
|
||||||
startSingleSignOn: jest.fn(),
|
startSingleSignOn: jest.fn(),
|
||||||
|
@ -125,7 +126,7 @@ describe("Registration", function () {
|
||||||
|
|
||||||
fetchMock.get("https://server2/_matrix/client/versions", {
|
fetchMock.get("https://server2/_matrix/client/versions", {
|
||||||
unstable_features: {},
|
unstable_features: {},
|
||||||
versions: [],
|
versions: ["v1.1"],
|
||||||
});
|
});
|
||||||
rerender(getRawComponent("https://server2"));
|
rerender(getRawComponent("https://server2"));
|
||||||
await waitForElementToBeRemoved(() => screen.queryAllByLabelText("Loading…"));
|
await waitForElementToBeRemoved(() => screen.queryAllByLabelText("Loading…"));
|
||||||
|
|
|
@ -112,7 +112,7 @@ describe("<ServerPickerDialog />", () => {
|
||||||
it("should allow user to revert from a custom server to the default", async () => {
|
it("should allow user to revert from a custom server to the default", async () => {
|
||||||
fetchMock.get(`https://custom.org/_matrix/client/versions`, {
|
fetchMock.get(`https://custom.org/_matrix/client/versions`, {
|
||||||
unstable_features: {},
|
unstable_features: {},
|
||||||
versions: [],
|
versions: ["v1.1"],
|
||||||
});
|
});
|
||||||
|
|
||||||
const onFinished = jest.fn();
|
const onFinished = jest.fn();
|
||||||
|
@ -142,7 +142,7 @@ describe("<ServerPickerDialog />", () => {
|
||||||
const homeserver = "https://myhomeserver.site";
|
const homeserver = "https://myhomeserver.site";
|
||||||
fetchMock.get(`${homeserver}/_matrix/client/versions`, {
|
fetchMock.get(`${homeserver}/_matrix/client/versions`, {
|
||||||
unstable_features: {},
|
unstable_features: {},
|
||||||
versions: [],
|
versions: ["v1.1"],
|
||||||
});
|
});
|
||||||
const onFinished = jest.fn();
|
const onFinished = jest.fn();
|
||||||
getComponent({ onFinished });
|
getComponent({ onFinished });
|
||||||
|
@ -195,7 +195,7 @@ describe("<ServerPickerDialog />", () => {
|
||||||
|
|
||||||
fetchMock.getOnce(wellKnownUrl, validWellKnown);
|
fetchMock.getOnce(wellKnownUrl, validWellKnown);
|
||||||
fetchMock.getOnce(versionsUrl, {
|
fetchMock.getOnce(versionsUrl, {
|
||||||
versions: [],
|
versions: ["v1.1"],
|
||||||
});
|
});
|
||||||
fetchMock.getOnce(isWellKnownUrl, {});
|
fetchMock.getOnce(isWellKnownUrl, {});
|
||||||
const onFinished = jest.fn();
|
const onFinished = jest.fn();
|
||||||
|
@ -231,7 +231,7 @@ describe("<ServerPickerDialog />", () => {
|
||||||
const wellKnownUrl = `https://${homeserver}/.well-known/matrix/client`;
|
const wellKnownUrl = `https://${homeserver}/.well-known/matrix/client`;
|
||||||
fetchMock.get(wellKnownUrl, { status: 404 });
|
fetchMock.get(wellKnownUrl, { status: 404 });
|
||||||
// but is otherwise live (happy versions response)
|
// 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();
|
const onFinished = jest.fn();
|
||||||
getComponent({ onFinished });
|
getComponent({ onFinished });
|
||||||
|
|
||||||
|
|
|
@ -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
|
// eslint-disable-next-line no-restricted-properties
|
||||||
cli.mxcUrlToHttp.mockImplementation(
|
cli.mxcUrlToHttp.mockImplementation(
|
||||||
(mxcUrl: string, width?: number, height?: number, resizeMethod?: string, allowDirectLinks?: boolean) => {
|
(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 () => {
|
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 thumbUrl = "https://server/_matrix/media/v3/thumbnail/server/image?width=800&height=600&method=scale";
|
||||||
const downloadUrl = "https://server/_matrix/media/r0/download/server/image";
|
const downloadUrl = "https://server/_matrix/media/v3/download/server/image";
|
||||||
|
|
||||||
const event = new MatrixEvent({
|
const event = new MatrixEvent({
|
||||||
room_id: "!room:server",
|
room_id: "!room:server",
|
||||||
|
@ -227,7 +227,7 @@ describe("<MImageBody/>", () => {
|
||||||
mocked(global.URL.createObjectURL).mockReturnValue("blob:generated-thumb");
|
mocked(global.URL.createObjectURL).mockReturnValue("blob:generated-thumb");
|
||||||
|
|
||||||
fetchMock.getOnce(
|
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")),
|
body: fs.readFileSync(path.resolve(__dirname, "..", "..", "..", "images", "animated-logo.webp")),
|
||||||
},
|
},
|
||||||
|
|
|
@ -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 });
|
fetchMock.getOnce(thumbUrl, { status: 200 });
|
||||||
|
|
||||||
// eslint-disable-next-line no-restricted-properties
|
// eslint-disable-next-line no-restricted-properties
|
||||||
|
|
|
@ -6,7 +6,7 @@ exports[`<MImageBody/> should generate a thumbnail if one isn't included for ani
|
||||||
class="mx_MImageBody"
|
class="mx_MImageBody"
|
||||||
>
|
>
|
||||||
<a
|
<a
|
||||||
href="https://server/_matrix/media/r0/download/server/image"
|
href="https://server/_matrix/media/v3/download/server/image"
|
||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
class="mx_MImageBody_thumbnail_container"
|
class="mx_MImageBody_thumbnail_container"
|
||||||
|
|
|
@ -37,7 +37,7 @@ exports[`MVideoBody should show poster for encrypted media before downloading it
|
||||||
class="mx_MVideoBody"
|
class="mx_MVideoBody"
|
||||||
controls=""
|
controls=""
|
||||||
controlslist="nodownload"
|
controlslist="nodownload"
|
||||||
poster="https://server/_matrix/media/r0/download/server/encrypted-poster"
|
poster="https://server/_matrix/media/v3/download/server/encrypted-poster"
|
||||||
preload="none"
|
preload="none"
|
||||||
title="alt for a test video"
|
title="alt for a test video"
|
||||||
/>
|
/>
|
||||||
|
|
86
test/components/views/settings/ChangePassword-test.tsx
Normal file
86
test/components/views/settings/ChangePassword-test.tsx
Normal 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();
|
||||||
|
});
|
||||||
|
});
|
|
@ -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>
|
||||||
|
`;
|
67
test/components/views/settings/account/PhoneNumbers-test.tsx
Normal file
67
test/components/views/settings/account/PhoneNumbers-test.tsx
Normal 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" }]);
|
||||||
|
});
|
||||||
|
});
|
|
@ -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>
|
||||||
|
`;
|
|
@ -42,7 +42,6 @@ describe("<EmailAddress/>", () => {
|
||||||
const mockClient = getMockClientWithEventEmitter({
|
const mockClient = getMockClientWithEventEmitter({
|
||||||
getIdentityServerUrl: jest.fn().mockReturnValue("https://fake-identity-server"),
|
getIdentityServerUrl: jest.fn().mockReturnValue("https://fake-identity-server"),
|
||||||
generateClientSecret: jest.fn(),
|
generateClientSecret: jest.fn(),
|
||||||
doesServerSupportSeparateAddAndBind: jest.fn(),
|
|
||||||
requestEmailToken: jest.fn(),
|
requestEmailToken: jest.fn(),
|
||||||
bindThreePid: jest.fn(),
|
bindThreePid: jest.fn(),
|
||||||
});
|
});
|
||||||
|
@ -74,7 +73,6 @@ describe("<EmailAddress/>", () => {
|
||||||
describe("Email verification share phase", () => {
|
describe("Email verification share phase", () => {
|
||||||
it("shows translated error message", async () => {
|
it("shows translated error message", async () => {
|
||||||
render(<EmailAddress email={emailThreepidFixture} />);
|
render(<EmailAddress email={emailThreepidFixture} />);
|
||||||
mockClient.doesServerSupportSeparateAddAndBind.mockResolvedValue(true);
|
|
||||||
mockClient.requestEmailToken.mockRejectedValue(
|
mockClient.requestEmailToken.mockRejectedValue(
|
||||||
new MatrixError(
|
new MatrixError(
|
||||||
{ errcode: "M_THREEPID_IN_USE", error: "Some fake MatrixError occured" },
|
{ errcode: "M_THREEPID_IN_USE", error: "Some fake MatrixError occured" },
|
||||||
|
@ -94,7 +92,6 @@ describe("<EmailAddress/>", () => {
|
||||||
// Start these tests out at the "Complete" phase
|
// Start these tests out at the "Complete" phase
|
||||||
render(<EmailAddress email={emailThreepidFixture} />);
|
render(<EmailAddress email={emailThreepidFixture} />);
|
||||||
mockClient.requestEmailToken.mockResolvedValue({ sid: "123-fake-sid" } satisfies IRequestTokenResponse);
|
mockClient.requestEmailToken.mockResolvedValue({ sid: "123-fake-sid" } satisfies IRequestTokenResponse);
|
||||||
mockClient.doesServerSupportSeparateAddAndBind.mockResolvedValue(true);
|
|
||||||
fireEvent.click(screen.getByText("Share"));
|
fireEvent.click(screen.getByText("Share"));
|
||||||
// Then wait for the completion screen to come up
|
// Then wait for the completion screen to come up
|
||||||
await screen.findByText("Complete");
|
await screen.findByText("Complete");
|
||||||
|
|
|
@ -15,38 +15,47 @@ limitations under the License.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import React from "react";
|
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 { 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 PhoneNumbers, { PhoneNumber } from "../../../../../src/components/views/settings/discovery/PhoneNumbers";
|
||||||
|
import { stubClient } from "../../../../test-utils";
|
||||||
|
|
||||||
const msisdn: IThreepid = {
|
const msisdn: IThreepid = {
|
||||||
medium: ThreepidMedium.Phone,
|
medium: ThreepidMedium.Phone,
|
||||||
address: "+441111111111",
|
address: "441111111111",
|
||||||
validated_at: 12345,
|
validated_at: 12345,
|
||||||
added_at: 12342,
|
added_at: 12342,
|
||||||
bound: false,
|
bound: false,
|
||||||
};
|
};
|
||||||
describe("<PhoneNumber/>", () => {
|
describe("<PhoneNumber/>", () => {
|
||||||
it("should track props.msisdn.bound changes", async () => {
|
it("should track props.msisdn.bound changes", async () => {
|
||||||
const { rerender } = render(<PhoneNumber msisdn={msisdn} />);
|
const { rerender } = render(<PhoneNumber msisdn={{ ...msisdn }} />);
|
||||||
await screen.findByText("Share");
|
await screen.findByText("Share");
|
||||||
|
|
||||||
msisdn.bound = true;
|
rerender(<PhoneNumber msisdn={{ ...msisdn, bound: true }} />);
|
||||||
rerender(<PhoneNumber msisdn={{ ...msisdn }} />);
|
|
||||||
await screen.findByText("Revoke");
|
await screen.findByText("Revoke");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const mockGetAccessToken = jest.fn().mockResolvedValue("$$getAccessToken");
|
||||||
|
jest.mock("../../../../../src/IdentityAuthClient", () =>
|
||||||
|
jest.fn().mockImplementation(() => ({
|
||||||
|
getAccessToken: mockGetAccessToken,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
|
||||||
describe("<PhoneNumbers />", () => {
|
describe("<PhoneNumbers />", () => {
|
||||||
it("should render a loader while loading", async () => {
|
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();
|
expect(container).toMatchSnapshot();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should render phone numbers", async () => {
|
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();
|
expect(container).toMatchSnapshot();
|
||||||
});
|
});
|
||||||
|
@ -56,4 +65,37 @@ describe("<PhoneNumbers />", () => {
|
||||||
|
|
||||||
expect(container).toMatchSnapshot();
|
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");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
|
@ -1,5 +1,67 @@
|
||||||
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
// 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`] = `
|
exports[`<PhoneNumbers /> should handle no numbers 1`] = `
|
||||||
<div>
|
<div>
|
||||||
<div
|
<div
|
||||||
|
@ -85,14 +147,14 @@ exports[`<PhoneNumbers /> should render phone numbers 1`] = `
|
||||||
class="mx_GeneralUserSettingsTab_section--discovery_existing_address"
|
class="mx_GeneralUserSettingsTab_section--discovery_existing_address"
|
||||||
>
|
>
|
||||||
+
|
+
|
||||||
+441111111111
|
441111111111
|
||||||
</span>
|
</span>
|
||||||
<div
|
<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"
|
role="button"
|
||||||
tabindex="0"
|
tabindex="0"
|
||||||
>
|
>
|
||||||
Revoke
|
Share
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
@ -126,7 +126,6 @@ export const mockClientMethodsEvents = () => ({
|
||||||
* Returns basic mocked client methods related to server support
|
* Returns basic mocked client methods related to server support
|
||||||
*/
|
*/
|
||||||
export const mockClientMethodsServer = (): Partial<Record<MethodLikeKeys<MatrixClient>, unknown>> => ({
|
export const mockClientMethodsServer = (): Partial<Record<MethodLikeKeys<MatrixClient>, unknown>> => ({
|
||||||
doesServerSupportSeparateAddAndBind: jest.fn(),
|
|
||||||
getIdentityServerUrl: jest.fn(),
|
getIdentityServerUrl: jest.fn(),
|
||||||
getHomeserverUrl: jest.fn(),
|
getHomeserverUrl: jest.fn(),
|
||||||
getCapabilities: jest.fn().mockReturnValue({}),
|
getCapabilities: jest.fn().mockReturnValue({}),
|
||||||
|
|
|
@ -217,7 +217,6 @@ export function createTestClient(): MatrixClient {
|
||||||
uploadContent: jest.fn(),
|
uploadContent: jest.fn(),
|
||||||
getEventMapper: (_options?: MapperOpts) => (event: Partial<IEvent>) => new MatrixEvent(event),
|
getEventMapper: (_options?: MapperOpts) => (event: Partial<IEvent>) => new MatrixEvent(event),
|
||||||
leaveRoomChain: jest.fn((roomId) => ({ [roomId]: null })),
|
leaveRoomChain: jest.fn((roomId) => ({ [roomId]: null })),
|
||||||
doesServerSupportLogoutDevices: jest.fn().mockReturnValue(true),
|
|
||||||
requestPasswordEmailToken: jest.fn().mockRejectedValue({}),
|
requestPasswordEmailToken: jest.fn().mockRejectedValue({}),
|
||||||
setPassword: jest.fn().mockRejectedValue({}),
|
setPassword: jest.fn().mockRejectedValue({}),
|
||||||
groupCallEventHandler: { groupCalls: new Map<string, GroupCall>() },
|
groupCallEventHandler: { groupCalls: new Map<string, GroupCall>() },
|
||||||
|
@ -244,6 +243,12 @@ export function createTestClient(): MatrixClient {
|
||||||
exportRoomKeys: jest.fn(),
|
exportRoomKeys: jest.fn(),
|
||||||
knockRoom: jest.fn(),
|
knockRoom: jest.fn(),
|
||||||
leave: 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;
|
} as unknown as MatrixClient;
|
||||||
|
|
||||||
client.reEmitter = new ReEmitter(client);
|
client.reEmitter = new ReEmitter(client);
|
||||||
|
|
|
@ -232,5 +232,22 @@ describe("AutoDiscoveryUtils", () => {
|
||||||
warning: undefined,
|
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.",
|
||||||
|
);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue