This repository has been archived by the owner on Apr 3, 2019. It is now read-only.
/
app-start.js
720 lines (638 loc) · 22.5 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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
/* 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.
*/
define([
'underscore',
'backbone',
'lib/promise',
'lib/router',
'lib/translator',
'lib/session',
'lib/url',
'lib/config-loader',
'lib/screen-info',
'lib/metrics',
'lib/sentry',
'lib/storage-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/null',
'lib/channels/web',
'lib/storage',
'lib/able',
'lib/environment',
'lib/origin-check',
'lib/height-observer',
'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/fx-fennec-v1',
'models/auth_brokers/fx-ios-v1',
'models/auth_brokers/first-run',
'models/auth_brokers/web-channel',
'models/auth_brokers/redirect',
'models/auth_brokers/iframe',
'models/unique-user-id',
'models/user',
'models/form-prefill',
'models/notifications',
'views/close_button'
],
function (
_,
Backbone,
p,
Router,
Translator,
Session,
Url,
ConfigLoader,
ScreenInfo,
Metrics,
SentryMetrics,
StorageMetrics,
FxaClient,
Assertion,
Constants,
OAuthClient,
OAuthErrors,
AuthErrors,
ProfileClient,
MarketingEmailClient,
InterTabChannel,
IframeChannel,
NullChannel,
WebChannel,
Storage,
Able,
Environment,
OriginCheck,
HeightObserver,
Relier,
OAuthRelier,
FxDesktopRelier,
BaseAuthenticationBroker,
FxDesktopV1AuthenticationBroker,
FxDesktopV2AuthenticationBroker,
FxFennecV1AuthenticationBroker,
FxiOSV1AuthenticationBroker,
FirstRunAuthenticationBroker,
WebChannelAuthenticationBroker,
RedirectAuthenticationBroker,
IframeAuthenticationBroker,
UniqueUserId,
User,
FormPrefill,
Notifications,
CloseButtonView
) {
'use strict';
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._storage = options.storage || Storage;
this._history = options.history || Backbone.history;
this._configLoader = new ConfigLoader();
}
Start.prototype = {
// delay before redirecting to the error page to
// ensure metrics are reported to the backend.
ERROR_REDIRECT_TIMEOUT_MS: 1000,
startApp: function () {
var self = this;
// fetch both config and translations in parallel to speed up load.
return p.all([
this.initializeConfig(),
this.initializeL10n(),
this.initializeInterTabChannel()
])
.then(_.bind(this.allResourcesReady, this))
.fail(function (err) {
if (console && console.error) {
console.error('Critical error:');
console.error(String(err));
}
// if there is no error metrics set that means there was probably an error with app start
// therefore force error reporting to get error information
if (! self._sentryMetrics) {
self.enableSentryMetrics();
}
self._sentryMetrics.captureException(err);
if (self._metrics) {
self._metrics.logError(err);
}
// give a bit of time to flush the Sentry error logs,
// otherwise Safari Mobile redirects too quickly.
return p().delay(self.ERROR_REDIRECT_TIMEOUT_MS)
.then(function () {
if (self._metrics) {
return self._metrics.flush();
}
})
.then(function () {
//Something terrible happened. Let's bail.
var redirectTo = self._getErrorPage(err);
self._window.location.href = redirectTo;
});
});
},
initializeInterTabChannel: function () {
this._interTabChannel = new InterTabChannel();
},
initializeAble: function () {
this._able = new Able();
},
initializeConfig: function () {
return this._configLoader.fetch()
.then(_.bind(this.useConfig, this))
.then(_.bind(this.initializeAble, this))
.then(_.bind(this.initializeErrorMetrics, 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))
// depends on the authentication broker
.then(_.bind(this.initializeHeightObserver, 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);
},
initializeErrorMetrics: function () {
if (this._config && this._config.env && this._able) {
var abData = {
env: this._config.env,
uniqueUserId: this._getUniqueUserId()
};
var abChoose = this._able.choose('sentryEnabled', abData);
if (abChoose) {
this.enableSentryMetrics();
}
}
},
enableSentryMetrics: function () {
this._sentryMetrics = new SentryMetrics(this._window.location.host);
},
initializeL10n: function () {
this._translator = this._window.translator = new Translator();
return this._translator.fetch();
},
initializeMetrics: function () {
var isSampledUser = this._able.choose('isSampledUser', {
env: this._config.env,
uniqueUserId: this._getUniqueUserId()
});
var relier = this._relier;
var screenInfo = new ScreenInfo(this._window);
this._metrics = this._createMetrics({
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,
isSampledUser: isSampledUser,
uniqueUserId: this._getUniqueUserId(),
utmCampaign: relier.get('utmCampaign'),
utmContent: relier.get('utmContent'),
utmMedium: relier.get('utmMedium'),
utmSource: relier.get('utmSource'),
utmTerm: relier.get('utmTerm')
});
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({
window: self._window
});
var allowedOrigins = self._getAllowedParentOrigins();
return originCheck.getOrigin(self._window.parent, allowedOrigins);
},
initializeIframeChannel: function () {
var self = this;
if (! self._isInAnIframe()) {
// Create a NullChannel in case any dependencies require it, such
// as when the FirstRunAuthenticationBroker is used in functional
// tests. The firstrun tests don't actually use an iframe, so the
// real IframeChannel is not created.
self._iframeChannel = new NullChannel();
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 () {
if (! this._authenticationBroker) {
if (this._isFirstRun()) {
this._authenticationBroker = new FirstRunAuthenticationBroker({
iframeChannel: this._iframeChannel,
relier: this._relier,
window: this._window
});
} else if (this._isFxFennecV1()) {
this._authenticationBroker = new FxFennecV1AuthenticationBroker({
window: this._window,
relier: this._relier
});
} else if (this._isFxDesktopV2()) {
this._authenticationBroker = new FxDesktopV2AuthenticationBroker({
window: this._window,
relier: this._relier
});
} else if (this._isFxDesktopV1()) {
this._authenticationBroker = new FxDesktopV1AuthenticationBroker({
window: this._window,
relier: this._relier
});
} else if (this._isFxiOSV1()) {
this._authenticationBroker = new FxiOSV1AuthenticationBroker({
window: this._window,
relier: this._relier
});
} 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,
metrics: this._metrics
});
} else {
this._authenticationBroker = new BaseAuthenticationBroker({
relier: this._relier
});
}
var metrics = this._metrics;
var win = this._window;
this._authenticationBroker.on('error', function (err) {
win.console.error('broker error', String(err));
metrics.logError(err);
});
metrics.setBrokerType(this._authenticationBroker.type);
return this._authenticationBroker.fetch();
}
},
initializeHeightObserver: function () {
var self = this;
if (self._isInAnIframe()) {
var heightObserver = new HeightObserver({
target: self._window.document.body,
window: self._window
});
heightObserver.on('change', function (height) {
self._iframeChannel.send('resize', { height: height });
});
heightObserver.start();
}
},
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(),
uniqueUserId: this._getUniqueUserId()
});
}
},
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
});
},
_uniqueUserId: null,
_getUniqueUserId: function () {
if (! this._uniqueUserId) {
/**
* Sets a UUID value that is unrelated to any account information.
* This value is useful to determine if the logged out user qualifies
* for A/B testing or metrics.
*/
this._uniqueUserId = new UniqueUserId({
window: this._window
}).get('uniqueUserId');
}
return this._uniqueUserId;
},
upgradeStorageFormats: function () {
return this._user.upgradeFromSession(Session, this._fxaClient);
},
initializeRouter: function () {
if (! this._router) {
this._router = new Router({
metrics: this._metrics,
sentryMetrics: this._sentryMetrics,
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 () {
// The IFrame cannot use pushState or else a page transition
// would cause the parent frame to redirect.
var usePushState = ! this._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.
this._window.location.hash = this._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 startPage = this._selectStartPage();
var isSilent = !! startPage;
this._history.start({ pushState: usePushState, silent: isSilent });
if (startPage) {
this._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,
client_id: err.client_id //eslint-disable-line camelcase
});
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.SYNC_SERVICE;
},
_isFxFennecV1: function () {
return this._searchParam('context') === Constants.FX_FENNEC_V1_CONTEXT;
},
_isFxDesktopV1: function () {
return this._searchParam('context') === Constants.FX_DESKTOP_V1_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()) ||
(this._searchParam('context') === Constants.FX_DESKTOP_V2_CONTEXT);
},
_isFxiOSV1: function () {
return this._searchParam('context') === Constants.FX_IOS_V1_CONTEXT;
},
_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._isFxiOSV1() ||
this._isSync();
},
_isFirstRun: function () {
return this._isFxDesktopV2() && this._isIframeContext();
},
_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 () {
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 () {
if (this._window.location.pathname !== '/cookies_disabled' &&
! this._storage.isLocalStorageEnabled(this._window)) {
return 'cookies_disabled';
}
},
_createMetrics: function (options) {
if (this._isAutomatedBrowser()) {
return new StorageMetrics(options);
}
return new Metrics(options);
},
_isAutomatedBrowser: function () {
return this._searchParam('automatedBrowser') === 'true';
}
};
return Start;
});