This repository has been archived by the owner on Aug 4, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathFxAccounts.jsm
1776 lines (1617 loc) · 63 KB
/
FxAccounts.jsm
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
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* 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/. */
"use strict";
this.EXPORTED_SYMBOLS = ["fxAccounts", "FxAccounts"];
const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
Cu.importGlobalProperties(["URL"]);
Cu.import("resource://gre/modules/Log.jsm");
Cu.import("resource://gre/modules/Promise.jsm");
Cu.import("resource://services-common/utils.js");
Cu.import("resource://services-common/rest.js");
Cu.import("resource://services-crypto/utils.js");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Timer.jsm");
Cu.import("resource://gre/modules/Task.jsm");
Cu.import("resource://gre/modules/FxAccountsStorage.jsm");
Cu.import("resource://gre/modules/FxAccountsCommon.js");
XPCOMUtils.defineLazyModuleGetter(this, "FxAccountsClient",
"resource://gre/modules/FxAccountsClient.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "FxAccountsConfig",
"resource://gre/modules/FxAccountsConfig.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "jwcrypto",
"resource://gre/modules/services-crypto/jwcrypto.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "FxAccountsOAuthGrantClient",
"resource://gre/modules/FxAccountsOAuthGrantClient.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "FxAccountsProfile",
"resource://gre/modules/FxAccountsProfile.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Utils",
"resource://services-sync/util.js");
// All properties exposed by the public FxAccounts API.
var publicProperties = [
"accountStatus",
"checkVerificationStatus",
"getAccountsClient",
"getAssertion",
"getDeviceId",
"getDeviceList",
"getKeys",
"getOAuthToken",
"getProfileCache",
"getSignedInUser",
"getSignedInUserProfile",
"handleDeviceDisconnection",
"invalidateCertificate",
"loadAndPoll",
"localtimeOffsetMsec",
"notifyDevices",
"now",
"promiseAccountsChangeProfileURI",
"promiseAccountsForceSigninURI",
"promiseAccountsManageURI",
"promiseAccountsManageDevicesURI",
"promiseAccountsSignUpURI",
"promiseAccountsSignInURI",
"removeCachedOAuthToken",
"requiresHttps",
"resendVerificationEmail",
"resetCredentials",
"sessionStatus",
"setProfileCache",
"setSignedInUser",
"signOut",
"updateDeviceRegistration",
"deleteDeviceRegistration",
"updateUserAccountData",
"whenVerified",
];
// An AccountState object holds all state related to one specific account.
// Only one AccountState is ever "current" in the FxAccountsInternal object -
// whenever a user logs out or logs in, the current AccountState is discarded,
// making it impossible for the wrong state or state data to be accidentally
// used.
// In addition, it has some promise-related helpers to ensure that if an
// attempt is made to resolve a promise on a "stale" state (eg, if an
// operation starts, but a different user logs in before the operation
// completes), the promise will be rejected.
// It is intended to be used thusly:
// somePromiseBasedFunction: function() {
// let currentState = this.currentAccountState;
// return someOtherPromiseFunction().then(
// data => currentState.resolve(data)
// );
// }
// If the state has changed between the function being called and the promise
// being resolved, the .resolve() call will actually be rejected.
var AccountState = this.AccountState = function(storageManager) {
this.storageManager = storageManager;
this.promiseInitialized = this.storageManager.getAccountData().then(data => {
this.oauthTokens = data && data.oauthTokens ? data.oauthTokens : {};
}).catch(err => {
log.error("Failed to initialize the storage manager", err);
// Things are going to fall apart, but not much we can do about it here.
});
};
AccountState.prototype = {
oauthTokens: null,
whenVerifiedDeferred: null,
whenKeysReadyDeferred: null,
// If the storage manager has been nuked then we are no longer current.
get isCurrent() {
return this.storageManager != null;
},
abort() {
if (this.whenVerifiedDeferred) {
this.whenVerifiedDeferred.reject(
new Error("Verification aborted; Another user signing in"));
this.whenVerifiedDeferred = null;
}
if (this.whenKeysReadyDeferred) {
this.whenKeysReadyDeferred.reject(
new Error("Verification aborted; Another user signing in"));
this.whenKeysReadyDeferred = null;
}
this.cert = null;
this.keyPair = null;
this.oauthTokens = null;
// Avoid finalizing the storageManager multiple times (ie, .signOut()
// followed by .abort())
if (!this.storageManager) {
return Promise.resolve();
}
let storageManager = this.storageManager;
this.storageManager = null;
return storageManager.finalize();
},
// Clobber all cached data and write that empty data to storage.
signOut() {
this.cert = null;
this.keyPair = null;
this.oauthTokens = null;
let storageManager = this.storageManager;
this.storageManager = null;
return storageManager.deleteAccountData().then(() => {
return storageManager.finalize();
});
},
// Get user account data. Optionally specify explicit field names to fetch
// (and note that if you require an in-memory field you *must* specify the
// field name(s).)
getUserAccountData(fieldNames = null) {
if (!this.isCurrent) {
return Promise.reject(new Error("Another user has signed in"));
}
return this.storageManager.getAccountData(fieldNames).then(result => {
return this.resolve(result);
});
},
updateUserAccountData(updatedFields) {
if (!this.isCurrent) {
return Promise.reject(new Error("Another user has signed in"));
}
return this.storageManager.updateAccountData(updatedFields);
},
resolve(result) {
if (!this.isCurrent) {
log.info("An accountState promise was resolved, but was actually rejected" +
" due to a different user being signed in. Originally resolved" +
" with", result);
return Promise.reject(new Error("A different user signed in"));
}
return Promise.resolve(result);
},
reject(error) {
// It could be argued that we should just let it reject with the original
// error - but this runs the risk of the error being (eg) a 401, which
// might cause the consumer to attempt some remediation and cause other
// problems.
if (!this.isCurrent) {
log.info("An accountState promise was rejected, but we are ignoring that" +
"reason and rejecting it due to a different user being signed in." +
"Originally rejected with", error);
return Promise.reject(new Error("A different user signed in"));
}
return Promise.reject(error);
},
// Abstractions for storage of cached tokens - these are all sync, and don't
// handle revocation etc - it's just storage (and the storage itself is async,
// but we don't return the storage promises, so it *looks* sync)
// These functions are sync simply so we can handle "token races" - when there
// are multiple in-flight requests for the same scope, we can detect this
// and revoke the redundant token.
// A preamble for the cache helpers...
_cachePreamble() {
if (!this.isCurrent) {
throw new Error("Another user has signed in");
}
},
// Set a cached token. |tokenData| must have a 'token' element, but may also
// have additional fields (eg, it probably specifies the server to revoke
// from). The 'get' functions below return the entire |tokenData| value.
setCachedToken(scopeArray, tokenData) {
this._cachePreamble();
if (!tokenData.token) {
throw new Error("No token");
}
let key = getScopeKey(scopeArray);
this.oauthTokens[key] = tokenData;
// And a background save...
this._persistCachedTokens();
},
// Return data for a cached token or null (or throws on bad state etc)
getCachedToken(scopeArray) {
this._cachePreamble();
let key = getScopeKey(scopeArray);
let result = this.oauthTokens[key];
if (result) {
// later we might want to check an expiry date - but we currently
// have no such concept, so just return it.
log.trace("getCachedToken returning cached token");
return result;
}
return null;
},
// Remove a cached token from the cache. Does *not* revoke it from anywhere.
// Returns the entire token entry if found, null otherwise.
removeCachedToken(token) {
this._cachePreamble();
let data = this.oauthTokens;
for (let [key, tokenValue] of Object.entries(data)) {
if (tokenValue.token == token) {
delete data[key];
// And a background save...
this._persistCachedTokens();
return tokenValue;
}
}
return null;
},
// A hook-point for tests. Returns a promise that's ignored in most cases
// (notable exceptions are tests and when we explicitly are saving the entire
// set of user data.)
_persistCachedTokens() {
this._cachePreamble();
return this.updateUserAccountData({ oauthTokens: this.oauthTokens }).catch(err => {
log.error("Failed to update cached tokens", err);
});
},
}
/* Given an array of scopes, make a string key by normalizing. */
function getScopeKey(scopeArray) {
let normalizedScopes = scopeArray.map(item => item.toLowerCase());
return normalizedScopes.sort().join("|");
}
/**
* Copies properties from a given object to another object.
*
* @param from (object)
* The object we read property descriptors from.
* @param to (object)
* The object that we set property descriptors on.
* @param options (object) (optional)
* {keys: [...]}
* Lets the caller pass the names of all properties they want to be
* copied. Will copy all properties of the given source object by
* default.
* {bind: object}
* Lets the caller specify the object that will be used to .bind()
* all function properties we find to. Will bind to the given target
* object by default.
*/
function copyObjectProperties(from, to, opts = {}) {
let keys = (opts && opts.keys) || Object.keys(from);
let thisArg = (opts && opts.bind) || to;
for (let prop of keys) {
let desc = Object.getOwnPropertyDescriptor(from, prop);
if (typeof(desc.value) == "function") {
desc.value = desc.value.bind(thisArg);
}
if (desc.get) {
desc.get = desc.get.bind(thisArg);
}
if (desc.set) {
desc.set = desc.set.bind(thisArg);
}
Object.defineProperty(to, prop, desc);
}
}
function urlsafeBase64Encode(key) {
return ChromeUtils.base64URLEncode(new Uint8Array(key), { pad: false });
}
/**
* The public API's constructor.
*/
this.FxAccounts = function(mockInternal) {
let internal = new FxAccountsInternal();
let external = {};
// Copy all public properties to the 'external' object.
let prototype = FxAccountsInternal.prototype;
let options = {keys: publicProperties, bind: internal};
copyObjectProperties(prototype, external, options);
// Copy all of the mock's properties to the internal object.
if (mockInternal && !mockInternal.onlySetInternal) {
copyObjectProperties(mockInternal, internal);
}
if (mockInternal) {
// Exposes the internal object for testing only.
external.internal = internal;
}
if (!internal.fxaPushService) {
// internal.fxaPushService option is used in testing.
// Otherwise we load the service lazily.
XPCOMUtils.defineLazyGetter(internal, "fxaPushService", function() {
return Components.classes["@mozilla.org/fxaccounts/push;1"]
.getService(Components.interfaces.nsISupports)
.wrappedJSObject;
});
}
// wait until after the mocks are setup before initializing.
internal.initialize();
return Object.freeze(external);
}
/**
* The internal API's constructor.
*/
function FxAccountsInternal() {
// Make a local copy of this constant so we can mock it in testing
this.POLL_SESSION = POLL_SESSION;
// All significant initialization should be done in the initialize() method
// below as it helps with testing.
}
/**
* The internal API's prototype.
*/
FxAccountsInternal.prototype = {
// The timeout (in ms) we use to poll for a verified mail for the first 2 mins.
VERIFICATION_POLL_TIMEOUT_INITIAL: 15000, // 15 seconds
// And how often we poll after the first 2 mins.
VERIFICATION_POLL_TIMEOUT_SUBSEQUENT: 30000, // 30 seconds.
// The current version of the device registration, we use this to re-register
// devices after we update what we send on device registration.
DEVICE_REGISTRATION_VERSION: 2,
_fxAccountsClient: null,
// All significant initialization should be done in this initialize() method,
// as it's called after this object has been mocked for tests.
initialize() {
this.currentTimer = null;
this.currentAccountState = this.newAccountState();
},
get fxAccountsClient() {
if (!this._fxAccountsClient) {
this._fxAccountsClient = new FxAccountsClient();
}
return this._fxAccountsClient;
},
// The profile object used to fetch the actual user profile.
_profile: null,
get profile() {
if (!this._profile) {
let profileServerUrl = Services.urlFormatter.formatURLPref("identity.fxaccounts.remote.profile.uri");
this._profile = new FxAccountsProfile({
fxa: this,
profileServerUrl,
});
}
return this._profile;
},
// A hook-point for tests who may want a mocked AccountState or mocked storage.
newAccountState(credentials) {
let storage = new FxAccountsStorageManager();
storage.initialize(credentials);
return new AccountState(storage);
},
/**
* Send a message to a set of devices in the same account
*
* @return Promise
*/
notifyDevices(deviceIds, payload, TTL) {
if (!Array.isArray(deviceIds)) {
deviceIds = [deviceIds];
}
return this.currentAccountState.getUserAccountData()
.then(data => {
if (!data) {
throw this._error(ERROR_NO_ACCOUNT);
}
if (!data.sessionToken) {
throw this._error(ERROR_AUTH_ERROR,
"notifyDevices called without a session token");
}
return this.fxAccountsClient.notifyDevices(data.sessionToken, deviceIds,
payload, TTL);
});
},
/**
* Return the current time in milliseconds as an integer. Allows tests to
* manipulate the date to simulate certificate expiration.
*/
now() {
return this.fxAccountsClient.now();
},
getAccountsClient() {
return this.fxAccountsClient;
},
/**
* Return clock offset in milliseconds, as reported by the fxAccountsClient.
* This can be overridden for testing.
*
* The offset is the number of milliseconds that must be added to the client
* clock to make it equal to the server clock. For example, if the client is
* five minutes ahead of the server, the localtimeOffsetMsec will be -300000.
*/
get localtimeOffsetMsec() {
return this.fxAccountsClient.localtimeOffsetMsec;
},
/**
* Ask the server whether the user's email has been verified
*/
checkEmailStatus: function checkEmailStatus(sessionToken, options = {}) {
if (!sessionToken) {
return Promise.reject(new Error(
"checkEmailStatus called without a session token"));
}
return this.fxAccountsClient.recoveryEmailStatus(sessionToken,
options).catch(error => this._handleTokenError(error));
},
/**
* Once the user's email is verified, we can request the keys
*/
fetchKeys: function fetchKeys(keyFetchToken) {
log.debug("fetchKeys: " + !!keyFetchToken);
if (logPII) {
log.debug("fetchKeys - the token is " + keyFetchToken);
}
return this.fxAccountsClient.accountKeys(keyFetchToken);
},
// set() makes sure that polling is happening, if necessary.
// get() does not wait for verification, and returns an object even if
// unverified. The caller of get() must check .verified .
// The "fxaccounts:onverified" event will fire only when the verified
// state goes from false to true, so callers must register their observer
// and then call get(). In particular, it will not fire when the account
// was found to be verified in a previous boot: if our stored state says
// the account is verified, the event will never fire. So callers must do:
// register notification observer (go)
// userdata = get()
// if (userdata.verified()) {go()}
/**
* Get the user currently signed in to Firefox Accounts.
*
* @return Promise
* The promise resolves to the credentials object of the signed-in user:
* {
* email: The user's email address
* uid: The user's unique id
* sessionToken: Session for the FxA server
* kA: An encryption key from the FxA server
* kB: An encryption key derived from the user's FxA password
* verified: email verification status
* authAt: The time (seconds since epoch) that this record was
* authenticated
* }
* or null if no user is signed in.
*/
getSignedInUser: function getSignedInUser() {
let currentState = this.currentAccountState;
return currentState.getUserAccountData().then(data => {
if (!data) {
return null;
}
if (!this.isUserEmailVerified(data)) {
// If the email is not verified, start polling for verification,
// but return null right away. We don't want to return a promise
// that might not be fulfilled for a long time.
this.startVerifiedCheck(data);
}
return data;
}).then(result => currentState.resolve(result));
},
/**
* Set the current user signed in to Firefox Accounts.
*
* @param credentials
* The credentials object obtained by logging in or creating
* an account on the FxA server:
* {
* authAt: The time (seconds since epoch) that this record was
* authenticated
* email: The users email address
* keyFetchToken: a keyFetchToken which has not yet been used
* sessionToken: Session for the FxA server
* uid: The user's unique id
* unwrapBKey: used to unwrap kB, derived locally from the
* password (not revealed to the FxA server)
* verified: true/false
* }
* @return Promise
* The promise resolves to null when the data is saved
* successfully and is rejected on error.
*/
setSignedInUser: function setSignedInUser(credentials) {
log.debug("setSignedInUser - aborting any existing flows");
return this.getSignedInUser().then(signedInUser => {
if (signedInUser) {
return this.deleteDeviceRegistration(signedInUser.sessionToken, signedInUser.deviceId);
}
return null;
}).then(() =>
this.abortExistingFlow()
).then(() => {
let currentAccountState = this.currentAccountState = this.newAccountState(
Cu.cloneInto(credentials, {}) // Pass a clone of the credentials object.
);
// This promise waits for storage, but not for verification.
// We're telling the caller that this is durable now (although is that
// really something we should commit to? Why not let the write happen in
// the background? Already does for updateAccountData ;)
return currentAccountState.promiseInitialized.then(() => {
// Starting point for polling if new user
if (!this.isUserEmailVerified(credentials)) {
this.startVerifiedCheck(credentials);
}
return this.updateDeviceRegistration();
}).then(() => {
Services.telemetry.getHistogramById("FXA_CONFIGURED").add(1);
this.notifyObservers(ONLOGIN_NOTIFICATION);
}).then(() => {
return currentAccountState.resolve();
});
});
},
/**
* Update account data for the currently signed in user.
*
* @param credentials
* The credentials object containing the fields to be updated.
* This object must contain |email| and |uid| fields and they must
* match the currently signed in user.
*/
updateUserAccountData(credentials) {
log.debug("updateUserAccountData called with fields", Object.keys(credentials));
if (logPII) {
log.debug("updateUserAccountData called with data", credentials);
}
let currentAccountState = this.currentAccountState;
return currentAccountState.promiseInitialized.then(() => {
return currentAccountState.getUserAccountData(["email", "uid"]);
}).then(existing => {
if (existing.email != credentials.email || existing.uid != credentials.uid) {
throw new Error("The specified credentials aren't for the current user");
}
// We need to nuke email and uid as storage will complain if we try and
// update them (even when the value is the same)
credentials = Cu.cloneInto(credentials, {}); // clone it first
delete credentials.email;
delete credentials.uid;
return currentAccountState.updateUserAccountData(credentials);
});
},
/**
* returns a promise that fires with the assertion. If there is no verified
* signed-in user, fires with null.
*/
getAssertion: function getAssertion(audience) {
return this._getAssertion(audience);
},
// getAssertion() is "public" so screws with our mock story. This
// implementation method *can* be (and is) mocked by tests.
_getAssertion: function _getAssertion(audience) {
log.debug("enter getAssertion()");
let currentState = this.currentAccountState;
return currentState.getUserAccountData().then(data => {
if (!data) {
// No signed-in user
return null;
}
if (!this.isUserEmailVerified(data)) {
// Signed-in user has not verified email
return null;
}
if (!data.sessionToken) {
// can't get a signed certificate without a session token. This
// can happen if we request an assertion after clearing an invalid
// session token from storage.
throw this._error(ERROR_AUTH_ERROR, "getAssertion called without a session token");
}
return this.getKeypairAndCertificate(currentState).then(
({keyPair, certificate}) => {
return this.getAssertionFromCert(data, keyPair, certificate, audience);
}
);
}).catch(err =>
this._handleTokenError(err)
).then(result => currentState.resolve(result));
},
/**
* Invalidate the FxA certificate, so that it will be refreshed from the server
* the next time it is needed.
*/
invalidateCertificate() {
return this.currentAccountState.updateUserAccountData({ cert: null });
},
getDeviceId() {
return this.currentAccountState.getUserAccountData()
.then(data => {
if (data) {
if (!data.deviceId || !data.deviceRegistrationVersion ||
data.deviceRegistrationVersion < this.DEVICE_REGISTRATION_VERSION) {
// There is no device id or the device registration is outdated.
// Either way, we should register the device with FxA
// before returning the id to the caller.
return this._registerOrUpdateDevice(data);
}
// Return the device id that we already registered with the server.
return data.deviceId;
}
// Without a signed-in user, there can be no device id.
return null;
});
},
async getDeviceList() {
let accountData = await this._getVerifiedAccountOrReject();
return this.fxAccountsClient.getDeviceList(accountData.sessionToken);
},
/**
* Resend the verification email fot the currently signed-in user.
*
*/
resendVerificationEmail: function resendVerificationEmail() {
let currentState = this.currentAccountState;
return this.getSignedInUser().then(data => {
// If the caller is asking for verification to be re-sent, and there is
// no signed-in user to begin with, this is probably best regarded as an
// error.
if (data) {
if (!data.sessionToken) {
return Promise.reject(new Error(
"resendVerificationEmail called without a session token"));
}
this.pollEmailStatus(currentState, data.sessionToken, "start");
return this.fxAccountsClient.resendVerificationEmail(
data.sessionToken).catch(err => this._handleTokenError(err));
}
throw new Error("Cannot resend verification email; no signed-in user");
});
},
/*
* Reset state such that any previous flow is canceled.
*/
abortExistingFlow: function abortExistingFlow() {
if (this.currentTimer) {
log.debug("Polling aborted; Another user signing in");
clearTimeout(this.currentTimer);
this.currentTimer = 0;
}
if (this._profile) {
this._profile.tearDown();
this._profile = null;
}
// We "abort" the accountState and assume our caller is about to throw it
// away and replace it with a new one.
return this.currentAccountState.abort();
},
accountStatus: function accountStatus() {
return this.currentAccountState.getUserAccountData().then(data => {
if (!data) {
return false;
}
return this.fxAccountsClient.accountStatus(data.uid);
});
},
checkVerificationStatus() {
log.trace("checkVerificationStatus");
let currentState = this.currentAccountState;
return currentState.getUserAccountData().then(data => {
if (!data) {
log.trace("checkVerificationStatus - no user data");
return null;
}
// Always check the verification status, even if the local state indicates
// we're already verified. If the user changed their password, the check
// will fail, and we'll enter the reauth state.
log.trace("checkVerificationStatus - forcing verification status check");
return this.pollEmailStatus(currentState, data.sessionToken, "push");
});
},
_destroyOAuthToken(tokenData) {
let client = new FxAccountsOAuthGrantClient({
serverURL: tokenData.server,
client_id: FX_OAUTH_CLIENT_ID
});
return client.destroyToken(tokenData.token)
},
_destroyAllOAuthTokens(tokenInfos) {
// let's just destroy them all in parallel...
let promises = [];
for (let tokenInfo of Object.values(tokenInfos || {})) {
promises.push(this._destroyOAuthToken(tokenInfo));
}
return Promise.all(promises);
},
signOut: function signOut(localOnly) {
let currentState = this.currentAccountState;
let sessionToken;
let tokensToRevoke;
let deviceId;
return currentState.getUserAccountData().then(data => {
// Save the session token, tokens to revoke and the
// device id for use in the call to signOut below.
if (data) {
sessionToken = data.sessionToken;
tokensToRevoke = data.oauthTokens;
deviceId = data.deviceId;
}
return this._signOutLocal();
}).then(() => {
// FxAccountsManager calls here, then does its own call
// to FxAccountsClient.signOut().
if (!localOnly) {
// Wrap this in a promise so *any* errors in signOut won't
// block the local sign out. This is *not* returned.
Promise.resolve().then(() => {
// This can happen in the background and shouldn't block
// the user from signing out. The server must tolerate
// clients just disappearing, so this call should be best effort.
if (sessionToken) {
return this._signOutServer(sessionToken, deviceId);
}
log.warn("Missing session token; skipping remote sign out");
return null;
}).catch(err => {
log.error("Error during remote sign out of Firefox Accounts", err);
}).then(() => {
return this._destroyAllOAuthTokens(tokensToRevoke);
}).catch(err => {
log.error("Error during destruction of oauth tokens during signout", err);
}).then(() => {
FxAccountsConfig.resetConfigURLs();
// just for testing - notifications are cheap when no observers.
this.notifyObservers("testhelper-fxa-signout-complete");
})
} else {
// We want to do this either way -- but if we're signing out remotely we
// need to wait until we destroy the oauth tokens if we want that to succeed.
FxAccountsConfig.resetConfigURLs();
}
}).then(() => {
this.notifyObservers(ONLOGOUT_NOTIFICATION);
});
},
/**
* This function should be called in conjunction with a server-side
* signOut via FxAccountsClient.
*/
_signOutLocal: function signOutLocal() {
let currentAccountState = this.currentAccountState;
return currentAccountState.signOut().then(() => {
// this "aborts" this.currentAccountState but doesn't make a new one.
return this.abortExistingFlow();
}).then(() => {
this.currentAccountState = this.newAccountState();
return this.currentAccountState.promiseInitialized;
});
},
_signOutServer(sessionToken, deviceId) {
// For now we assume the service being logged out from is Sync, so
// we must tell the server to either destroy the device or sign out
// (if no device exists). We might need to revisit this when this
// FxA code is used in a context that isn't Sync.
const options = { service: "sync" };
if (deviceId) {
log.debug("destroying device, session and unsubscribing from FxA push");
return this.deleteDeviceRegistration(sessionToken, deviceId);
}
log.debug("destroying session");
return this.fxAccountsClient.signOut(sessionToken, options);
},
/**
* Check the status of the current session using cached credentials.
*
* @return Promise
* Resolves with a boolean indicating if the session is still valid
*/
sessionStatus() {
return this.getSignedInUser().then(data => {
if (!data.sessionToken) {
return Promise.reject(new Error(
"sessionStatus called without a session token"));
}
return this.fxAccountsClient.sessionStatus(data.sessionToken);
});
},
/**
* Fetch encryption keys for the signed-in-user from the FxA API server.
*
* Not for user consumption. Exists to cause the keys to be fetch.
*
* Returns user data so that it can be chained with other methods.
*
* @return Promise
* The promise resolves to the credentials object of the signed-in user:
* {
* email: The user's email address
* uid: The user's unique id
* sessionToken: Session for the FxA server
* kA: An encryption key from the FxA server
* kB: An encryption key derived from the user's FxA password
* verified: email verification status
* }
* or null if no user is signed in
*/
getKeys() {
let currentState = this.currentAccountState;
return currentState.getUserAccountData().then((userData) => {
if (!userData) {
throw new Error("Can't get keys; User is not signed in");
}
if (userData.kA && userData.kB) {
return userData;
}
if (!currentState.whenKeysReadyDeferred) {
currentState.whenKeysReadyDeferred = Promise.defer();
if (userData.keyFetchToken) {
this.fetchAndUnwrapKeys(userData.keyFetchToken).then(
(dataWithKeys) => {
if (!dataWithKeys.kA || !dataWithKeys.kB) {
currentState.whenKeysReadyDeferred.reject(
new Error("user data missing kA or kB")
);
return;
}
currentState.whenKeysReadyDeferred.resolve(dataWithKeys);
},
(err) => {
currentState.whenKeysReadyDeferred.reject(err);
}
);
} else {
currentState.whenKeysReadyDeferred.reject("No keyFetchToken");
}
}
return currentState.whenKeysReadyDeferred.promise;
}).catch(err =>
this._handleTokenError(err)
).then(result => currentState.resolve(result));
},
fetchAndUnwrapKeys(keyFetchToken) {
if (logPII) {
log.debug("fetchAndUnwrapKeys: token: " + keyFetchToken);
}
let currentState = this.currentAccountState;
return Task.spawn(function* task() {
// Sign out if we don't have a key fetch token.
if (!keyFetchToken) {
log.warn("improper fetchAndUnwrapKeys() call: token missing");
yield this.signOut();
return null;
}
let {kA, wrapKB} = yield this.fetchKeys(keyFetchToken);
let data = yield currentState.getUserAccountData();
// Sanity check that the user hasn't changed out from under us
if (data.keyFetchToken !== keyFetchToken) {
throw new Error("Signed in user changed while fetching keys!");
}
// Next statements must be synchronous until we setUserAccountData
// so that we don't risk getting into a weird state.
let kB_hex = CryptoUtils.xor(CommonUtils.hexToBytes(data.unwrapBKey),
wrapKB);
if (logPII) {
log.debug("kB_hex: " + kB_hex);
}
let updateData = {
kA: CommonUtils.bytesAsHex(kA),
kB: CommonUtils.bytesAsHex(kB_hex),
keyFetchToken: null, // null values cause the item to be removed.
unwrapBKey: null,
}
log.debug("Keys Obtained: kA=" + !!updateData.kA + ", kB=" + !!updateData.kB);
if (logPII) {
log.debug("Keys Obtained: kA=" + updateData.kA + ", kB=" + updateData.kB);
}
yield currentState.updateUserAccountData(updateData);
// We are now ready for business. This should only be invoked once
// per setSignedInUser(), regardless of whether we've rebooted since
// setSignedInUser() was called.
this.notifyObservers(ONVERIFIED_NOTIFICATION);
return currentState.getUserAccountData();
}.bind(this)).then(result => currentState.resolve(result));
},
getAssertionFromCert(data, keyPair, cert, audience) {
log.debug("getAssertionFromCert");
let d = Promise.defer();
let options = {
duration: ASSERTION_LIFETIME,
localtimeOffsetMsec: this.localtimeOffsetMsec,
now: this.now()
};
let currentState = this.currentAccountState;
// "audience" should look like "http://123done.org".
// The generated assertion will expire in two minutes.
jwcrypto.generateAssertion(cert, keyPair, audience, options, (err, signed) => {
if (err) {
log.error("getAssertionFromCert: " + err);
d.reject(err);
} else {
log.debug("getAssertionFromCert returning signed: " + !!signed);
if (logPII) {
log.debug("getAssertionFromCert returning signed: " + signed);
}
d.resolve(signed);
}
});
return d.promise.then(result => currentState.resolve(result));
},
getCertificateSigned(sessionToken, serializedPublicKey, lifetime) {