This repository has been archived by the owner on Apr 3, 2019. It is now read-only.
/
app-start.js
623 lines (553 loc) · 19.4 KB
/
app-start.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// this module starts it all.
/**
* the flow:
* 1) Initialize session information from URL search parameters.
* 2) Fetch /config from the backend, the returned info includes a flag that
* indicates whether cookies are enabled.
* 3) Fetch translations from the backend.
* 4) Create the web/desktop communication channel.
* 5) If cookies are disabled, go to the /cookies_disabled page.
* 6) Start the app if cookies are enabled.
*/
'use strict';
define([
'underscore',
'backbone',
'lib/promise',
'router',
'lib/translator',
'lib/session',
'lib/url',
'lib/config-loader',
'lib/screen-info',
'lib/metrics',
'lib/storage-metrics',
'lib/null-metrics',
'lib/fxa-client',
'lib/assertion',
'lib/constants',
'lib/oauth-client',
'lib/oauth-errors',
'lib/auth-errors',
'lib/profile-client',
'lib/marketing-email-client',
'lib/channels/inter-tab',
'lib/channels/iframe',
'lib/channels/web',
'lib/storage',
'lib/able',
'lib/environment',
'lib/origin-check',
'models/reliers/relier',
'models/reliers/oauth',
'models/reliers/fx-desktop',
'models/auth_brokers/base',
'models/auth_brokers/fx-desktop',
'models/auth_brokers/fx-desktop-v2',
'models/auth_brokers/web-channel',
'models/auth_brokers/redirect',
'models/auth_brokers/iframe',
'models/user',
'models/form-prefill',
'models/notifications',
'views/close_button'
],
function (
_,
Backbone,
p,
Router,
Translator,
Session,
Url,
ConfigLoader,
ScreenInfo,
Metrics,
StorageMetrics,
NullMetrics,
FxaClient,
Assertion,
Constants,
OAuthClient,
OAuthErrors,
AuthErrors,
ProfileClient,
MarketingEmailClient,
InterTabChannel,
IframeChannel,
WebChannel,
Storage,
Able,
Environment,
OriginCheck,
Relier,
OAuthRelier,
FxDesktopRelier,
BaseAuthenticationBroker,
FxDesktopV1AuthenticationBroker,
FxDesktopV2AuthenticationBroker,
WebChannelAuthenticationBroker,
RedirectAuthenticationBroker,
IframeAuthenticationBroker,
User,
FormPrefill,
Notifications,
CloseButtonView
) {
function isMetricsCollectionEnabled (sampleRate) {
return Math.random() <= sampleRate;
}
function Start(options) {
options = options || {};
this._window = options.window || window;
this._router = options.router;
this._relier = options.relier;
this._authenticationBroker = options.broker;
this._user = options.user;
this._history = options.history || Backbone.history;
this._configLoader = new ConfigLoader();
}
Start.prototype = {
startApp: function () {
var self = this;
// fetch both config and translations in parallel to speed up load.
return p.all([
this.initializeAble(),
this.initializeConfig(),
this.initializeL10n(),
this.initializeInterTabChannel()
])
.then(_.bind(this.allResourcesReady, this))
.then(function () {
self._trackWindowOnError();
}, function (err) {
if (console && console.error) {
console.error('Critical error:');
console.error(String(err));
}
if (self._metrics) {
self._metrics.logError(err);
}
// this extra promise is to ensure the message is printed
// to the console in Firefox before redirecting. Without
// the delay, the console message is lost, even with
// persistent logs enabled. See #2183
return p()
.then(function () {
//Something terrible happened. Let's bail.
var redirectTo = self._getErrorPage(err);
self._window.location.href = redirectTo;
});
});
},
initializeInterTabChannel: function () {
this._interTabChannel = new InterTabChannel();
},
_trackWindowOnError: function () {
var self = this;
// if startup is okay we want to log future window.onerror events
window.onerror = function (message /*, url, lineNumber*/) {
var errMsg = 'null';
if (message) {
errMsg = message.toString().substring(0, Constants.ONERROR_MESSAGE_LIMIT);
}
if (self._metrics) {
self._metrics.logEvent('error.onwindow.' + errMsg);
}
};
},
initializeAble: function () {
this._able = new Able();
},
initializeConfig: function () {
return this._configLoader.fetch()
.then(_.bind(this.useConfig, this))
.then(_.bind(this.initializeOAuthClient, this))
// both the metrics and router depend on the language
// fetched from config.
.then(_.bind(this.initializeRelier, this))
// metrics depends on the relier.
.then(_.bind(this.initializeMetrics, this))
// iframe channel depends on the relier and metrics
.then(_.bind(this.initializeIframeChannel, this))
// fxaClient depends on the relier and
// inter tab communication.
.then(_.bind(this.initializeFxaClient, this))
// assertionLibrary depends on fxaClient
.then(_.bind(this.initializeAssertionLibrary, this))
// profileClient depends on fxaClient and assertionLibrary
.then(_.bind(this.initializeProfileClient, this))
// marketingEmailClient depends on config
.then(_.bind(this.initializeMarketingEmailClient, this))
// user depends on the profileClient, oAuthClient, and assertionLibrary.
.then(_.bind(this.initializeUser, this))
// broker relies on the user, relier, fxaClient,
// assertionLibrary, and metrics
.then(_.bind(this.initializeAuthenticationBroker, this))
// the close button depends on the broker
.then(_.bind(this.initializeCloseButton, this))
// storage format upgrades depend on user
.then(_.bind(this.upgradeStorageFormats, this))
// depends on nothing
.then(_.bind(this.initializeFormPrefill, this))
// depends on iframeChannel and interTabChannel
.then(_.bind(this.initializeNotifications, this))
// router depends on all of the above
.then(_.bind(this.initializeRouter, this));
},
useConfig: function (config) {
this._config = config;
this._configLoader.useConfig(config);
},
initializeL10n: function () {
this._translator = this._window.translator = new Translator();
return this._translator.fetch();
},
initializeMetrics: function () {
var relier = this._relier;
var screenInfo = new ScreenInfo(this._window);
this._metrics = this._createMetrics(this._config.metricsSampleRate, {
lang: this._config.language,
service: relier.get('service'),
context: relier.get('context'),
entrypoint: relier.get('entrypoint'),
migration: relier.get('migration'),
campaign: relier.get('campaign'),
clientHeight: screenInfo.clientHeight,
clientWidth: screenInfo.clientWidth,
devicePixelRatio: screenInfo.devicePixelRatio,
screenHeight: screenInfo.screenHeight,
screenWidth: screenInfo.screenWidth,
able: this._able
});
this._metrics.init();
},
_getAllowedParentOrigins: function () {
if (! this._isInAnIframe()) {
return [];
} else if (this._isFxDesktop()) {
// If in an iframe for sync, the origin is checked against
// a pre-defined set of origins sent from the server.
return this._config.allowedParentOrigins;
} else if (this._isOAuth()) {
// If in oauth, the relier has the allowed parent origin.
return [this._relier.get('origin')];
}
return [];
},
_checkParentOrigin: function (originCheck) {
var self = this;
originCheck = originCheck || new OriginCheck(self._window);
var allowedOrigins = self._getAllowedParentOrigins();
return originCheck.getOrigin(self._window.parent, allowedOrigins);
},
initializeIframeChannel: function () {
var self = this;
if (! self._isInAnIframe()) {
return p();
}
return self._checkParentOrigin()
.then(function (parentOrigin) {
if (! parentOrigin) {
// No allowed origins were found. Illegal iframe.
throw AuthErrors.toError('ILLEGAL_IFRAME_PARENT');
}
var iframeChannel = new IframeChannel();
iframeChannel.initialize({
window: self._window,
origin: parentOrigin,
metrics: self._metrics
});
self._iframeChannel = iframeChannel;
});
},
initializeFormPrefill: function () {
this._formPrefill = new FormPrefill();
},
initializeOAuthClient: function () {
this._oAuthClient = new OAuthClient({
oAuthUrl: this._config.oAuthUrl
});
},
initializeProfileClient: function () {
this._profileClient = new ProfileClient({
profileUrl: this._config.profileUrl
});
},
initializeMarketingEmailClient: function () {
this._marketingEmailClient = new MarketingEmailClient({
baseUrl: this._config.marketingEmailServerUrl,
preferencesUrl: this._config.marketingEmailPreferencesUrl
});
},
initializeRelier: function () {
if (! this._relier) {
var relier;
if (this._isFxDesktop()) {
// Use the FxDesktopRelier for sync verification so that
// the service name is translated correctly.
relier = new FxDesktopRelier({
window: this._window,
translator: this._translator
});
} else if (this._isOAuth()) {
relier = new OAuthRelier({
window: this._window,
oAuthClient: this._oAuthClient,
session: Session
});
} else {
relier = new Relier({
window: this._window
});
}
this._relier = relier;
return relier.fetch();
}
},
initializeAssertionLibrary: function () {
this._assertionLibrary = new Assertion({
fxaClient: this._fxaClient,
audience: this._config.oAuthUrl
});
},
initializeAuthenticationBroker: function () {
/*jshint maxcomplexity: 7 */
/*eslint complexity: [2, 7] */
if (! this._authenticationBroker) {
if (this._isFxDesktopV2()) {
this._authenticationBroker = new FxDesktopV2AuthenticationBroker({
window: this._window,
relier: this._relier,
metrics: this._metrics
});
} else if (this._isFxDesktopV1()) {
this._authenticationBroker = new FxDesktopV1AuthenticationBroker({
window: this._window,
relier: this._relier,
metrics: this._metrics
});
} else if (this._isWebChannel()) {
this._authenticationBroker = new WebChannelAuthenticationBroker({
window: this._window,
relier: this._relier,
fxaClient: this._fxaClient,
assertionLibrary: this._assertionLibrary,
oAuthClient: this._oAuthClient,
session: Session
});
} else if (this._isIframe()) {
this._authenticationBroker = new IframeAuthenticationBroker({
window: this._window,
relier: this._relier,
assertionLibrary: this._assertionLibrary,
oAuthClient: this._oAuthClient,
session: Session,
channel: this._iframeChannel,
metrics: this._metrics
});
} else if (this._isOAuth()) {
this._authenticationBroker = new RedirectAuthenticationBroker({
window: this._window,
relier: this._relier,
assertionLibrary: this._assertionLibrary,
oAuthClient: this._oAuthClient,
session: Session
});
} else {
this._authenticationBroker = new BaseAuthenticationBroker({
relier: this._relier
});
}
this._metrics.setBrokerType(this._authenticationBroker.type);
return this._authenticationBroker.fetch();
}
},
initializeCloseButton: function () {
if (this._authenticationBroker.canCancel()) {
this._closeButton = new CloseButtonView({
broker: this._authenticationBroker
});
this._closeButton.render();
}
},
initializeFxaClient: function () {
if (! this._fxaClient) {
this._fxaClient = new FxaClient({
interTabChannel: this._interTabChannel,
authServerUrl: this._config.authServerUrl
});
}
},
initializeUser: function () {
if (! this._user) {
this._user = new User({
oAuthClientId: this._config.oAuthClientId,
profileClient: this._profileClient,
oAuthClient: this._oAuthClient,
fxaClient: this._fxaClient,
marketingEmailClient: this._marketingEmailClient,
assertion: this._assertionLibrary,
storage: this._getStorageInstance()
});
}
},
initializeNotifications: function () {
var notificationWebChannel =
new WebChannel(Constants.ACCOUNT_UPDATES_WEBCHANNEL_ID);
notificationWebChannel.initialize();
this._notifications = new Notifications({
tabChannel: this._interTabChannel,
iframeChannel: this._iframeChannel,
webChannel: notificationWebChannel
});
},
upgradeStorageFormats: function () {
return this._user.upgradeFromSession(Session, this._fxaClient);
},
initializeRouter: function () {
if (! this._router) {
this._router = new Router({
metrics: this._metrics,
language: this._config.language,
relier: this._relier,
broker: this._authenticationBroker,
fxaClient: this._fxaClient,
user: this._user,
interTabChannel: this._interTabChannel,
session: Session,
formPrefill: this._formPrefill,
notifications: this._notifications,
able: this._able
});
}
this._window.router = this._router;
},
allResourcesReady: function () {
var self = this;
return this._selectStartPage()
.then(function (startPage) {
// The IFrame cannot use pushState or else a page transition
// would cause the parent frame to redirect.
var usePushState = ! self._isInAnIframe();
if (! usePushState) {
// If pushState cannot be used, Backbone falls back to using
// the hashchange. Put the initial pathname onto the hash
// so the correct page loads.
self._window.location.hash = self._window.location.pathname;
}
// If a new start page is specified, do not attempt to render
// the route displayed in the URL because the user is
// immediately redirected
var isSilent = !! startPage;
self._history.start({ pushState: usePushState, silent: isSilent });
if (startPage) {
self._router.navigate(startPage);
}
});
},
_getErrorPage: function (err) {
if (OAuthErrors.is(err, 'MISSING_PARAMETER') ||
OAuthErrors.is(err, 'UNKNOWN_CLIENT')) {
var queryString = Url.objToSearchString({
message: OAuthErrors.toInterpolatedMessage(err, this._translator),
errno: err.errno,
namespace: err.namespace,
context: err.context,
param: err.param,
//jshint camelcase: false
client_id: err.client_id
});
return Constants.BAD_REQUEST_PAGE + queryString;
}
return Constants.INTERNAL_ERROR_PAGE;
},
_getStorageInstance: function () {
return Storage.factory('localStorage', this._window);
},
_isSync: function () {
return this._searchParam('service') === Constants.FX_DESKTOP_SYNC;
},
_isFxDesktopV1: function () {
return this._searchParam('context') === Constants.FX_DESKTOP_CONTEXT;
},
_isFxDesktopV2: function () {
// A user is signing into sync from within an iframe on a trusted
// web page. Automatically speak version 2 using WebChannels.
//
// A check for context=fx_desktop_v2 can be added when about:accounts
// is converted to use WebChannels.
return this._isSync() && this._isIframeContext();
},
_isFxDesktop: function () {
// In addition to the two obvious fx desktop choices, sync is always
// considered fx-desktop. If service=sync is on the URL, it's considered
// fx-desktop.
return this._isFxDesktopV1() || this._isFxDesktopV2() || this._isSync();
},
_isWebChannel: function () {
return !! (this._searchParam('webChannelId') || // signup/signin
(this._isOAuthVerificationSameBrowser() &&
Session.oauth && Session.oauth.webChannelId));
},
_isInAnIframe: function () {
return new Environment(this._window).isFramed();
},
_isIframeContext: function () {
return this._searchParam('context') === Constants.IFRAME_CONTEXT;
},
_isIframe: function () {
return this._isInAnIframe() && this._isIframeContext();
},
_isOAuth: function () {
// for /force_auth
return !! (this._searchParam('client_id') ||
// for verification flows
(this._searchParam('code') && this._searchParam('service')) ||
// for /oauth/signin or /oauth/signup
/oauth/.test(this._window.location.href));
},
_isOAuthVerificationSameBrowser: function () {
//jshint camelcase: false
var savedClientId = Session.oauth && Session.oauth.client_id;
return !! (this._searchParam('code') &&
(this._searchParam('service') === savedClientId));
},
_searchParam: function (name) {
return Url.searchParam(name, this._window.location.search);
},
_selectStartPage: function () {
var self = this;
return p().then(function () {
if (self._window.location.pathname === '/cookies_disabled') {
// If the user is already at the cookies_disabled page, don't even
// attempt the cookie check or else a blank screen is rendered if
// cookies are actually disabled.
return;
}
return self._configLoader.areCookiesEnabled(false, self._window)
.then(function (areCookiesEnabled) {
if (! areCookiesEnabled) {
return 'cookies_disabled';
}
});
});
},
_createMetrics: function (sampleRate, options) {
if (this._isAutomatedBrowser()) {
return new StorageMetrics(options);
} else if (isMetricsCollectionEnabled(sampleRate)) {
return new Metrics(options);
} else {
return new NullMetrics();
}
},
_isAutomatedBrowser: function () {
return this._searchParam('automatedBrowser') === 'true';
}
};
return Start;
});