-
Notifications
You must be signed in to change notification settings - Fork 875
/
rpchandler.js
3028 lines (2733 loc) · 107 KB
/
rpchandler.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
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
/**
* @license
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Utility for handling RPC requests to server.
*/
goog.provide('fireauth.RpcHandler');
goog.provide('fireauth.RpcHandler.ApiMethodHandler');
goog.provide('fireauth.RpcHandler.VerifyAssertionData');
goog.provide('fireauth.XmlHttpFactory');
goog.require('fireauth.AuthError');
goog.require('fireauth.AuthErrorWithCredential');
goog.require('fireauth.authenum.Error');
goog.require('fireauth.constants');
goog.require('fireauth.idp');
goog.require('fireauth.idp.ProviderId');
goog.require('fireauth.object');
goog.require('fireauth.util');
goog.require('goog.Promise');
goog.require('goog.Uri');
goog.require('goog.html.TrustedResourceUrl');
goog.require('goog.json');
goog.require('goog.net.CorsXmlHttpFactory');
goog.require('goog.net.EventType');
goog.require('goog.net.FetchXmlHttpFactory');
goog.require('goog.net.XhrIo');
goog.require('goog.net.XmlHttpFactory');
goog.require('goog.net.jsloader');
goog.require('goog.object');
goog.require('goog.string.Const');
/**
* Firebase Auth XmlHttpRequest factory. This is useful for environments like
* Node.js where XMLHttpRequest does not exist. XmlHttpFactory would be
* initialized using the polyfill XMLHttpRequest module.
* @param {function(new:XMLHttpRequest)} xmlHttpRequest The xmlHttpRequest
* constructor.
* @constructor
* @extends {goog.net.XmlHttpFactory}
* @final
*/
fireauth.XmlHttpFactory = function(xmlHttpRequest) {
/**
* @private {function(new:XMLHttpRequest)} The underlying XHR reference.
*/
this.xmlHttpRequest_ = xmlHttpRequest;
fireauth.XmlHttpFactory.base(this, 'constructor');
};
goog.inherits(fireauth.XmlHttpFactory, goog.net.XmlHttpFactory);
/**
* @return {!goog.net.XhrLike|!XMLHttpRequest} A new XhrLike instance.
* @override
*/
fireauth.XmlHttpFactory.prototype.createInstance = function() {
return new this.xmlHttpRequest_();
};
/**
* @return {!Object} Options describing how XHR objects obtained from this
* factory should be used.
* @override
*/
fireauth.XmlHttpFactory.prototype.internalGetOptions = function() {
return {};
};
/**
* Creates an RPC request handler for the project specified by the API key.
*
* @param {string} apiKey The API key.
* @param {?Object=} opt_config The RPC request processor configuration.
* @param {?string=} opt_firebaseClientVersion The optional Firebase client
* version to log with requests to Firebase Auth server.
* @constructor
*/
fireauth.RpcHandler = function(apiKey, opt_config, opt_firebaseClientVersion) {
/** @private {string} The project API key. */
this.apiKey_ = apiKey;
var config = opt_config || {};
this.secureTokenEndpoint_ = config['secureTokenEndpoint'] ||
fireauth.RpcHandler.SECURE_TOKEN_ENDPOINT_;
/**
* @private @const {!fireauth.util.Delay} The delay for secure token endpoint
* network timeout.
*/
this.secureTokenTimeout_ = config['secureTokenTimeout'] ||
fireauth.RpcHandler.DEFAULT_SECURE_TOKEN_TIMEOUT_;
/** @private @const {!Object} The secure token server headers. */
this.secureTokenHeaders_ = goog.object.clone(
config['secureTokenHeaders'] ||
fireauth.RpcHandler.DEFAULT_SECURE_TOKEN_HEADERS_);
/** @private {string} The Firebase Auth endpoint. */
this.firebaseEndpoint_ = config['firebaseEndpoint'] ||
fireauth.RpcHandler.FIREBASE_ENDPOINT_;
/** @private {string} The identity platform endpoint. */
this.identityPlatformEndpoint_ = config['identityPlatformEndpoint'] ||
fireauth.RpcHandler.IDENTITY_PLATFORM_ENDPOINT_;
/**
* @private @const {!fireauth.util.Delay} The delay for Firebase Auth endpoint
* network timeout.
*/
this.firebaseTimeout_ = config['firebaseTimeout'] ||
fireauth.RpcHandler.DEFAULT_FIREBASE_TIMEOUT_;
this.firebaseHeaders_ = goog.object.clone(
config['firebaseHeaders'] ||
fireauth.RpcHandler.DEFAULT_FIREBASE_HEADERS_);
// If Firebase client version needs to be logged too.
if (opt_firebaseClientVersion) {
// Log client version for Firebase Auth server.
this.firebaseHeaders_['X-Client-Version'] = opt_firebaseClientVersion;
// Log client version for securetoken server.
this.secureTokenHeaders_['X-Client-Version'] = opt_firebaseClientVersion;
}
// Get XMLHttpRequest reference.
var XMLHttpRequest = fireauth.RpcHandler.getXMLHttpRequest();
if (!XMLHttpRequest && !fireauth.util.isWorker()) {
// In a Node.js environment, xmlhttprequest module needs to be required.
throw new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR,
'The XMLHttpRequest compatibility library was not found.');
}
/** @private {!goog.net.XmlHttpFactory|undefined} The XHR factory. */
this.rpcHandlerXhrFactory_ = undefined;
// Initialize XHR factory. CORS does not apply in native environments or
// workers so don't use CorsXmlHttpFactory in those cases.
if (fireauth.util.isWorker()) {
// For worker environment use FetchXmlHttpFactory.
this.rpcHandlerXhrFactory_ = new goog.net.FetchXmlHttpFactory(
/** @type {!WorkerGlobalScope} */ (self));
} else if (fireauth.util.isNativeEnvironment()) {
// For Node.js, this is the polyfill library. For other environments,
// this is the native global XMLHttpRequest.
this.rpcHandlerXhrFactory_ = new fireauth.XmlHttpFactory(
/** @type {function(new:XMLHttpRequest)} */ (XMLHttpRequest));
} else {
// CORS Browser environment.
this.rpcHandlerXhrFactory_ = new goog.net.CorsXmlHttpFactory();
}
/** @private {?string} The tenant ID. */
this.tenantId_ = null;
};
/**
* @return {?function(new:XMLHttpRequest)|undefined} The current environment
* XMLHttpRequest. This is undefined for worker environment.
*/
fireauth.RpcHandler.getXMLHttpRequest = function() {
// In Node.js XMLHttpRequest is polyfilled.
var isNode = fireauth.util.getEnvironment() == fireauth.util.Env.NODE;
var XMLHttpRequest = goog.global['XMLHttpRequest'] ||
(isNode &&
firebase.INTERNAL['node'] &&
firebase.INTERNAL['node']['XMLHttpRequest']);
return XMLHttpRequest;
};
/**
* Enums for HTTP request methods.
* @enum {string}
*/
fireauth.RpcHandler.HttpMethod = {
POST: 'POST',
GET: 'GET'
};
/**
* Firebase Auth server error codes.
* @enum {string}
*/
fireauth.RpcHandler.ServerError = {
ADMIN_ONLY_OPERATION: 'ADMIN_ONLY_OPERATION',
CAPTCHA_CHECK_FAILED: 'CAPTCHA_CHECK_FAILED',
CORS_UNSUPPORTED: 'CORS_UNSUPPORTED',
CREDENTIAL_MISMATCH: 'CREDENTIAL_MISMATCH',
CREDENTIAL_TOO_OLD_LOGIN_AGAIN: 'CREDENTIAL_TOO_OLD_LOGIN_AGAIN',
DYNAMIC_LINK_NOT_ACTIVATED: 'DYNAMIC_LINK_NOT_ACTIVATED',
EMAIL_CHANGE_NEEDS_VERIFICATION: 'EMAIL_CHANGE_NEEDS_VERIFICATION',
EMAIL_EXISTS: 'EMAIL_EXISTS',
EMAIL_NOT_FOUND: 'EMAIL_NOT_FOUND',
EXPIRED_OOB_CODE: 'EXPIRED_OOB_CODE',
FEDERATED_USER_ID_ALREADY_LINKED: 'FEDERATED_USER_ID_ALREADY_LINKED',
INVALID_APP_CREDENTIAL: 'INVALID_APP_CREDENTIAL',
INVALID_APP_ID: 'INVALID_APP_ID',
INVALID_CERT_HASH: 'INVALID_CERT_HASH',
INVALID_CODE: 'INVALID_CODE',
INVALID_CONTINUE_URI: 'INVALID_CONTINUE_URI',
INVALID_CUSTOM_TOKEN: 'INVALID_CUSTOM_TOKEN',
INVALID_DYNAMIC_LINK_DOMAIN: 'INVALID_DYNAMIC_LINK_DOMAIN',
INVALID_EMAIL: 'INVALID_EMAIL',
INVALID_ID_TOKEN: 'INVALID_ID_TOKEN',
INVALID_IDP_RESPONSE: 'INVALID_IDP_RESPONSE',
INVALID_IDENTIFIER: 'INVALID_IDENTIFIER',
INVALID_MESSAGE_PAYLOAD: 'INVALID_MESSAGE_PAYLOAD',
INVALID_MFA_PENDING_CREDENTIAL: 'INVALID_MFA_PENDING_CREDENTIAL',
INVALID_OAUTH_CLIENT_ID: 'INVALID_OAUTH_CLIENT_ID',
INVALID_OOB_CODE: 'INVALID_OOB_CODE',
INVALID_PASSWORD: 'INVALID_PASSWORD',
INVALID_PENDING_TOKEN: 'INVALID_PENDING_TOKEN',
INVALID_PHONE_NUMBER: 'INVALID_PHONE_NUMBER',
INVALID_PROVIDER_ID: 'INVALID_PROVIDER_ID',
INVALID_RECIPIENT_EMAIL: 'INVALID_RECIPIENT_EMAIL',
INVALID_SENDER: 'INVALID_SENDER',
INVALID_SESSION_INFO: 'INVALID_SESSION_INFO',
INVALID_TEMPORARY_PROOF: 'INVALID_TEMPORARY_PROOF',
INVALID_TENANT_ID: 'INVALID_TENANT_ID',
MFA_ENROLLMENT_NOT_FOUND: 'MFA_ENROLLMENT_NOT_FOUND',
MISSING_ANDROID_PACKAGE_NAME: 'MISSING_ANDROID_PACKAGE_NAME',
MISSING_APP_CREDENTIAL: 'MISSING_APP_CREDENTIAL',
MISSING_CODE: 'MISSING_CODE',
MISSING_CONTINUE_URI: 'MISSING_CONTINUE_URI',
MISSING_CUSTOM_TOKEN: 'MISSING_CUSTOM_TOKEN',
MISSING_IOS_BUNDLE_ID: 'MISSING_IOS_BUNDLE_ID',
MISSING_MFA_ENROLLMENT_ID: 'MISSING_MFA_ENROLLMENT_ID',
MISSING_MFA_PENDING_CREDENTIAL: 'MISSING_MFA_PENDING_CREDENTIAL',
MISSING_OOB_CODE: 'MISSING_OOB_CODE',
MISSING_OR_INVALID_NONCE: 'MISSING_OR_INVALID_NONCE',
MISSING_PASSWORD: 'MISSING_PASSWORD',
MISSING_PHONE_NUMBER: 'MISSING_PHONE_NUMBER',
MISSING_SESSION_INFO: 'MISSING_SESSION_INFO',
OPERATION_NOT_ALLOWED: 'OPERATION_NOT_ALLOWED',
PASSWORD_LOGIN_DISABLED: 'PASSWORD_LOGIN_DISABLED',
QUOTA_EXCEEDED: 'QUOTA_EXCEEDED',
RESET_PASSWORD_EXCEED_LIMIT: 'RESET_PASSWORD_EXCEED_LIMIT',
REJECTED_CREDENTIAL: 'REJECTED_CREDENTIAL',
SECOND_FACTOR_EXISTS: 'SECOND_FACTOR_EXISTS',
SECOND_FACTOR_LIMIT_EXCEEDED: 'SECOND_FACTOR_LIMIT_EXCEEDED',
SESSION_EXPIRED: 'SESSION_EXPIRED',
TENANT_ID_MISMATCH: 'TENANT_ID_MISMATCH',
TOKEN_EXPIRED: 'TOKEN_EXPIRED',
TOO_MANY_ATTEMPTS_TRY_LATER: 'TOO_MANY_ATTEMPTS_TRY_LATER',
UNSUPPORTED_FIRST_FACTOR: 'UNSUPPORTED_FIRST_FACTOR',
UNSUPPORTED_TENANT_OPERATION: 'UNSUPPORTED_TENANT_OPERATION',
UNVERIFIED_EMAIL: 'UNVERIFIED_EMAIL',
UNAUTHORIZED_DOMAIN: 'UNAUTHORIZED_DOMAIN',
USER_CANCELLED: 'USER_CANCELLED',
USER_DISABLED: 'USER_DISABLED',
USER_NOT_FOUND: 'USER_NOT_FOUND',
WEAK_PASSWORD: 'WEAK_PASSWORD'
};
/**
* A map of server error codes to client errors.
* @typedef {!Object<
* !fireauth.RpcHandler.ServerError, !fireauth.authenum.Error>}
*/
fireauth.RpcHandler.ServerErrorMap;
/**
* Firebase Auth response field names.
* @enum {string}
*/
fireauth.RpcHandler.AuthServerField = {
ALL_PROVIDERS: 'allProviders',
AUTH_URI: 'authUri',
AUTHORIZED_DOMAINS: 'authorizedDomains',
DYNAMIC_LINKS_DOMAIN: 'dynamicLinksDomain',
EMAIL: 'email',
ERROR_MESSAGE: 'errorMessage',
EXPIRES_IN: 'expiresIn',
ID_TOKEN: 'idToken',
MFA_PENDING_CREDENTIAL: 'mfaPendingCredential',
NEED_CONFIRMATION: 'needConfirmation',
OAUTH_ID_TOKEN: 'oauthIdToken',
PENDING_TOKEN: 'pendingToken',
PHONE_RESPONSE_INFO: 'phoneResponseInfo',
PHONE_SESSION_INFO: 'phoneSessionInfo',
POST_BODY: 'postBody',
PROVIDER_ID: 'providerId',
RECAPTCHA_SITE_KEY: 'recaptchaSiteKey',
REQUEST_URI: 'requestUri',
REFRESH_TOKEN: 'refreshToken',
SESSION_ID: 'sessionId',
SESSION_INFO: 'sessionInfo',
SIGNIN_METHODS: 'signinMethods',
TEMPORARY_PROOF: 'temporaryProof'
};
/**
* Firebase Auth response injected fields.
* @enum {string}
*/
fireauth.RpcHandler.InjectedResponseField = {
NONCE: 'nonce'
};
/**
* Firebase Auth getOobConfirmationCode requestType possible values.
* @enum {string}
*/
fireauth.RpcHandler.GetOobCodeRequestType = {
EMAIL_SIGNIN: 'EMAIL_SIGNIN',
NEW_EMAIL_ACCEPT: 'NEW_EMAIL_ACCEPT',
PASSWORD_RESET: 'PASSWORD_RESET',
VERIFY_AND_CHANGE_EMAIL: 'VERIFY_AND_CHANGE_EMAIL',
VERIFY_EMAIL: 'VERIFY_EMAIL'
};
/**
* Firebase Auth response field names.
* @enum {string}
*/
fireauth.RpcHandler.StsServerField = {
ACCESS_TOKEN: 'access_token',
EXPIRES_IN: 'expires_in',
REFRESH_TOKEN: 'refresh_token'
};
/**
* @return {string} The API key.
*/
fireauth.RpcHandler.prototype.getApiKey = function() {
return this.apiKey_;
};
/**
* The Firebase custom locale header.
* @const {string}
* @private
*/
fireauth.RpcHandler.FIREBASE_LOCALE_KEY_ = 'X-Firebase-Locale';
/**
* The secure token endpoint.
* @const {string}
* @private
*/
fireauth.RpcHandler.SECURE_TOKEN_ENDPOINT_ =
'https://securetoken.googleapis.com/v1/token';
/**
* The default timeout delay (units in milliseconds) for requests sending to
* STS token endpoint.
* @const {!fireauth.util.Delay}
* @private
*/
fireauth.RpcHandler.DEFAULT_SECURE_TOKEN_TIMEOUT_ =
new fireauth.util.Delay(30000, 60000);
/**
* The STS token RPC content headers.
* @const {!Object}
* @private
*/
fireauth.RpcHandler.DEFAULT_SECURE_TOKEN_HEADERS_ = {
'Content-Type': 'application/x-www-form-urlencoded'
};
/**
* The Firebase endpoint.
* @const {string}
* @private
*/
fireauth.RpcHandler.FIREBASE_ENDPOINT_ =
'https://www.googleapis.com/identitytoolkit/v3/relyingparty/';
/**
* The Identity Platform endpoint.
* @const {string}
* @private
*/
fireauth.RpcHandler.IDENTITY_PLATFORM_ENDPOINT_ =
'https://identitytoolkit.googleapis.com/v2/';
/**
* The default timeout delay (units in milliseconds) for requests sending to
* Firebase endpoint.
* @const {!fireauth.util.Delay}
* @private
*/
fireauth.RpcHandler.DEFAULT_FIREBASE_TIMEOUT_ =
new fireauth.util.Delay(30000, 60000);
/**
* The Firebase RPC content headers.
* @const {!Object}
* @private
*/
fireauth.RpcHandler.DEFAULT_FIREBASE_HEADERS_ = {
'Content-Type': 'application/json'
};
/**
* Updates the custom locale header.
* @param {?string} languageCode The new languageCode.
*/
fireauth.RpcHandler.prototype.updateCustomLocaleHeader =
function(languageCode) {
if (languageCode) {
// If a language code is provided, add it to the header.
this.firebaseHeaders_[fireauth.RpcHandler.FIREBASE_LOCALE_KEY_] =
languageCode;
} else {
// Otherwise remove the custom locale header.
delete this.firebaseHeaders_[fireauth.RpcHandler.FIREBASE_LOCALE_KEY_];
}
};
/**
* Updates the emulator configuration.
* @param {?fireauth.constants.EmulatorSettings} emulatorConfig The new
* emulator config.
*/
fireauth.RpcHandler.prototype.updateEmulatorConfig = function(emulatorConfig) {
if (!emulatorConfig) {
return;
}
// If an emulator config is provided, update the endpoints.
this.secureTokenEndpoint_ =
fireauth.RpcHandler.generateEmululatorEndpointUrl_(
fireauth.RpcHandler.SECURE_TOKEN_ENDPOINT_, emulatorConfig);
this.firebaseEndpoint_ =
fireauth.RpcHandler.generateEmululatorEndpointUrl_(
fireauth.RpcHandler.FIREBASE_ENDPOINT_, emulatorConfig);
this.identityPlatformEndpoint_ =
fireauth.RpcHandler.generateEmululatorEndpointUrl_(
fireauth.RpcHandler.IDENTITY_PLATFORM_ENDPOINT_, emulatorConfig);
}
/**
* Creates an endpoint URL intended for use by the emulator.
*
* According to go/firebase-auth-emulator-dd
* @param {string} endpoint the production endpoint URL.
* @param {?fireauth.constants.EmulatorSettings} emulatorConfig The emulator
* config.
* @return {string} The emulator endpoint URL.
* @private
*/
fireauth.RpcHandler.generateEmululatorEndpointUrl_ = function(endpoint, emulatorConfig) {
const uri = goog.Uri.parse(endpoint);
const endpointUri = goog.Uri.parse(emulatorConfig.url);
uri.setPath(uri.getDomain() + uri.getPath());
uri.setScheme(endpointUri.getScheme());
uri.setDomain(endpointUri.getDomain());
uri.setPort(endpointUri.getPort());
return uri.toString();
}
/**
* Updates the X-Client-Version in the header.
* @param {?string} clientVersion The new client version.
*/
fireauth.RpcHandler.prototype.updateClientVersion = function(clientVersion) {
if (clientVersion) {
// Update client version for Firebase Auth server.
this.firebaseHeaders_['X-Client-Version'] = clientVersion;
// Update client version for securetoken server.
this.secureTokenHeaders_['X-Client-Version'] = clientVersion;
} else {
// Remove client version from header.
delete this.firebaseHeaders_['X-Client-Version'];
delete this.secureTokenHeaders_['X-Client-Version'];
}
};
/**
* Updates the tenant ID in the request.
* @param {?string} tenantId The new tenant ID.
*/
fireauth.RpcHandler.prototype.updateTenantId = function(tenantId) {
this.tenantId_ = tenantId;
};
/**
* Returns the tenant ID.
* @return {?string} The tenant ID.
*/
fireauth.RpcHandler.prototype.getTenantId = function() {
return this.tenantId_;
};
/**
* Sends XhrIo request using goog.net.XhrIo.
* @param {string} url The URL to make a request to.
* @param {function(?Object)=} opt_callback The callback to run on completion.
* @param {fireauth.RpcHandler.HttpMethod=} opt_httpMethod The HTTP send method.
* @param {?ArrayBuffer|?ArrayBufferView|?Blob|?Document|?FormData|string=}
* opt_data The request content.
* @param {?Object=} opt_headers The request content headers.
* @param {number=} opt_timeout The request timeout.
* @private
*/
fireauth.RpcHandler.prototype.sendXhr_ = function(
url,
opt_callback,
opt_httpMethod,
opt_data,
opt_headers,
opt_timeout) {
var sendXhr;
if (fireauth.util.supportsCors() || fireauth.util.isWorker()) {
// If supports CORS use goog.net.XhrIo.
sendXhr = goog.bind(this.sendXhrUsingXhrIo_, this);
} else {
// Load gapi.client.request and gapi.auth dependency dynamically.
if (!fireauth.RpcHandler.loadGApi_) {
fireauth.RpcHandler.loadGApi_ =
new goog.Promise(function(resolve, reject) {
// On load, resolve.
fireauth.RpcHandler.loadGApiJs_(resolve, reject);
});
}
// If does not support CORS, use gapi.client.request.
sendXhr = goog.bind(this.sendXhrUsingGApiClient_, this);
}
sendXhr(
url, opt_callback, opt_httpMethod, opt_data, opt_headers, opt_timeout);
};
/**
* Sends XhrIo request using goog.net.XhrIo.
* @param {string} url The URL to make a request to.
* @param {function(?Object)=} opt_callback The callback to run on completion.
* @param {fireauth.RpcHandler.HttpMethod=} opt_httpMethod The HTTP send method.
* @param {?ArrayBuffer|?ArrayBufferView|?Blob|?Document|?FormData|string=}
* opt_data The request content.
* @param {?Object=} opt_headers The request content headers.
* @param {number=} opt_timeout The request timeout.
* @private
*/
fireauth.RpcHandler.prototype.sendXhrUsingXhrIo_ = function(
url,
opt_callback,
opt_httpMethod,
opt_data,
opt_headers,
opt_timeout) {
if (fireauth.util.isWorker() && !fireauth.util.isFetchSupported()) {
throw new fireauth.AuthError(
fireauth.authenum.Error.OPERATION_NOT_SUPPORTED,
'fetch, Headers and Request native APIs or equivalent Polyfills ' +
'must be available to support HTTP requests from a Worker ' +
'environment.');
}
var xhrIo = new goog.net.XhrIo(this.rpcHandlerXhrFactory_);
// xhrIo.setTimeoutInterval not working in IE10 and IE11, handle manually.
var requestTimeout;
if (opt_timeout) {
xhrIo.setTimeoutInterval(opt_timeout);
requestTimeout = setTimeout(function() {
xhrIo.dispatchEvent(goog.net.EventType.TIMEOUT);
}, opt_timeout);
}
// Run callback function on completion.
xhrIo.listen(
goog.net.EventType.COMPLETE,
/** @this {goog.net.XhrIo} */
function() {
// Clear timeout timer.
if (requestTimeout) {
clearTimeout(requestTimeout);
}
// Response assumed to be in json format. If not, catch, log error and
// pass null to callback.
var response = null;
try {
// Do not use this.responseJson() as it uses goog.json.parse
// underneath. Internal goog.json.parse parsing uses eval and since
// recommended Content Security Policy does not allow unsafe-eval,
// this is failing and throwing an error in chrome extensions and
// warnings else where. Use native parsing instead via JSON.parse.
response = JSON.parse(this.getResponseText()) || null;
} catch (e) {
response = null;
}
if (opt_callback) {
opt_callback(/** @type {?Object} */ (response));
}
});
// Dispose xhrIo on ready.
xhrIo.listenOnce(
goog.net.EventType.READY,
/** @this {goog.net.XhrIo} */
function() {
// Clear timeout timer.
if (requestTimeout) {
clearTimeout(requestTimeout);
}
// Dispose xhrIo.
this.dispose();
});
// Listen to timeout error.
// This should work when request is aborted too.
xhrIo.listenOnce(
goog.net.EventType.TIMEOUT,
/** @this {goog.net.XhrIo} */
function() {
// Clear timeout timer.
if (requestTimeout) {
clearTimeout(requestTimeout);
}
// Dispose xhrIo.
this.dispose();
// The request timed out.
if (opt_callback) {
opt_callback(null);
}
});
xhrIo.send(url, opt_httpMethod, opt_data, opt_headers);
};
/**
* @const {!goog.string.Const} The GApi client library URL.
* @private
*/
fireauth.RpcHandler.GAPI_SRC_ = goog.string.Const.from(
'https://apis.google.com/js/client.js?onload=%{onload}');
/**
* @const {string}
* @private
*/
fireauth.RpcHandler.GAPI_CALLBACK_NAME_ =
'__fcb' + Math.floor(Math.random() * 1000000).toString();
/**
* Loads the GApi client library if it is not loaded.
* @param {function()} callback The callback to invoke once it's loaded.
* @param {function(?Object)} errback The error callback.
* @private
*/
fireauth.RpcHandler.loadGApiJs_ = function(callback, errback) {
// If gapi.client.request not available, load it dynamically.
if (!((window['gapi'] || {})['client'] || {})['request']) {
goog.global[fireauth.RpcHandler.GAPI_CALLBACK_NAME_] = function() {
// Callback will be called by GApi, test properly loaded here instead of
// after jsloader resolves.
if (!((window['gapi'] || {})['client'] || {})['request']) {
errback(new Error(fireauth.RpcHandler.ServerError.CORS_UNSUPPORTED));
} else {
callback();
}
};
var url = goog.html.TrustedResourceUrl.format(
fireauth.RpcHandler.GAPI_SRC_,
{'onload': fireauth.RpcHandler.GAPI_CALLBACK_NAME_});
// TODO: replace goog.net.jsloader with our own script includer.
var result = goog.net.jsloader.safeLoad(url);
result.addErrback(function() {
// In case file fails to load.
errback(new Error(fireauth.RpcHandler.ServerError.CORS_UNSUPPORTED));
});
} else {
callback();
}
};
/**
* Sends XhrIo request using gapi.client.
* @param {string} url The URL to make a request to.
* @param {function(?Object)=} opt_callback The callback to run on completion.
* @param {fireauth.RpcHandler.HttpMethod=} opt_httpMethod The HTTP send method.
* @param {?ArrayBuffer|?ArrayBufferView|?Blob|?Document|?FormData|string=}
* opt_data The request content.
* @param {?Object=} opt_headers The request content headers.
* @param {number=} opt_timeout The request timeout.
* @private
*/
fireauth.RpcHandler.prototype.sendXhrUsingGApiClient_ = function(
url,
opt_callback,
opt_httpMethod,
opt_data,
opt_headers,
opt_timeout) {
var self = this;
// Wait for GApi dependency to load.
fireauth.RpcHandler.loadGApi_.then(function() {
window['gapi']['client']['setApiKey'](self.getApiKey());
// GApi maintains the Auth result and automatically append the Auth token to
// all outgoing requests. Firebase Auth requests will be rejected if there
// are others scopes (e.g. google plus) for the Auth token. Need to empty
// the token before call gitkit api. Restored in callback.
var oauth2Token = window['gapi']['auth']['getToken']();
window['gapi']['auth']['setToken'](null);
window['gapi']['client']['request']({
'path': url,
'method': opt_httpMethod,
'body': opt_data,
'headers': opt_headers,
// This needs to be set to none, otherwise the access token will be passed
// in the header field causing apiary to complain.
'authType': 'none',
'callback': function(response) {
window['gapi']['auth']['setToken'](oauth2Token);
if (opt_callback) {
opt_callback(response);
}
}
});
}).thenCatch(function(error) {
// Catches failure to support CORS and propagates it.
if (opt_callback) {
// Simulate backend server error to be caught by upper layer.
opt_callback({
'error': {
'message': (error && error['message']) ||
fireauth.RpcHandler.ServerError.CORS_UNSUPPORTED
}
});
}
});
};
/**
* Validates the request for the STS access token.
*
* @param {?Object} data The STS token request body.
* @return {boolean} Whether the request is valid.
* @private
*/
fireauth.RpcHandler.prototype.validateStsTokenRequest_ = function(data) {
if (data['grant_type'] == 'refresh_token' && data['refresh_token']) {
// Exchange refresh token.
return true;
} else if (data['grant_type'] == 'authorization_code' && data['code']) {
// Exchange ID token.
return true;
} else {
// Invalid.
return false;
}
};
/**
* Handles the request for the STS access token.
*
* @param {!Object} data The STS token request body.
* @return {!goog.Promise<!Object>}
*/
fireauth.RpcHandler.prototype.requestStsToken = function(data) {
var self = this;
return new goog.Promise(function(resolve, reject) {
if (self.validateStsTokenRequest_(data)) {
self.sendXhr_(
self.secureTokenEndpoint_ + '?key=' +
encodeURIComponent(self.getApiKey()),
function(response) {
if (!response) {
// An unparseable response from the XHR most likely indicates some
// problem with the network.
reject(new fireauth.AuthError(
fireauth.authenum.Error.NETWORK_REQUEST_FAILED));
} else if (fireauth.RpcHandler.hasError_(response)) {
reject(fireauth.RpcHandler.getDeveloperError_(response));
} else if (
!response[fireauth.RpcHandler.StsServerField.ACCESS_TOKEN] ||
!response[fireauth.RpcHandler.StsServerField.REFRESH_TOKEN]) {
reject(new fireauth.AuthError(
fireauth.authenum.Error.INTERNAL_ERROR));
} else {
resolve(response);
}
},
fireauth.RpcHandler.HttpMethod.POST,
goog.Uri.QueryData.createFromMap(data).toString(),
self.secureTokenHeaders_,
self.secureTokenTimeout_.get());
} else {
reject(new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR));
}
});
};
/**
* @param {!Object} data The object to serialize.
* @return {string} The serialized object with null, undefined and empty string
* values removed.
* @private
*/
fireauth.RpcHandler.serialize_ = function(data) {
// goog.json.serialize converts undefined values to null.
// This helper removes all empty strings, nulls and undefined from serialized
// object.
// Serialize trimmed data.
return goog.json.serialize(fireauth.util.copyWithoutNullsOrUndefined(data));
};
/**
* Creates and executes a request for the given API method using the legacy
* Firebase Auth endpoint.
* @param {string} method The API method.
* @param {!fireauth.RpcHandler.HttpMethod} httpMethod The http request method.
* @param {!Object} data The data for the API request. In the case of a GET
* request, the contents of this object will be form encoded and appended
* to the query string of the URL. No post body is sent in that case. If an
* object value is specified, it will be converted to a string:
* encodeURIComponent(String(value)).
* @param {?fireauth.RpcHandler.ServerErrorMap=} opt_customErrorMap A map
* of server error codes to client errors to override default error
* handling.
* @param {boolean=} opt_cachebuster Whether to append a unique string to
* request to force backend to return an uncached response to request.
* @return {!goog.Promise<!Object>}
*/
fireauth.RpcHandler.prototype.requestFirebaseEndpoint = function(
method, httpMethod, data, opt_customErrorMap, opt_cachebuster) {
return this.requestAuthEndpoint_(
this.firebaseEndpoint_, method, httpMethod, data, opt_customErrorMap,
opt_cachebuster);
};
/**
* Creates and executes a request for the given API method using the identity
* platform endpoint.
* @param {string} method The API method.
* @param {!fireauth.RpcHandler.HttpMethod} httpMethod The http request method.
* @param {!Object} data The data for the API request. In the case of a GET
* request, the contents of this object will be form encoded and appended
* to the query string of the URL. No post body is sent in that case. If an
* object value is specified, it will be converted to a string:
* encodeURIComponent(String(value)).
* @param {?fireauth.RpcHandler.ServerErrorMap=} opt_customErrorMap A map
* of server error codes to client errors to override default error
* handling.
* @param {boolean=} opt_cachebuster Whether to append a unique string to
* request to force backend to return an uncached response to request.
* @return {!goog.Promise<!Object>}
*/
fireauth.RpcHandler.prototype.requestIdentityPlatformEndpoint = function(
method, httpMethod, data, opt_customErrorMap, opt_cachebuster) {
return this.requestAuthEndpoint_(
this.identityPlatformEndpoint_, method, httpMethod, data,
opt_customErrorMap, opt_cachebuster);
};
/**
* Creates and executes a request for the given API method and Auth endpoint.
* @param {string} endpoint The Auth endpoint to use.
* @param {string} method The API method.
* @param {!fireauth.RpcHandler.HttpMethod} httpMethod The http request method.
* @param {!Object} data The data for the API request. In the case of a GET
* request, the contents of this object will be form encoded and appended
* to the query string of the URL. No post body is sent in that case. If an
* object value is specified, it will be converted to a string:
* encodeURIComponent(String(value)).
* @param {?fireauth.RpcHandler.ServerErrorMap=} opt_customErrorMap A map
* of server error codes to client errors to override default error
* handling.
* @param {boolean=} opt_cachebuster Whether to append a unique string to
* request to force backend to return an uncached response to request.
* @return {!goog.Promise<!Object>}
* @private
*/
fireauth.RpcHandler.prototype.requestAuthEndpoint_ = function(
endpoint, method, httpMethod, data, opt_customErrorMap, opt_cachebuster) {
var self = this;
// Construct endpoint URL.
var uri = goog.Uri.parse(endpoint + method);
uri.setParameterValue('key', this.getApiKey());
// Check whether to append cachebuster to request.
if (opt_cachebuster) {
uri.setParameterValue('cb', goog.now().toString());
}
// Firebase allows GET endpoints.
var isGet = httpMethod == fireauth.RpcHandler.HttpMethod.GET;
if (isGet) {
// For GET HTTP method, append data to query string.
for (var key in data) {
if (data.hasOwnProperty(key)) {
uri.setParameterValue(key, data[key]);
}
}
}
return new goog.Promise(function(resolve, reject) {
self.sendXhr_(
uri.toString(),
function(response) {
if (!response) {
// An unparseable response from the XHR most likely indicates some
// problem with the network.
reject(new fireauth.AuthError(
fireauth.authenum.Error.NETWORK_REQUEST_FAILED));
} else if (fireauth.RpcHandler.hasError_(response)) {
reject(fireauth.RpcHandler.getDeveloperError_(response,
opt_customErrorMap || {}));
} else {
resolve(response);
}
},
httpMethod,
// No post body data in GET requests.
isGet ? undefined : fireauth.RpcHandler.serialize_(data),
self.firebaseHeaders_,
self.firebaseTimeout_.get());
});
};
/**
* Verifies that the request has a valid email set.
* @param {!Object} request
* @private
*/
fireauth.RpcHandler.validateRequestHasEmail_ = function(request) {
if (!fireauth.util.isValidEmailAddress(request['email'])) {
throw new fireauth.AuthError(fireauth.authenum.Error.INVALID_EMAIL);
}
};
/**
* Verifies that the response has a valid email set.
* @param {!Object} response
* @private
*/
fireauth.RpcHandler.validateResponseHasEmail_ = function(response) {
if (!fireauth.util.isValidEmailAddress(response['email'])) {
throw new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR);
}
};
/**
* Verifies that the an email is valid, if it is there.
* @param {!Object} request
* @private
*/
fireauth.RpcHandler.validateEmailIfPresent_ = function(request) {
if ('email' in request) {
fireauth.RpcHandler.validateRequestHasEmail_(request);
}
};
/**
* @param {string} providerId The provider ID.
* @param {?Array<string>=} opt_additionalScopes The list of scope strings.
* @return {?string} The IDP and its comma separated scope strings serialized.
* @private
*/
fireauth.RpcHandler.getAdditionalScopes_ =
function(providerId, opt_additionalScopes) {
var scopes = {};
if (opt_additionalScopes && opt_additionalScopes.length) {
scopes[providerId] = opt_additionalScopes.join(',');
// Return stringified scopes.
return goog.json.serialize(scopes);
}
return null;
};