Skip to content
This repository has been archived by the owner on Sep 11, 2024. It is now read-only.

Commit

Permalink
Merge pull request #3462 from matrix-org/jryans/msc2290
Browse files Browse the repository at this point in the history
Use separate 3PID add and bind flow for supporting HSes
  • Loading branch information
jryans authored Sep 20, 2019
2 parents 46e0a7c + f9a09d2 commit 351a3eb
Show file tree
Hide file tree
Showing 7 changed files with 229 additions and 46 deletions.
148 changes: 126 additions & 22 deletions src/AddThreepid.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/*
Copyright 2016 OpenMarket Ltd
Copyright 2017 Vector Creations Ltd
Copyright 2019 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.
Expand All @@ -26,21 +27,23 @@ import IdentityAuthClient from './IdentityAuthClient';
* This involves getting an email token from the identity server to "prove" that
* the client owns the given email address, which is then passed to the
* add threepid API on the homeserver.
*
* Diagrams of the intended API flows here are available at:
*
* https://gist.github.com/jryans/839a09bf0c5a70e2f36ed990d50ed928
*/
export default class AddThreepid {
constructor() {
this.clientSecret = MatrixClientPeg.get().generateClientSecret();
}

/**
* Attempt to add an email threepid. This will trigger a side-effect of
* sending an email to the provided email address.
* Attempt to add an email threepid to the homeserver.
* This will trigger a side-effect of sending an email to the provided email address.
* @param {string} emailAddress The email address to add
* @param {boolean} bind If True, bind this email to this mxid on the Identity Server
* @return {Promise} Resolves when the email has been sent. Then call checkEmailLinkClicked().
*/
addEmailAddress(emailAddress, bind) {
this.bind = bind;
addEmailAddress(emailAddress) {
return MatrixClientPeg.get().requestAdd3pidEmailToken(emailAddress, this.clientSecret, 1).then((res) => {
this.sessionId = res.sid;
return res;
Expand All @@ -55,15 +58,45 @@ export default class AddThreepid {
}

/**
* Attempt to add a msisdn threepid. This will trigger a side-effect of
* sending a test message to the provided phone number.
* Attempt to bind an email threepid on the identity server via the homeserver.
* This will trigger a side-effect of sending an email to the provided email address.
* @param {string} emailAddress The email address to add
* @return {Promise} Resolves when the email has been sent. Then call checkEmailLinkClicked().
*/
async bindEmailAddress(emailAddress) {
this.bind = true;
if (await MatrixClientPeg.get().doesServerSupportSeparateAddAndBind()) {
// For separate bind, request a token directly from the IS.
const authClient = new IdentityAuthClient();
const identityAccessToken = await authClient.getAccessToken();
return MatrixClientPeg.get().requestEmailToken(
emailAddress, this.clientSecret, 1,
undefined, undefined, identityAccessToken,
).then((res) => {
this.sessionId = res.sid;
return res;
}, function(err) {
if (err.errcode === 'M_THREEPID_IN_USE') {
err.message = _t('This email address is already in use');
} else if (err.httpStatus) {
err.message = err.message + ` (Status ${err.httpStatus})`;
}
throw err;
});
} else {
// For tangled bind, request a token via the HS.
return this.addEmailAddress(emailAddress);
}
}

/**
* Attempt to add a MSISDN threepid to the homeserver.
* This will trigger a side-effect of sending an SMS to the provided phone number.
* @param {string} phoneCountry The ISO 2 letter code of the country to resolve phoneNumber in
* @param {string} phoneNumber The national or international formatted phone number to add
* @param {boolean} bind If True, bind this phone number to this mxid on the Identity Server
* @return {Promise} Resolves when the text message has been sent. Then call haveMsisdnToken().
*/
addMsisdn(phoneCountry, phoneNumber, bind) {
this.bind = bind;
addMsisdn(phoneCountry, phoneNumber) {
return MatrixClientPeg.get().requestAdd3pidMsisdnToken(
phoneCountry, phoneNumber, this.clientSecret, 1,
).then((res) => {
Expand All @@ -79,26 +112,79 @@ export default class AddThreepid {
});
}

/**
* Attempt to bind a MSISDN threepid on the identity server via the homeserver.
* This will trigger a side-effect of sending an SMS to the provided phone number.
* @param {string} phoneCountry The ISO 2 letter code of the country to resolve phoneNumber in
* @param {string} phoneNumber The national or international formatted phone number to add
* @return {Promise} Resolves when the text message has been sent. Then call haveMsisdnToken().
*/
async bindMsisdn(phoneCountry, phoneNumber) {
this.bind = true;
if (await MatrixClientPeg.get().doesServerSupportSeparateAddAndBind()) {
// For separate bind, request a token directly from the IS.
const authClient = new IdentityAuthClient();
const identityAccessToken = await authClient.getAccessToken();
return MatrixClientPeg.get().requestMsisdnToken(
phoneCountry, phoneNumber, this.clientSecret, 1,
undefined, undefined, identityAccessToken,
).then((res) => {
this.sessionId = res.sid;
return res;
}, function(err) {
if (err.errcode === 'M_THREEPID_IN_USE') {
err.message = _t('This phone number is already in use');
} else if (err.httpStatus) {
err.message = err.message + ` (Status ${err.httpStatus})`;
}
throw err;
});
} else {
// For tangled bind, request a token via the HS.
return this.addMsisdn(phoneCountry, phoneNumber);
}
}

/**
* Checks if the email link has been clicked by attempting to add the threepid
* @return {Promise} Resolves if the email address was added. Rejects with an object
* with a "message" property which contains a human-readable message detailing why
* the request failed.
*/
checkEmailLinkClicked() {
async checkEmailLinkClicked() {
const identityServerDomain = MatrixClientPeg.get().idBaseUrl.split("://")[1];
return MatrixClientPeg.get().addThreePid({
sid: this.sessionId,
client_secret: this.clientSecret,
id_server: identityServerDomain,
}, this.bind).catch(function(err) {
try {
if (await MatrixClientPeg.get().doesServerSupportSeparateAddAndBind()) {
if (this.bind) {
const authClient = new IdentityAuthClient();
const identityAccessToken = await authClient.getAccessToken();
await MatrixClientPeg.get().bindThreePid({
sid: this.sessionId,
client_secret: this.clientSecret,
id_server: identityServerDomain,
id_access_token: identityAccessToken,
});
} else {
await MatrixClientPeg.get().addThreePidOnly({
sid: this.sessionId,
client_secret: this.clientSecret,
});
}
} else {
await MatrixClientPeg.get().addThreePid({
sid: this.sessionId,
client_secret: this.clientSecret,
id_server: identityServerDomain,
}, this.bind);
}
} catch (err) {
if (err.httpStatus === 401) {
err.message = _t('Failed to verify email address: make sure you clicked the link in the email');
} else if (err.httpStatus) {
err.message += ` (Status ${err.httpStatus})`;
}
throw err;
});
}
}

/**
Expand All @@ -123,10 +209,28 @@ export default class AddThreepid {
}

const identityServerDomain = MatrixClientPeg.get().idBaseUrl.split("://")[1];
return MatrixClientPeg.get().addThreePid({
sid: this.sessionId,
client_secret: this.clientSecret,
id_server: identityServerDomain,
}, this.bind);
if (await MatrixClientPeg.get().doesServerSupportSeparateAddAndBind()) {
if (this.bind) {
const authClient = new IdentityAuthClient();
const identityAccessToken = await authClient.getAccessToken();
await MatrixClientPeg.get().bindThreePid({
sid: this.sessionId,
client_secret: this.clientSecret,
id_server: identityServerDomain,
id_access_token: identityAccessToken,
});
} else {
await MatrixClientPeg.get().addThreePidOnly({
sid: this.sessionId,
client_secret: this.clientSecret,
});
}
} else {
await MatrixClientPeg.get().addThreePid({
sid: this.sessionId,
client_secret: this.clientSecret,
id_server: identityServerDomain,
}, this.bind);
}
}
}
4 changes: 1 addition & 3 deletions src/components/views/dialogs/SetEmailDialog.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,7 @@ export default createReactClass({
return;
}
this._addThreepid = new AddThreepid();
// we always bind emails when registering, so let's do the
// same here.
this._addThreepid.addEmailAddress(emailAddress, true).done(() => {
this._addThreepid.addEmailAddress(emailAddress).done(() => {
Modal.createTrackedDialog('Verification Pending', '', QuestionDialog, {
title: _t("Verification Pending"),
description: _t(
Expand Down
2 changes: 1 addition & 1 deletion src/components/views/settings/account/EmailAddresses.js
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ export default class EmailAddresses extends React.Component {
const task = new AddThreepid();
this.setState({verifying: true, continueDisabled: true, addTask: task});

task.addEmailAddress(email, false).then(() => {
task.addEmailAddress(email).then(() => {
this.setState({continueDisabled: false});
}).catch((err) => {
console.error("Unable to add email address " + email + " " + err);
Expand Down
2 changes: 1 addition & 1 deletion src/components/views/settings/account/PhoneNumbers.js
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ export default class PhoneNumbers extends React.Component {
const task = new AddThreepid();
this.setState({verifying: true, continueDisabled: true, addTask: task});

task.addMsisdn(phoneCountry, phoneNumber, false).then((response) => {
task.addMsisdn(phoneCountry, phoneNumber).then((response) => {
this.setState({continueDisabled: false, verifyMsisdn: response.msisdn});
}).catch((err) => {
console.error("Unable to add phone number " + phoneNumber + " " + err);
Expand Down
50 changes: 43 additions & 7 deletions src/components/views/settings/discovery/EmailAddresses.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,44 @@ export class EmailAddress extends React.Component {
}

async changeBinding({ bind, label, errorTitle }) {
if (!await MatrixClientPeg.get().doesServerSupportSeparateAddAndBind()) {
return this.changeBindingTangledAddBind({ bind, label, errorTitle });
}

const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog");
const { medium, address } = this.props.email;

try {
if (bind) {
const task = new AddThreepid();
this.setState({
verifying: true,
continueDisabled: true,
addTask: task,
});
await task.bindEmailAddress(address);
this.setState({
continueDisabled: false,
});
} else {
await MatrixClientPeg.get().unbindThreePid(medium, address);
}
this.setState({ bound: bind });
} catch (err) {
console.error(`Unable to ${label} email address ${address} ${err}`);
this.setState({
verifying: false,
continueDisabled: false,
addTask: null,
});
Modal.createTrackedDialog(`Unable to ${label} email address`, '', ErrorDialog, {
title: errorTitle,
description: ((err && err.message) ? err.message : _t("Operation failed")),
});
}
}

async changeBindingTangledAddBind({ bind, label, errorTitle }) {
const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog");
const { medium, address } = this.props.email;

Expand All @@ -75,14 +113,12 @@ export class EmailAddress extends React.Component {
});

try {
// XXX: Unfortunately, at the moment we can't just bind via the HS
// in a single operation, at it will error saying the 3PID is in use
// even though it's in use by the current user. For the moment, we
// work around this by removing the 3PID from the HS and re-adding
// it with IS binding enabled.
// See https://github.com/matrix-org/matrix-doc/pull/2140/files#r311462052
await MatrixClientPeg.get().deleteThreePid(medium, address);
await task.addEmailAddress(address, bind);
if (bind) {
await task.bindEmailAddress(address);
} else {
await task.addEmailAddress(address);
}
this.setState({
continueDisabled: false,
bound: bind,
Expand Down
54 changes: 47 additions & 7 deletions src/components/views/settings/discovery/PhoneNumbers.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,48 @@ export class PhoneNumber extends React.Component {
}

async changeBinding({ bind, label, errorTitle }) {
if (!await MatrixClientPeg.get().doesServerSupportSeparateAddAndBind()) {
return this.changeBindingTangledAddBind({ bind, label, errorTitle });
}

const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog");
const { medium, address } = this.props.msisdn;

try {
if (bind) {
const task = new AddThreepid();
this.setState({
verifying: true,
continueDisabled: true,
addTask: task,
});
// 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
await task.bindMsisdn(null, `+${address}`);
this.setState({
continueDisabled: false,
});
} else {
await MatrixClientPeg.get().unbindThreePid(medium, address);
}
this.setState({ bound: bind });
} catch (err) {
console.error(`Unable to ${label} phone number ${address} ${err}`);
this.setState({
verifying: false,
continueDisabled: false,
addTask: null,
});
Modal.createTrackedDialog(`Unable to ${label} phone number`, '', ErrorDialog, {
title: errorTitle,
description: ((err && err.message) ? err.message : _t("Operation failed")),
});
}
}

async changeBindingTangledAddBind({ bind, label, errorTitle }) {
const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog");
const { medium, address } = this.props.msisdn;

Expand All @@ -67,18 +109,16 @@ export class PhoneNumber extends React.Component {
});

try {
// XXX: Unfortunately, at the moment we can't just bind via the HS
// in a single operation, at it will error saying the 3PID is in use
// even though it's in use by the current user. For the moment, we
// work around this by removing the 3PID from the HS and re-adding
// it with IS binding enabled.
// See https://github.com/matrix-org/matrix-doc/pull/2140/files#r311462052
await MatrixClientPeg.get().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
await task.addMsisdn(null, `+${address}`, bind);
if (bind) {
await task.bindMsisdn(null, `+${address}`);
} else {
await task.addMsisdn(null, `+${address}`);
}
this.setState({
continueDisabled: false,
bound: bind,
Expand Down
Loading

0 comments on commit 351a3eb

Please sign in to comment.