UNPKG

23.9 kBSource Map (JSON)View Raw
1{"version":3,"sources":["../src/interactive-auth.js"],"names":["url","require","utils","EMAIL_STAGE_TYPE","MSISDN_STAGE_TYPE","InteractiveAuth","opts","_matrixClient","matrixClient","_data","authData","_requestCallback","doRequest","_stateUpdatedCallback","stateUpdated","startAuthStage","_completionDeferred","_inputs","inputs","sessionId","session","_clientSecret","clientSecret","generateClientSecret","_emailSid","emailSid","undefined","_currentStage","prototype","attemptAuth","Promise","defer","resolve","then","flows","_doRequest","_startNextAuthStage","promise","poll","authDict","idServerParsedUrl","parse","getIdentityServerUrl","type","threepid_creds","sid","client_secret","id_server","host","submitAuthDict","getSessionId","getClientSecret","getStageParams","loginType","params","background","Error","auth","extend","getEmailSid","setEmailSid","self","prom","e","reject","result","console","log","error","errorFlows","data","haveFlows","Boolean","httpStatus","completed","catch","done","nextStage","_chooseStage","errcode","stageStatus","flow","_chooseFlow","_firstUncompletedStage","haveEmail","emailAddress","haveMsisdn","phoneCountry","phoneNumber","flowHasEmail","flowHasMsisdn","stages","stage","err","name","required_stages","push","available_flows","i","length","stageType","indexOf","module","exports"],"mappings":"AAAA;;;;;;;;;;;;;;;;AAgBA;;AAEA;;;;;;;;;;AACA;;;;;;AACA,IAAMA,MAAMC,QAAQ,KAAR,CAAZ;;AAEA,IAAMC,QAAQD,QAAQ,SAAR,CAAd;;AAEA,IAAME,mBAAmB,wBAAzB;AACA,IAAMC,oBAAoB,gBAA1B;;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgEA,SAASC,eAAT,CAAyBC,IAAzB,EAA+B;AAC3B,SAAKC,aAAL,GAAqBD,KAAKE,YAA1B;AACA,SAAKC,KAAL,GAAaH,KAAKI,QAAL,IAAiB,EAA9B;AACA,SAAKC,gBAAL,GAAwBL,KAAKM,SAA7B;AACA;AACA,SAAKC,qBAAL,GAA6BP,KAAKQ,YAAL,IAAqBR,KAAKS,cAAvD;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7F,gBAAzB;AACf,YAAImF,UAAJ,EAAgBO,IAAIE,eAAJ,CAAoBC,IAApB,CAAyB5F,iBAAzB;AAChByF,YAAII,eAAJ,GAAsB/D,KAAtB;AACA,cAAM2D,GAAN;AACH,KA5SuB;;AA8SxB;;;;;;;AAOAV,4BAAwB,gCAASF,IAAT,EAAe;AACnC,YAAMP,YAAY,CAAC,KAAKjE,KAAL,IAAc,EAAf,EAAmBiE,SAAnB,IAAgC,EAAlD;AACA,aAAK,IAAIwB,IAAI,CAAb,EAAgBA,IAAIjB,KAAKU,MAAL,CAAYQ,MAAhC,EAAwC,EAAED,CAA1C,EAA6C;AACzC,gBAAME,YAAYnB,KAAKU,MAAL,CAAYO,CAAZ,CAAlB;AACA,gBAAIxB,UAAU2B,OAAV,CAAkBD,SAAlB,MAAiC,CAAC,CAAtC,EAAyC;AACrC,uBAAOA,SAAP;AACH;AACJ;AACJ;AA7TuB,CAA5B;;AAiUA;AACAE,OAAOC,OAAP,GAAiBlG,eAAjB","file":"interactive-auth.js","sourcesContent":["/*\nCopyright 2016 OpenMarket Ltd\nCopyright 2017 Vector Creations Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\"use strict\";\n\n/** @module interactive-auth */\nimport Promise from 'bluebird';\nconst url = require(\"url\");\n\nconst utils = require(\"./utils\");\n\nconst EMAIL_STAGE_TYPE = \"m.login.email.identity\";\nconst MSISDN_STAGE_TYPE = \"m.login.msisdn\";\n\n/**\n * Abstracts the logic used to drive the interactive auth process.\n *\n * <p>Components implementing an interactive auth flow should instantiate one of\n * these, passing in the necessary callbacks to the constructor. They should\n * then call attemptAuth, which will return a promise which will resolve or\n * reject when the interactive-auth process completes.\n *\n * <p>Meanwhile, calls will be made to the startAuthStage and doRequest\n * callbacks, and information gathered from the user can be submitted with\n * submitAuthDict.\n *\n * @constructor\n * @alias module:interactive-auth\n *\n * @param {object} opts options object\n *\n * @param {object} opts.matrixClient A matrix client to use for the auth process\n *\n * @param {object?} opts.authData error response from the last request. If\n * null, a request will be made with no auth before starting.\n *\n * @param {function(object?, bool?): module:client.Promise} opts.doRequest\n * called with the new auth dict to submit the request and a flag set\n * to true if this request is a background request. Should return a\n * promise which resolves to the successful response or rejects with a\n * MatrixError.\n *\n * @param {function(string, object?)} opts.stateUpdated\n * called when the status of the UI auth changes, ie. when the state of\n * an auth stage changes of when the auth flow moves to a new stage.\n * The arguments are: the login type (eg m.login.password); and an object\n * which is either an error or an informational object specific to the\n * login type. If the 'errcode' key is defined, the object is an error,\n * and has keys:\n * errcode: string, the textual error code, eg. M_UNKNOWN\n * error: string, human readable string describing the error\n *\n * The login type specific objects are as follows:\n * m.login.email.identity:\n * * emailSid: string, the sid of the active email auth session\n *\n * @param {object?} opts.inputs Inputs provided by the user and used by different\n * stages of the auto process. The inputs provided will affect what flow is chosen.\n *\n * @param {string?} opts.inputs.emailAddress An email address. If supplied, a flow\n * using email verification will be chosen.\n *\n * @param {string?} opts.inputs.phoneCountry An ISO two letter country code. Gives\n * the country that opts.phoneNumber should be resolved relative to.\n *\n * @param {string?} opts.inputs.phoneNumber A phone number. If supplied, a flow\n * using phone number validation will be chosen.\n *\n * @param {string?} opts.sessionId If resuming an existing interactive auth session,\n * the sessionId of that session.\n *\n * @param {string?} opts.clientSecret If resuming an existing interactive auth session,\n * the client secret for that session\n *\n * @param {string?} opts.emailSid If returning from having completed m.login.email.identity\n * auth, the sid for the email verification session.\n *\n */\nfunction InteractiveAuth(opts) {\n this._matrixClient = opts.matrixClient;\n this._data = opts.authData || {};\n this._requestCallback = opts.doRequest;\n // startAuthStage included for backwards compat\n this._stateUpdatedCallback = opts.stateUpdated || opts.startAuthStage;\n this._completionDeferred = null;\n this._inputs = opts.inputs || {};\n\n if (opts.sessionId) this._data.session = opts.sessionId;\n this._clientSecret = opts.clientSecret || this._matrixClient.generateClientSecret();\n this._emailSid = opts.emailSid;\n if (this._emailSid === undefined) this._emailSid = null;\n\n this._currentStage = null;\n}\n\nInteractiveAuth.prototype = {\n /**\n * begin the authentication process.\n *\n * @return {module:client.Promise} which resolves to the response on success,\n * or rejects with the error on failure. Rejects with NoAuthFlowFoundError if\n * no suitable authentication flow can be found\n */\n attemptAuth: function() {\n this._completionDeferred = Promise.defer();\n\n // wrap in a promise so that if _startNextAuthStage\n // throws, it rejects the promise in a consistent way\n return Promise.resolve().then(() => {\n // if we have no flows, try a request (we'll have\n // just a session ID in _data if resuming)\n if (!this._data.flows) {\n this._doRequest(this._data);\n } else {\n this._startNextAuthStage();\n }\n return this._completionDeferred.promise;\n });\n },\n\n /**\n * Poll to check if the auth session or current stage has been\n * completed out-of-band. If so, the attemptAuth promise will\n * be resolved.\n */\n poll: function() {\n if (!this._data.session) return;\n\n let authDict = {};\n if (this._currentStage == EMAIL_STAGE_TYPE) {\n // The email can be validated out-of-band, but we need to provide the\n // creds so the HS can go & check it.\n if (this._emailSid) {\n const idServerParsedUrl = url.parse(\n this._matrixClient.getIdentityServerUrl(),\n );\n authDict = {\n type: EMAIL_STAGE_TYPE,\n threepid_creds: {\n sid: this._emailSid,\n client_secret: this._clientSecret,\n id_server: idServerParsedUrl.host,\n },\n };\n }\n }\n\n this.submitAuthDict(authDict, true);\n },\n\n /**\n * get the auth session ID\n *\n * @return {string} session id\n */\n getSessionId: function() {\n return this._data ? this._data.session : undefined;\n },\n\n /**\n * get the client secret used for validation sessions\n * with the ID server.\n *\n * @return {string} client secret\n */\n getClientSecret: function() {\n return this._clientSecret;\n },\n\n /**\n * get the server params for a given stage\n *\n * @param {string} loginType login type for the stage\n * @return {object?} any parameters from the server for this stage\n */\n getStageParams: function(loginType) {\n let params = {};\n if (this._data && this._data.params) {\n params = this._data.params;\n }\n return params[loginType];\n },\n\n /**\n * submit a new auth dict and fire off the request. This will either\n * make attemptAuth resolve/reject, or cause the startAuthStage callback\n * to be called for a new stage.\n *\n * @param {object} authData new auth dict to send to the server. Should\n * include a `type` propterty denoting the login type, as well as any\n * other params for that stage.\n * @param {bool} background If true, this request failing will not result\n * in the attemptAuth promise being rejected. This can be set to true\n * for requests that just poll to see if auth has been completed elsewhere.\n */\n submitAuthDict: function(authData, background) {\n if (!this._completionDeferred) {\n throw new Error(\"submitAuthDict() called before attemptAuth()\");\n }\n\n // use the sessionid from the last request.\n const auth = {\n session: this._data.session,\n };\n utils.extend(auth, authData);\n\n this._doRequest(auth, background);\n },\n\n /**\n * Gets the sid for the email validation session\n * Specific to m.login.email.identity\n *\n * @returns {string} The sid of the email auth session\n */\n getEmailSid: function() {\n return this._emailSid;\n },\n\n /**\n * Sets the sid for the email validation session\n * This must be set in order to successfully poll for completion\n * of the email validation.\n * Specific to m.login.email.identity\n *\n * @param {string} sid The sid for the email validation session\n */\n setEmailSid: function(sid) {\n this._emailSid = sid;\n },\n\n /**\n * Fire off a request, and either resolve the promise, or call\n * startAuthStage.\n *\n * @private\n * @param {object?} auth new auth dict, including session id\n * @param {bool?} background If true, this request is a background poll, so it\n * failing will not result in the attemptAuth promise being rejected.\n * This can be set to true for requests that just poll to see if auth has\n * been completed elsewhere.\n */\n _doRequest: function(auth, background) {\n const self = this;\n\n // hackery to make sure that synchronous exceptions end up in the catch\n // handler (without the additional event loop entailed by q.fcall or an\n // extra Promise.resolve().then)\n let prom;\n try {\n prom = this._requestCallback(auth, background);\n } catch (e) {\n prom = Promise.reject(e);\n }\n\n prom = prom.then(\n function(result) {\n console.log(\"result from request: \", result);\n self._completionDeferred.resolve(result);\n }, function(error) {\n // sometimes UI auth errors don't come with flows\n const errorFlows = error.data ? error.data.flows : null;\n const haveFlows = Boolean(self._data.flows) || Boolean(errorFlows);\n if (error.httpStatus !== 401 || !error.data || !haveFlows) {\n // doesn't look like an interactive-auth failure. fail the whole lot.\n throw error;\n }\n // if the error didn't come with flows, completed flows or session ID,\n // copy over the ones we have. Synapse sometimes sends responses without\n // any UI auth data (eg. when polling for email validation, if the email\n // has not yet been validated). This appears to be a Synapse bug, which\n // we workaround here.\n if (!error.data.flows && !error.data.completed && !error.data.session) {\n error.data.flows = self._data.flows;\n error.data.completed = self._data.completed;\n error.data.session = self._data.session;\n }\n self._data = error.data;\n self._startNextAuthStage();\n },\n );\n if (!background) {\n prom = prom.catch((e) => {\n this._completionDeferred.reject(e);\n });\n } else {\n // We ignore all failures here (even non-UI auth related ones)\n // since we don't want to suddenly fail if the internet connection\n // had a blip whilst we were polling\n prom = prom.catch((error) => {\n console.log(\"Ignoring error from UI auth: \" + error);\n });\n }\n prom.done();\n },\n\n /**\n * Pick the next stage and call the callback\n *\n * @private\n * @throws {NoAuthFlowFoundError} If no suitable authentication flow can be found\n */\n _startNextAuthStage: function() {\n const nextStage = this._chooseStage();\n if (!nextStage) {\n throw new Error(\"No incomplete flows from the server\");\n }\n this._currentStage = nextStage;\n\n if (nextStage == 'm.login.dummy') {\n this.submitAuthDict({\n type: 'm.login.dummy',\n });\n return;\n }\n\n if (this._data.errcode || this._data.error) {\n this._stateUpdatedCallback(nextStage, {\n errcode: this._data.errcode || \"\",\n error: this._data.error || \"\",\n });\n return;\n }\n\n const stageStatus = {};\n if (nextStage == EMAIL_STAGE_TYPE) {\n stageStatus.emailSid = this._emailSid;\n }\n this._stateUpdatedCallback(nextStage, stageStatus);\n },\n\n /**\n * Pick the next auth stage\n *\n * @private\n * @return {string?} login type\n * @throws {NoAuthFlowFoundError} If no suitable authentication flow can be found\n */\n _chooseStage: function() {\n const flow = this._chooseFlow();\n console.log(\"Active flow => %s\", JSON.stringify(flow));\n const nextStage = this._firstUncompletedStage(flow);\n console.log(\"Next stage: %s\", nextStage);\n return nextStage;\n },\n\n /**\n * Pick one of the flows from the returned list\n * If a flow using all of the inputs is found, it will\n * be returned, otherwise, null will be returned.\n *\n * Only flows using all given inputs are chosen because it\n * is likley to be surprising if the user provides a\n * credential and it is not used. For example, for registration,\n * this could result in the email not being used which would leave\n * the account with no means to reset a password.\n *\n * @private\n * @return {object} flow\n * @throws {NoAuthFlowFoundError} If no suitable authentication flow can be found\n */\n _chooseFlow: function() {\n const flows = this._data.flows || [];\n\n // we've been given an email or we've already done an email part\n const haveEmail = Boolean(this._inputs.emailAddress) || Boolean(this._emailSid);\n const haveMsisdn = (\n Boolean(this._inputs.phoneCountry) &&\n Boolean(this._inputs.phoneNumber)\n );\n\n for (const flow of flows) {\n let flowHasEmail = false;\n let flowHasMsisdn = false;\n for (const stage of flow.stages) {\n if (stage === EMAIL_STAGE_TYPE) {\n flowHasEmail = true;\n } else if (stage == MSISDN_STAGE_TYPE) {\n flowHasMsisdn = true;\n }\n }\n\n if (flowHasEmail == haveEmail && flowHasMsisdn == haveMsisdn) {\n return flow;\n }\n }\n // Throw an error with a fairly generic description, but with more\n // information such that the app can give a better one if so desired.\n const err = new Error(\"No appropriate authentication flow found\");\n err.name = 'NoAuthFlowFoundError';\n err.required_stages = [];\n if (haveEmail) err.required_stages.push(EMAIL_STAGE_TYPE);\n if (haveMsisdn) err.required_stages.push(MSISDN_STAGE_TYPE);\n err.available_flows = flows;\n throw err;\n },\n\n /**\n * Get the first uncompleted stage in the given flow\n *\n * @private\n * @param {object} flow\n * @return {string} login type\n */\n _firstUncompletedStage: function(flow) {\n const completed = (this._data || {}).completed || [];\n for (let i = 0; i < flow.stages.length; ++i) {\n const stageType = flow.stages[i];\n if (completed.indexOf(stageType) === -1) {\n return stageType;\n }\n }\n },\n};\n\n\n/** */\nmodule.exports = InteractiveAuth;\n"]}
\No newline at end of file