UNPKG

20 kBJavaScriptView Raw
1/*
2Copyright 2016 OpenMarket Ltd
3Copyright 2017 Vector Creations Ltd
4Copyright 2019 The Matrix.org Foundation C.I.C.
5
6Licensed under the Apache License, Version 2.0 (the "License");
7you may not use this file except in compliance with the License.
8You may obtain a copy of the License at
9
10 http://www.apache.org/licenses/LICENSE-2.0
11
12Unless required by applicable law or agreed to in writing, software
13distributed under the License is distributed on an "AS IS" BASIS,
14WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15See the License for the specific language governing permissions and
16limitations under the License.
17*/
18
19/** @module interactive-auth */
20
21import url from "url";
22import * as utils from "./utils";
23import {logger} from './logger';
24
25const EMAIL_STAGE_TYPE = "m.login.email.identity";
26const MSISDN_STAGE_TYPE = "m.login.msisdn";
27
28/**
29 * Abstracts the logic used to drive the interactive auth process.
30 *
31 * <p>Components implementing an interactive auth flow should instantiate one of
32 * these, passing in the necessary callbacks to the constructor. They should
33 * then call attemptAuth, which will return a promise which will resolve or
34 * reject when the interactive-auth process completes.
35 *
36 * <p>Meanwhile, calls will be made to the startAuthStage and doRequest
37 * callbacks, and information gathered from the user can be submitted with
38 * submitAuthDict.
39 *
40 * @constructor
41 * @alias module:interactive-auth
42 *
43 * @param {object} opts options object
44 *
45 * @param {object} opts.matrixClient A matrix client to use for the auth process
46 *
47 * @param {object?} opts.authData error response from the last request. If
48 * null, a request will be made with no auth before starting.
49 *
50 * @param {function(object?): Promise} opts.doRequest
51 * called with the new auth dict to submit the request. Also passes a
52 * second deprecated arg which is a flag set to true if this request
53 * is a background request. The busyChanged callback should be used
54 * instead of the backfround flag. Should return a promise which resolves
55 * to the successful response or rejects with a MatrixError.
56 *
57 * @param {function(bool): Promise} opts.busyChanged
58 * called whenever the interactive auth logic becomes busy submitting
59 * information provided by the user or finsihes. After this has been
60 * called with true the UI should indicate that a request is in progress
61 * until it is called again with false.
62 *
63 * @param {function(string, object?)} opts.stateUpdated
64 * called when the status of the UI auth changes, ie. when the state of
65 * an auth stage changes of when the auth flow moves to a new stage.
66 * The arguments are: the login type (eg m.login.password); and an object
67 * which is either an error or an informational object specific to the
68 * login type. If the 'errcode' key is defined, the object is an error,
69 * and has keys:
70 * errcode: string, the textual error code, eg. M_UNKNOWN
71 * error: string, human readable string describing the error
72 *
73 * The login type specific objects are as follows:
74 * m.login.email.identity:
75 * * emailSid: string, the sid of the active email auth session
76 *
77 * @param {object?} opts.inputs Inputs provided by the user and used by different
78 * stages of the auto process. The inputs provided will affect what flow is chosen.
79 *
80 * @param {string?} opts.inputs.emailAddress An email address. If supplied, a flow
81 * using email verification will be chosen.
82 *
83 * @param {string?} opts.inputs.phoneCountry An ISO two letter country code. Gives
84 * the country that opts.phoneNumber should be resolved relative to.
85 *
86 * @param {string?} opts.inputs.phoneNumber A phone number. If supplied, a flow
87 * using phone number validation will be chosen.
88 *
89 * @param {string?} opts.sessionId If resuming an existing interactive auth session,
90 * the sessionId of that session.
91 *
92 * @param {string?} opts.clientSecret If resuming an existing interactive auth session,
93 * the client secret for that session
94 *
95 * @param {string?} opts.emailSid If returning from having completed m.login.email.identity
96 * auth, the sid for the email verification session.
97 *
98 * @param {function?} opts.requestEmailToken A function that takes the email address (string),
99 * clientSecret (string), attempt number (int) and sessionId (string) and calls the
100 * relevant requestToken function and returns the promise returned by that function.
101 * If the resulting promise rejects, the rejection will propagate through to the
102 * attemptAuth promise.
103 *
104 */
105export function InteractiveAuth(opts) {
106 this._matrixClient = opts.matrixClient;
107 this._data = opts.authData || {};
108 this._requestCallback = opts.doRequest;
109 this._busyChangedCallback = opts.busyChanged;
110 // startAuthStage included for backwards compat
111 this._stateUpdatedCallback = opts.stateUpdated || opts.startAuthStage;
112 this._resolveFunc = null;
113 this._rejectFunc = null;
114 this._inputs = opts.inputs || {};
115 this._requestEmailTokenCallback = opts.requestEmailToken;
116
117 if (opts.sessionId) this._data.session = opts.sessionId;
118 this._clientSecret = opts.clientSecret || this._matrixClient.generateClientSecret();
119 this._emailSid = opts.emailSid;
120 if (this._emailSid === undefined) this._emailSid = null;
121 this._requestingEmailToken = false;
122
123 this._chosenFlow = null;
124 this._currentStage = null;
125
126 // if we are currently trying to submit an auth dict (which includes polling)
127 // the promise the will resolve/reject when it completes
128 this._submitPromise = null;
129}
130
131InteractiveAuth.prototype = {
132 /**
133 * begin the authentication process.
134 *
135 * @return {Promise} which resolves to the response on success,
136 * or rejects with the error on failure. Rejects with NoAuthFlowFoundError if
137 * no suitable authentication flow can be found
138 */
139 attemptAuth: function() {
140 // This promise will be quite long-lived and will resolve when the
141 // request is authenticated and completes successfully.
142 return new Promise((resolve, reject) => {
143 this._resolveFunc = resolve;
144 this._rejectFunc = reject;
145
146 // if we have no flows, try a request (we'll have
147 // just a session ID in _data if resuming)
148 if (!this._data.flows) {
149 if (this._busyChangedCallback) this._busyChangedCallback(true);
150 this._doRequest(this._data).finally(() => {
151 if (this._busyChangedCallback) this._busyChangedCallback(false);
152 });
153 } else {
154 this._startNextAuthStage();
155 }
156 });
157 },
158
159 /**
160 * Poll to check if the auth session or current stage has been
161 * completed out-of-band. If so, the attemptAuth promise will
162 * be resolved.
163 */
164 poll: async function() {
165 if (!this._data.session) return;
166 // if we currently have a request in flight, there's no point making
167 // another just to check what the status is
168 if (this._submitPromise) return;
169
170 let authDict = {};
171 if (this._currentStage == EMAIL_STAGE_TYPE) {
172 // The email can be validated out-of-band, but we need to provide the
173 // creds so the HS can go & check it.
174 if (this._emailSid) {
175 const creds = {
176 sid: this._emailSid,
177 client_secret: this._clientSecret,
178 };
179 if (await this._matrixClient.doesServerRequireIdServerParam()) {
180 const idServerParsedUrl = url.parse(
181 this._matrixClient.getIdentityServerUrl(),
182 );
183 creds.id_server = idServerParsedUrl.host;
184 }
185 authDict = {
186 type: EMAIL_STAGE_TYPE,
187 threepid_creds: creds,
188 };
189 }
190 }
191
192 this.submitAuthDict(authDict, true);
193 },
194
195 /**
196 * get the auth session ID
197 *
198 * @return {string} session id
199 */
200 getSessionId: function() {
201 return this._data ? this._data.session : undefined;
202 },
203
204 /**
205 * get the client secret used for validation sessions
206 * with the ID server.
207 *
208 * @return {string} client secret
209 */
210 getClientSecret: function() {
211 return this._clientSecret;
212 },
213
214 /**
215 * get the server params for a given stage
216 *
217 * @param {string} loginType login type for the stage
218 * @return {object?} any parameters from the server for this stage
219 */
220 getStageParams: function(loginType) {
221 let params = {};
222 if (this._data && this._data.params) {
223 params = this._data.params;
224 }
225 return params[loginType];
226 },
227
228 getChosenFlow() {
229 return this._chosenFlow;
230 },
231
232 /**
233 * submit a new auth dict and fire off the request. This will either
234 * make attemptAuth resolve/reject, or cause the startAuthStage callback
235 * to be called for a new stage.
236 *
237 * @param {object} authData new auth dict to send to the server. Should
238 * include a `type` propterty denoting the login type, as well as any
239 * other params for that stage.
240 * @param {bool} background If true, this request failing will not result
241 * in the attemptAuth promise being rejected. This can be set to true
242 * for requests that just poll to see if auth has been completed elsewhere.
243 */
244 submitAuthDict: async function(authData, background) {
245 if (!this._resolveFunc) {
246 throw new Error("submitAuthDict() called before attemptAuth()");
247 }
248
249 if (!background && this._busyChangedCallback) {
250 this._busyChangedCallback(true);
251 }
252
253 // if we're currently trying a request, wait for it to finish
254 // as otherwise we can get multiple 200 responses which can mean
255 // things like multiple logins for register requests.
256 // (but discard any expections as we only care when its done,
257 // not whether it worked or not)
258 while (this._submitPromise) {
259 try {
260 await this._submitPromise;
261 } catch (e) {
262 }
263 }
264
265 // use the sessionid from the last request.
266 const auth = {
267 session: this._data.session,
268 };
269 utils.extend(auth, authData);
270
271 try {
272 // NB. the 'background' flag is deprecated by the busyChanged
273 // callback and is here for backwards compat
274 this._submitPromise = this._doRequest(auth, background);
275 await this._submitPromise;
276 } finally {
277 this._submitPromise = null;
278 if (!background && this._busyChangedCallback) {
279 this._busyChangedCallback(false);
280 }
281 }
282 },
283
284 /**
285 * Gets the sid for the email validation session
286 * Specific to m.login.email.identity
287 *
288 * @returns {string} The sid of the email auth session
289 */
290 getEmailSid: function() {
291 return this._emailSid;
292 },
293
294 /**
295 * Sets the sid for the email validation session
296 * This must be set in order to successfully poll for completion
297 * of the email validation.
298 * Specific to m.login.email.identity
299 *
300 * @param {string} sid The sid for the email validation session
301 */
302 setEmailSid: function(sid) {
303 this._emailSid = sid;
304 },
305
306 /**
307 * Fire off a request, and either resolve the promise, or call
308 * startAuthStage.
309 *
310 * @private
311 * @param {object?} auth new auth dict, including session id
312 * @param {bool?} background If true, this request is a background poll, so it
313 * failing will not result in the attemptAuth promise being rejected.
314 * This can be set to true for requests that just poll to see if auth has
315 * been completed elsewhere.
316 */
317 _doRequest: async function(auth, background) {
318 try {
319 const result = await this._requestCallback(auth, background);
320 this._resolveFunc(result);
321 } catch (error) {
322 // sometimes UI auth errors don't come with flows
323 const errorFlows = error.data ? error.data.flows : null;
324 const haveFlows = Boolean(this._data.flows) || Boolean(errorFlows);
325 if (error.httpStatus !== 401 || !error.data || !haveFlows) {
326 // doesn't look like an interactive-auth failure.
327 if (!background) {
328 this._rejectFunc(error);
329 } else {
330 // We ignore all failures here (even non-UI auth related ones)
331 // since we don't want to suddenly fail if the internet connection
332 // had a blip whilst we were polling
333 logger.log(
334 "Background poll request failed doing UI auth: ignoring",
335 error,
336 );
337 }
338 }
339 // if the error didn't come with flows, completed flows or session ID,
340 // copy over the ones we have. Synapse sometimes sends responses without
341 // any UI auth data (eg. when polling for email validation, if the email
342 // has not yet been validated). This appears to be a Synapse bug, which
343 // we workaround here.
344 if (!error.data.flows && !error.data.completed && !error.data.session) {
345 error.data.flows = this._data.flows;
346 error.data.completed = this._data.completed;
347 error.data.session = this._data.session;
348 }
349 this._data = error.data;
350 this._startNextAuthStage();
351
352 if (
353 !this._emailSid &&
354 !this._requestingEmailToken &&
355 this._chosenFlow.stages.includes('m.login.email.identity')
356 ) {
357 // If we've picked a flow with email auth, we send the email
358 // now because we want the request to fail as soon as possible
359 // if the email address is not valid (ie. already taken or not
360 // registered, depending on what the operation is).
361 this._requestingEmailToken = true;
362 try {
363 const requestTokenResult = await this._requestEmailTokenCallback(
364 this._inputs.emailAddress,
365 this._clientSecret,
366 1, // TODO: Multiple send attempts?
367 this._data.session,
368 );
369 this._emailSid = requestTokenResult.sid;
370 // NB. promise is not resolved here - at some point, doRequest
371 // will be called again and if the user has jumped through all
372 // the hoops correctly, auth will be complete and the request
373 // will succeed.
374 // Also, we should expose the fact that this request has compledted
375 // so clients can know that the email has actually been sent.
376 } catch (e) {
377 // we failed to request an email token, so fail the request.
378 // This could be due to the email already beeing registered
379 // (or not being registered, depending on what we're trying
380 // to do) or it could be a network failure. Either way, pass
381 // the failure up as the user can't complete auth if we can't
382 // send the email, foe whatever reason.
383 this._rejectFunc(e);
384 } finally {
385 this._requestingEmailToken = false;
386 }
387 }
388 }
389 },
390
391 /**
392 * Pick the next stage and call the callback
393 *
394 * @private
395 * @throws {NoAuthFlowFoundError} If no suitable authentication flow can be found
396 */
397 _startNextAuthStage: function() {
398 const nextStage = this._chooseStage();
399 if (!nextStage) {
400 throw new Error("No incomplete flows from the server");
401 }
402 this._currentStage = nextStage;
403
404 if (nextStage === 'm.login.dummy') {
405 this.submitAuthDict({
406 type: 'm.login.dummy',
407 });
408 return;
409 }
410
411 if (this._data.errcode || this._data.error) {
412 this._stateUpdatedCallback(nextStage, {
413 errcode: this._data.errcode || "",
414 error: this._data.error || "",
415 });
416 return;
417 }
418
419 const stageStatus = {};
420 if (nextStage == EMAIL_STAGE_TYPE) {
421 stageStatus.emailSid = this._emailSid;
422 }
423 this._stateUpdatedCallback(nextStage, stageStatus);
424 },
425
426 /**
427 * Pick the next auth stage
428 *
429 * @private
430 * @return {string?} login type
431 * @throws {NoAuthFlowFoundError} If no suitable authentication flow can be found
432 */
433 _chooseStage: function() {
434 if (this._chosenFlow === null) {
435 this._chosenFlow = this._chooseFlow();
436 }
437 logger.log("Active flow => %s", JSON.stringify(this._chosenFlow));
438 const nextStage = this._firstUncompletedStage(this._chosenFlow);
439 logger.log("Next stage: %s", nextStage);
440 return nextStage;
441 },
442
443 /**
444 * Pick one of the flows from the returned list
445 * If a flow using all of the inputs is found, it will
446 * be returned, otherwise, null will be returned.
447 *
448 * Only flows using all given inputs are chosen because it
449 * is likley to be surprising if the user provides a
450 * credential and it is not used. For example, for registration,
451 * this could result in the email not being used which would leave
452 * the account with no means to reset a password.
453 *
454 * @private
455 * @return {object} flow
456 * @throws {NoAuthFlowFoundError} If no suitable authentication flow can be found
457 */
458 _chooseFlow: function() {
459 const flows = this._data.flows || [];
460
461 // we've been given an email or we've already done an email part
462 const haveEmail = Boolean(this._inputs.emailAddress) || Boolean(this._emailSid);
463 const haveMsisdn = (
464 Boolean(this._inputs.phoneCountry) &&
465 Boolean(this._inputs.phoneNumber)
466 );
467
468 for (const flow of flows) {
469 let flowHasEmail = false;
470 let flowHasMsisdn = false;
471 for (const stage of flow.stages) {
472 if (stage === EMAIL_STAGE_TYPE) {
473 flowHasEmail = true;
474 } else if (stage == MSISDN_STAGE_TYPE) {
475 flowHasMsisdn = true;
476 }
477 }
478
479 if (flowHasEmail == haveEmail && flowHasMsisdn == haveMsisdn) {
480 return flow;
481 }
482 }
483 // Throw an error with a fairly generic description, but with more
484 // information such that the app can give a better one if so desired.
485 const err = new Error("No appropriate authentication flow found");
486 err.name = 'NoAuthFlowFoundError';
487 err.required_stages = [];
488 if (haveEmail) err.required_stages.push(EMAIL_STAGE_TYPE);
489 if (haveMsisdn) err.required_stages.push(MSISDN_STAGE_TYPE);
490 err.available_flows = flows;
491 throw err;
492 },
493
494 /**
495 * Get the first uncompleted stage in the given flow
496 *
497 * @private
498 * @param {object} flow
499 * @return {string} login type
500 */
501 _firstUncompletedStage: function(flow) {
502 const completed = (this._data || {}).completed || [];
503 for (let i = 0; i < flow.stages.length; ++i) {
504 const stageType = flow.stages[i];
505 if (completed.indexOf(stageType) === -1) {
506 return stageType;
507 }
508 }
509 },
510};
511