-
Notifications
You must be signed in to change notification settings - Fork 373
/
Copy pathauth-api-request.ts
2323 lines (2165 loc) · 87 KB
/
auth-api-request.ts
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.
*/
import * as validator from '../utils/validator';
import { App } from '../app/index';
import { FirebaseApp } from '../app/firebase-app';
import { deepCopy, deepExtend } from '../utils/deep-copy';
import { AuthClientErrorCode, FirebaseAuthError } from '../utils/error';
import {
ApiSettings, AuthorizedHttpClient, HttpRequestConfig, HttpError,
} from '../utils/api-request';
import * as utils from '../utils/index';
import {
UserImportOptions, UserImportRecord, UserImportResult,
UserImportBuilder, AuthFactorInfo, convertMultiFactorInfoToServerFormat,
} from './user-import-builder';
import { ActionCodeSettings, ActionCodeSettingsBuilder } from './action-code-settings-builder';
import { Tenant, TenantServerResponse, CreateTenantRequest, UpdateTenantRequest } from './tenant';
import {
isUidIdentifier, isEmailIdentifier, isPhoneIdentifier, isProviderIdentifier,
UserIdentifier, UidIdentifier, EmailIdentifier,PhoneIdentifier, ProviderIdentifier,
} from './identifier';
import {
SAMLConfig, OIDCConfig, OIDCConfigServerResponse, SAMLConfigServerResponse,
OIDCConfigServerRequest, SAMLConfigServerRequest, CreateRequest, UpdateRequest,
OIDCAuthProviderConfig, SAMLAuthProviderConfig, OIDCUpdateAuthProviderRequest,
SAMLUpdateAuthProviderRequest
} from './auth-config';
import { ProjectConfig, ProjectConfigServerResponse, UpdateProjectConfigRequest } from './project-config';
/** Firebase Auth request header. */
const FIREBASE_AUTH_HEADER = {
'X-Client-Version': `Node/Admin/${utils.getSdkVersion()}`,
};
/** Firebase Auth request timeout duration in milliseconds. */
const FIREBASE_AUTH_TIMEOUT = 25000;
/** List of reserved claims which cannot be provided when creating a custom token. */
export const RESERVED_CLAIMS = [
'acr', 'amr', 'at_hash', 'aud', 'auth_time', 'azp', 'cnf', 'c_hash', 'exp', 'iat',
'iss', 'jti', 'nbf', 'nonce', 'sub', 'firebase',
];
/** List of supported email action request types. */
export const EMAIL_ACTION_REQUEST_TYPES = [
'PASSWORD_RESET', 'VERIFY_EMAIL', 'EMAIL_SIGNIN', 'VERIFY_AND_CHANGE_EMAIL',
];
/** Maximum allowed number of characters in the custom claims payload. */
const MAX_CLAIMS_PAYLOAD_SIZE = 1000;
/** Maximum allowed number of users to batch download at one time. */
const MAX_DOWNLOAD_ACCOUNT_PAGE_SIZE = 1000;
/** Maximum allowed number of users to batch upload at one time. */
const MAX_UPLOAD_ACCOUNT_BATCH_SIZE = 1000;
/** Maximum allowed number of users to batch get at one time. */
const MAX_GET_ACCOUNTS_BATCH_SIZE = 100;
/** Maximum allowed number of users to batch delete at one time. */
const MAX_DELETE_ACCOUNTS_BATCH_SIZE = 1000;
/** Minimum allowed session cookie duration in seconds (5 minutes). */
const MIN_SESSION_COOKIE_DURATION_SECS = 5 * 60;
/** Maximum allowed session cookie duration in seconds (2 weeks). */
const MAX_SESSION_COOKIE_DURATION_SECS = 14 * 24 * 60 * 60;
/** Maximum allowed number of provider configurations to batch download at one time. */
const MAX_LIST_PROVIDER_CONFIGURATION_PAGE_SIZE = 100;
/** The Firebase Auth backend base URL format. */
const FIREBASE_AUTH_BASE_URL_FORMAT =
'https://identitytoolkit.googleapis.com/{version}/projects/{projectId}{api}';
/** Firebase Auth base URlLformat when using the auth emultor. */
const FIREBASE_AUTH_EMULATOR_BASE_URL_FORMAT =
'http://{host}/identitytoolkit.googleapis.com/{version}/projects/{projectId}{api}';
/** The Firebase Auth backend multi-tenancy base URL format. */
const FIREBASE_AUTH_TENANT_URL_FORMAT = FIREBASE_AUTH_BASE_URL_FORMAT.replace(
'projects/{projectId}', 'projects/{projectId}/tenants/{tenantId}');
/** Firebase Auth base URL format when using the auth emultor with multi-tenancy. */
const FIREBASE_AUTH_EMULATOR_TENANT_URL_FORMAT = FIREBASE_AUTH_EMULATOR_BASE_URL_FORMAT.replace(
'projects/{projectId}', 'projects/{projectId}/tenants/{tenantId}');
/** Maximum allowed number of tenants to download at one time. */
const MAX_LIST_TENANT_PAGE_SIZE = 1000;
/**
* Enum for the user write operation type.
*/
enum WriteOperationType {
Create = 'create',
Update = 'update',
Upload = 'upload',
}
/** Defines a base utility to help with resource URL construction. */
class AuthResourceUrlBuilder {
protected urlFormat: string;
private projectId: string;
/**
* The resource URL builder constructor.
*
* @param projectId - The resource project ID.
* @param version - The endpoint API version.
* @constructor
*/
constructor(protected app: App, protected version: string = 'v1') {
if (useEmulator()) {
this.urlFormat = utils.formatString(FIREBASE_AUTH_EMULATOR_BASE_URL_FORMAT, {
host: emulatorHost()
});
} else {
this.urlFormat = FIREBASE_AUTH_BASE_URL_FORMAT;
}
}
/**
* Returns the resource URL corresponding to the provided parameters.
*
* @param api - The backend API name.
* @param params - The optional additional parameters to substitute in the
* URL path.
* @returns The corresponding resource URL.
*/
public getUrl(api?: string, params?: object): Promise<string> {
return this.getProjectId()
.then((projectId) => {
const baseParams = {
version: this.version,
projectId,
api: api || '',
};
const baseUrl = utils.formatString(this.urlFormat, baseParams);
// Substitute additional api related parameters.
return utils.formatString(baseUrl, params || {});
});
}
private getProjectId(): Promise<string> {
if (this.projectId) {
return Promise.resolve(this.projectId);
}
return utils.findProjectId(this.app)
.then((projectId) => {
if (!validator.isNonEmptyString(projectId)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_CREDENTIAL,
'Failed to determine project ID for Auth. Initialize the '
+ 'SDK with service account credentials or set project ID as an app option. '
+ 'Alternatively set the GOOGLE_CLOUD_PROJECT environment variable.',
);
}
this.projectId = projectId;
return projectId;
});
}
}
/** Tenant aware resource builder utility. */
class TenantAwareAuthResourceUrlBuilder extends AuthResourceUrlBuilder {
/**
* The tenant aware resource URL builder constructor.
*
* @param projectId - The resource project ID.
* @param version - The endpoint API version.
* @param tenantId - The tenant ID.
* @constructor
*/
constructor(protected app: App, protected version: string, protected tenantId: string) {
super(app, version);
if (useEmulator()) {
this.urlFormat = utils.formatString(FIREBASE_AUTH_EMULATOR_TENANT_URL_FORMAT, {
host: emulatorHost()
});
} else {
this.urlFormat = FIREBASE_AUTH_TENANT_URL_FORMAT;
}
}
/**
* Returns the resource URL corresponding to the provided parameters.
*
* @param api - The backend API name.
* @param params - The optional additional parameters to substitute in the
* URL path.
* @returns The corresponding resource URL.
*/
public getUrl(api?: string, params?: object): Promise<string> {
return super.getUrl(api, params)
.then((url) => {
return utils.formatString(url, { tenantId: this.tenantId });
});
}
}
/**
* Auth-specific HTTP client which uses the special "owner" token
* when communicating with the Auth Emulator.
*/
class AuthHttpClient extends AuthorizedHttpClient {
protected getToken(): Promise<string> {
if (useEmulator()) {
return Promise.resolve('owner');
}
return super.getToken();
}
}
/**
* Validates an AuthFactorInfo object. All unsupported parameters
* are removed from the original request. If an invalid field is passed
* an error is thrown.
*
* @param request - The AuthFactorInfo request object.
*/
function validateAuthFactorInfo(request: AuthFactorInfo): void {
const validKeys = {
mfaEnrollmentId: true,
displayName: true,
phoneInfo: true,
enrolledAt: true,
};
// Remove unsupported keys from the original request.
for (const key in request) {
if (!(key in validKeys)) {
delete request[key];
}
}
// No enrollment ID is available for signupNewUser. Use another identifier.
const authFactorInfoIdentifier =
request.mfaEnrollmentId || request.phoneInfo || JSON.stringify(request);
// Enrollment uid may or may not be specified for update operations.
if (typeof request.mfaEnrollmentId !== 'undefined' &&
!validator.isNonEmptyString(request.mfaEnrollmentId)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_UID,
'The second factor "uid" must be a valid non-empty string.',
);
}
if (typeof request.displayName !== 'undefined' &&
!validator.isString(request.displayName)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_DISPLAY_NAME,
`The second factor "displayName" for "${authFactorInfoIdentifier}" must be a valid string.`,
);
}
// enrolledAt must be a valid UTC date string.
if (typeof request.enrolledAt !== 'undefined' &&
!validator.isISODateString(request.enrolledAt)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_ENROLLMENT_TIME,
`The second factor "enrollmentTime" for "${authFactorInfoIdentifier}" must be a valid ` +
'UTC date string.');
}
// Validate required fields depending on second factor type.
if (typeof request.phoneInfo !== 'undefined') {
// phoneNumber should be a string and a valid phone number.
if (!validator.isPhoneNumber(request.phoneInfo)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_PHONE_NUMBER,
`The second factor "phoneNumber" for "${authFactorInfoIdentifier}" must be a non-empty ` +
'E.164 standard compliant identifier string.');
}
} else {
// Invalid second factor. For example, a phone second factor may have been provided without
// a phone number. A TOTP based second factor may require a secret key, etc.
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_ENROLLED_FACTORS,
'MFAInfo object provided is invalid.');
}
}
/**
* Validates a providerUserInfo object. All unsupported parameters
* are removed from the original request. If an invalid field is passed
* an error is thrown.
*
* @param request - The providerUserInfo request object.
*/
function validateProviderUserInfo(request: any): void {
const validKeys = {
rawId: true,
providerId: true,
email: true,
displayName: true,
photoUrl: true,
};
// Remove invalid keys from original request.
for (const key in request) {
if (!(key in validKeys)) {
delete request[key];
}
}
if (!validator.isNonEmptyString(request.providerId)) {
throw new FirebaseAuthError(AuthClientErrorCode.INVALID_PROVIDER_ID);
}
if (typeof request.displayName !== 'undefined' &&
typeof request.displayName !== 'string') {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_DISPLAY_NAME,
`The provider "displayName" for "${request.providerId}" must be a valid string.`,
);
}
if (!validator.isNonEmptyString(request.rawId)) {
// This is called localId on the backend but the developer specifies this as
// uid externally. So the error message should use the client facing name.
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_UID,
`The provider "uid" for "${request.providerId}" must be a valid non-empty string.`,
);
}
// email should be a string and a valid email.
if (typeof request.email !== 'undefined' && !validator.isEmail(request.email)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_EMAIL,
`The provider "email" for "${request.providerId}" must be a valid email string.`,
);
}
// photoUrl should be a URL.
if (typeof request.photoUrl !== 'undefined' &&
!validator.isURL(request.photoUrl)) {
// This is called photoUrl on the backend but the developer specifies this as
// photoURL externally. So the error message should use the client facing name.
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_PHOTO_URL,
`The provider "photoURL" for "${request.providerId}" must be a valid URL string.`,
);
}
}
/**
* Validates a create/edit request object. All unsupported parameters
* are removed from the original request. If an invalid field is passed
* an error is thrown.
*
* @param request - The create/edit request object.
* @param writeOperationType - The write operation type.
*/
function validateCreateEditRequest(request: any, writeOperationType: WriteOperationType): void {
const uploadAccountRequest = writeOperationType === WriteOperationType.Upload;
// Hash set of whitelisted parameters.
const validKeys = {
displayName: true,
localId: true,
email: true,
password: true,
rawPassword: true,
emailVerified: true,
photoUrl: true,
disabled: true,
disableUser: true,
deleteAttribute: true,
deleteProvider: true,
sanityCheck: true,
phoneNumber: true,
customAttributes: true,
validSince: true,
// Pass linkProviderUserInfo only for updates (i.e. not for uploads.)
linkProviderUserInfo: !uploadAccountRequest,
// Pass tenantId only for uploadAccount requests.
tenantId: uploadAccountRequest,
passwordHash: uploadAccountRequest,
salt: uploadAccountRequest,
createdAt: uploadAccountRequest,
lastLoginAt: uploadAccountRequest,
providerUserInfo: uploadAccountRequest,
mfaInfo: uploadAccountRequest,
// Only for non-uploadAccount requests.
mfa: !uploadAccountRequest,
};
// Remove invalid keys from original request.
for (const key in request) {
if (!(key in validKeys)) {
delete request[key];
}
}
if (typeof request.tenantId !== 'undefined' &&
!validator.isNonEmptyString(request.tenantId)) {
throw new FirebaseAuthError(AuthClientErrorCode.INVALID_TENANT_ID);
}
// For any invalid parameter, use the external key name in the error description.
// displayName should be a string.
if (typeof request.displayName !== 'undefined' &&
!validator.isString(request.displayName)) {
throw new FirebaseAuthError(AuthClientErrorCode.INVALID_DISPLAY_NAME);
}
if ((typeof request.localId !== 'undefined' || uploadAccountRequest) &&
!validator.isUid(request.localId)) {
// This is called localId on the backend but the developer specifies this as
// uid externally. So the error message should use the client facing name.
throw new FirebaseAuthError(AuthClientErrorCode.INVALID_UID);
}
// email should be a string and a valid email.
if (typeof request.email !== 'undefined' && !validator.isEmail(request.email)) {
throw new FirebaseAuthError(AuthClientErrorCode.INVALID_EMAIL);
}
// phoneNumber should be a string and a valid phone number.
if (typeof request.phoneNumber !== 'undefined' &&
!validator.isPhoneNumber(request.phoneNumber)) {
throw new FirebaseAuthError(AuthClientErrorCode.INVALID_PHONE_NUMBER);
}
// password should be a string and a minimum of 6 chars.
if (typeof request.password !== 'undefined' &&
!validator.isPassword(request.password)) {
throw new FirebaseAuthError(AuthClientErrorCode.INVALID_PASSWORD);
}
// rawPassword should be a string and a minimum of 6 chars.
if (typeof request.rawPassword !== 'undefined' &&
!validator.isPassword(request.rawPassword)) {
// This is called rawPassword on the backend but the developer specifies this as
// password externally. So the error message should use the client facing name.
throw new FirebaseAuthError(AuthClientErrorCode.INVALID_PASSWORD);
}
// emailVerified should be a boolean.
if (typeof request.emailVerified !== 'undefined' &&
typeof request.emailVerified !== 'boolean') {
throw new FirebaseAuthError(AuthClientErrorCode.INVALID_EMAIL_VERIFIED);
}
// photoUrl should be a URL.
if (typeof request.photoUrl !== 'undefined' &&
!validator.isURL(request.photoUrl)) {
// This is called photoUrl on the backend but the developer specifies this as
// photoURL externally. So the error message should use the client facing name.
throw new FirebaseAuthError(AuthClientErrorCode.INVALID_PHOTO_URL);
}
// disabled should be a boolean.
if (typeof request.disabled !== 'undefined' &&
typeof request.disabled !== 'boolean') {
throw new FirebaseAuthError(AuthClientErrorCode.INVALID_DISABLED_FIELD);
}
// validSince should be a number.
if (typeof request.validSince !== 'undefined' &&
!validator.isNumber(request.validSince)) {
throw new FirebaseAuthError(AuthClientErrorCode.INVALID_TOKENS_VALID_AFTER_TIME);
}
// createdAt should be a number.
if (typeof request.createdAt !== 'undefined' &&
!validator.isNumber(request.createdAt)) {
throw new FirebaseAuthError(AuthClientErrorCode.INVALID_CREATION_TIME);
}
// lastSignInAt should be a number.
if (typeof request.lastLoginAt !== 'undefined' &&
!validator.isNumber(request.lastLoginAt)) {
throw new FirebaseAuthError(AuthClientErrorCode.INVALID_LAST_SIGN_IN_TIME);
}
// disableUser should be a boolean.
if (typeof request.disableUser !== 'undefined' &&
typeof request.disableUser !== 'boolean') {
// This is called disableUser on the backend but the developer specifies this as
// disabled externally. So the error message should use the client facing name.
throw new FirebaseAuthError(AuthClientErrorCode.INVALID_DISABLED_FIELD);
}
// customAttributes should be stringified JSON with no blacklisted claims.
// The payload should not exceed 1KB.
if (typeof request.customAttributes !== 'undefined') {
let developerClaims: object;
try {
developerClaims = JSON.parse(request.customAttributes);
} catch (error) {
// JSON parsing error. This should never happen as we stringify the claims internally.
// However, we still need to check since setAccountInfo via edit requests could pass
// this field.
throw new FirebaseAuthError(AuthClientErrorCode.INVALID_CLAIMS, error.message);
}
const invalidClaims: string[] = [];
// Check for any invalid claims.
RESERVED_CLAIMS.forEach((blacklistedClaim) => {
if (Object.prototype.hasOwnProperty.call(developerClaims, blacklistedClaim)) {
invalidClaims.push(blacklistedClaim);
}
});
// Throw an error if an invalid claim is detected.
if (invalidClaims.length > 0) {
throw new FirebaseAuthError(
AuthClientErrorCode.FORBIDDEN_CLAIM,
invalidClaims.length > 1 ?
`Developer claims "${invalidClaims.join('", "')}" are reserved and cannot be specified.` :
`Developer claim "${invalidClaims[0]}" is reserved and cannot be specified.`,
);
}
// Check claims payload does not exceed maxmimum size.
if (request.customAttributes.length > MAX_CLAIMS_PAYLOAD_SIZE) {
throw new FirebaseAuthError(
AuthClientErrorCode.CLAIMS_TOO_LARGE,
`Developer claims payload should not exceed ${MAX_CLAIMS_PAYLOAD_SIZE} characters.`,
);
}
}
// passwordHash has to be a base64 encoded string.
if (typeof request.passwordHash !== 'undefined' &&
!validator.isString(request.passwordHash)) {
throw new FirebaseAuthError(AuthClientErrorCode.INVALID_PASSWORD_HASH);
}
// salt has to be a base64 encoded string.
if (typeof request.salt !== 'undefined' &&
!validator.isString(request.salt)) {
throw new FirebaseAuthError(AuthClientErrorCode.INVALID_PASSWORD_SALT);
}
// providerUserInfo has to be an array of valid UserInfo requests.
if (typeof request.providerUserInfo !== 'undefined' &&
!validator.isArray(request.providerUserInfo)) {
throw new FirebaseAuthError(AuthClientErrorCode.INVALID_PROVIDER_DATA);
} else if (validator.isArray(request.providerUserInfo)) {
request.providerUserInfo.forEach((providerUserInfoEntry: any) => {
validateProviderUserInfo(providerUserInfoEntry);
});
}
// linkProviderUserInfo must be a (single) UserProvider value.
if (typeof request.linkProviderUserInfo !== 'undefined') {
validateProviderUserInfo(request.linkProviderUserInfo);
}
// mfaInfo is used for importUsers.
// mfa.enrollments is used for setAccountInfo.
// enrollments has to be an array of valid AuthFactorInfo requests.
let enrollments: AuthFactorInfo[] | null = null;
if (request.mfaInfo) {
enrollments = request.mfaInfo;
} else if (request.mfa && request.mfa.enrollments) {
enrollments = request.mfa.enrollments;
}
if (enrollments) {
if (!validator.isArray(enrollments)) {
throw new FirebaseAuthError(AuthClientErrorCode.INVALID_ENROLLED_FACTORS);
}
enrollments.forEach((authFactorInfoEntry: AuthFactorInfo) => {
validateAuthFactorInfo(authFactorInfoEntry);
});
}
}
/**
* Instantiates the createSessionCookie endpoint settings.
*
* @internal
*/
export const FIREBASE_AUTH_CREATE_SESSION_COOKIE =
new ApiSettings(':createSessionCookie', 'POST')
// Set request validator.
.setRequestValidator((request: any) => {
// Validate the ID token is a non-empty string.
if (!validator.isNonEmptyString(request.idToken)) {
throw new FirebaseAuthError(AuthClientErrorCode.INVALID_ID_TOKEN);
}
// Validate the custom session cookie duration.
if (!validator.isNumber(request.validDuration) ||
request.validDuration < MIN_SESSION_COOKIE_DURATION_SECS ||
request.validDuration > MAX_SESSION_COOKIE_DURATION_SECS) {
throw new FirebaseAuthError(AuthClientErrorCode.INVALID_SESSION_COOKIE_DURATION);
}
})
// Set response validator.
.setResponseValidator((response: any) => {
// Response should always contain the session cookie.
if (!validator.isNonEmptyString(response.sessionCookie)) {
throw new FirebaseAuthError(AuthClientErrorCode.INTERNAL_ERROR);
}
});
/**
* Instantiates the uploadAccount endpoint settings.
*
* @internal
*/
export const FIREBASE_AUTH_UPLOAD_ACCOUNT = new ApiSettings('/accounts:batchCreate', 'POST');
/**
* Instantiates the downloadAccount endpoint settings.
*
* @internal
*/
export const FIREBASE_AUTH_DOWNLOAD_ACCOUNT = new ApiSettings('/accounts:batchGet', 'GET')
// Set request validator.
.setRequestValidator((request: any) => {
// Validate next page token.
if (typeof request.nextPageToken !== 'undefined' &&
!validator.isNonEmptyString(request.nextPageToken)) {
throw new FirebaseAuthError(AuthClientErrorCode.INVALID_PAGE_TOKEN);
}
// Validate max results.
if (!validator.isNumber(request.maxResults) ||
request.maxResults <= 0 ||
request.maxResults > MAX_DOWNLOAD_ACCOUNT_PAGE_SIZE) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_ARGUMENT,
'Required "maxResults" must be a positive integer that does not exceed ' +
`${MAX_DOWNLOAD_ACCOUNT_PAGE_SIZE}.`,
);
}
});
interface GetAccountInfoRequest {
localId?: string[];
email?: string[];
phoneNumber?: string[];
federatedUserId?: Array<{
providerId: string;
rawId: string;
}>;
}
/**
* Instantiates the getAccountInfo endpoint settings.
*
* @internal
*/
export const FIREBASE_AUTH_GET_ACCOUNT_INFO = new ApiSettings('/accounts:lookup', 'POST')
// Set request validator.
.setRequestValidator((request: GetAccountInfoRequest) => {
if (!request.localId && !request.email && !request.phoneNumber && !request.federatedUserId) {
throw new FirebaseAuthError(
AuthClientErrorCode.INTERNAL_ERROR,
'INTERNAL ASSERT FAILED: Server request is missing user identifier');
}
})
// Set response validator.
.setResponseValidator((response: any) => {
if (!response.users || !response.users.length) {
throw new FirebaseAuthError(AuthClientErrorCode.USER_NOT_FOUND);
}
});
/**
* Instantiates the getAccountInfo endpoint settings for use when fetching info
* for multiple accounts.
*
* @internal
*/
export const FIREBASE_AUTH_GET_ACCOUNTS_INFO = new ApiSettings('/accounts:lookup', 'POST')
// Set request validator.
.setRequestValidator((request: GetAccountInfoRequest) => {
if (!request.localId && !request.email && !request.phoneNumber && !request.federatedUserId) {
throw new FirebaseAuthError(
AuthClientErrorCode.INTERNAL_ERROR,
'INTERNAL ASSERT FAILED: Server request is missing user identifier');
}
});
/**
* Instantiates the deleteAccount endpoint settings.
*
* @internal
*/
export const FIREBASE_AUTH_DELETE_ACCOUNT = new ApiSettings('/accounts:delete', 'POST')
// Set request validator.
.setRequestValidator((request: any) => {
if (!request.localId) {
throw new FirebaseAuthError(
AuthClientErrorCode.INTERNAL_ERROR,
'INTERNAL ASSERT FAILED: Server request is missing user identifier');
}
});
interface BatchDeleteAccountsRequest {
localIds?: string[];
force?: boolean;
}
interface BatchDeleteErrorInfo {
index?: number;
localId?: string;
message?: string;
}
export interface BatchDeleteAccountsResponse {
errors?: BatchDeleteErrorInfo[];
}
/**
* @internal
*/
export const FIREBASE_AUTH_BATCH_DELETE_ACCOUNTS = new ApiSettings('/accounts:batchDelete', 'POST')
.setRequestValidator((request: BatchDeleteAccountsRequest) => {
if (!request.localIds) {
throw new FirebaseAuthError(
AuthClientErrorCode.INTERNAL_ERROR,
'INTERNAL ASSERT FAILED: Server request is missing user identifiers');
}
if (typeof request.force === 'undefined' || request.force !== true) {
throw new FirebaseAuthError(
AuthClientErrorCode.INTERNAL_ERROR,
'INTERNAL ASSERT FAILED: Server request is missing force=true field');
}
})
.setResponseValidator((response: BatchDeleteAccountsResponse) => {
const errors = response.errors || [];
errors.forEach((batchDeleteErrorInfo) => {
if (typeof batchDeleteErrorInfo.index === 'undefined') {
throw new FirebaseAuthError(
AuthClientErrorCode.INTERNAL_ERROR,
'INTERNAL ASSERT FAILED: Server BatchDeleteAccountResponse is missing an errors.index field');
}
if (!batchDeleteErrorInfo.localId) {
throw new FirebaseAuthError(
AuthClientErrorCode.INTERNAL_ERROR,
'INTERNAL ASSERT FAILED: Server BatchDeleteAccountResponse is missing an errors.localId field');
}
// Allow the (error) message to be missing/undef.
});
});
/**
* Instantiates the setAccountInfo endpoint settings for updating existing accounts.
*
* @internal
*/
export const FIREBASE_AUTH_SET_ACCOUNT_INFO = new ApiSettings('/accounts:update', 'POST')
// Set request validator.
.setRequestValidator((request: any) => {
// localId is a required parameter.
if (typeof request.localId === 'undefined') {
throw new FirebaseAuthError(
AuthClientErrorCode.INTERNAL_ERROR,
'INTERNAL ASSERT FAILED: Server request is missing user identifier');
}
// Throw error when tenantId is passed in POST body.
if (typeof request.tenantId !== 'undefined') {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_ARGUMENT,
'"tenantId" is an invalid "UpdateRequest" property.');
}
validateCreateEditRequest(request, WriteOperationType.Update);
})
// Set response validator.
.setResponseValidator((response: any) => {
// If the localId is not returned, then the request failed.
if (!response.localId) {
throw new FirebaseAuthError(AuthClientErrorCode.USER_NOT_FOUND);
}
});
/**
* Instantiates the signupNewUser endpoint settings for creating a new user with or without
* uid being specified. The backend will create a new one if not provided and return it.
*
* @internal
*/
export const FIREBASE_AUTH_SIGN_UP_NEW_USER = new ApiSettings('/accounts', 'POST')
// Set request validator.
.setRequestValidator((request: any) => {
// signupNewUser does not support customAttributes.
if (typeof request.customAttributes !== 'undefined') {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_ARGUMENT,
'"customAttributes" cannot be set when creating a new user.',
);
}
// signupNewUser does not support validSince.
if (typeof request.validSince !== 'undefined') {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_ARGUMENT,
'"validSince" cannot be set when creating a new user.',
);
}
// Throw error when tenantId is passed in POST body.
if (typeof request.tenantId !== 'undefined') {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_ARGUMENT,
'"tenantId" is an invalid "CreateRequest" property.');
}
validateCreateEditRequest(request, WriteOperationType.Create);
})
// Set response validator.
.setResponseValidator((response: any) => {
// If the localId is not returned, then the request failed.
if (!response.localId) {
throw new FirebaseAuthError(
AuthClientErrorCode.INTERNAL_ERROR,
'INTERNAL ASSERT FAILED: Unable to create new user');
}
});
const FIREBASE_AUTH_GET_OOB_CODE = new ApiSettings('/accounts:sendOobCode', 'POST')
// Set request validator.
.setRequestValidator((request: any) => {
if (!validator.isEmail(request.email)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_EMAIL,
);
}
if (typeof request.newEmail !== 'undefined' && !validator.isEmail(request.newEmail)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_NEW_EMAIL,
);
}
if (EMAIL_ACTION_REQUEST_TYPES.indexOf(request.requestType) === -1) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_ARGUMENT,
`"${request.requestType}" is not a supported email action request type.`,
);
}
})
// Set response validator.
.setResponseValidator((response: any) => {
// If the oobLink is not returned, then the request failed.
if (!response.oobLink) {
throw new FirebaseAuthError(
AuthClientErrorCode.INTERNAL_ERROR,
'INTERNAL ASSERT FAILED: Unable to create the email action link');
}
});
/**
* Instantiates the retrieve OIDC configuration endpoint settings.
*
* @internal
*/
const GET_OAUTH_IDP_CONFIG = new ApiSettings('/oauthIdpConfigs/{providerId}', 'GET')
// Set response validator.
.setResponseValidator((response: any) => {
// Response should always contain the OIDC provider resource name.
if (!validator.isNonEmptyString(response.name)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INTERNAL_ERROR,
'INTERNAL ASSERT FAILED: Unable to get OIDC configuration',
);
}
});
/**
* Instantiates the delete OIDC configuration endpoint settings.
*
* @internal
*/
const DELETE_OAUTH_IDP_CONFIG = new ApiSettings('/oauthIdpConfigs/{providerId}', 'DELETE');
/**
* Instantiates the create OIDC configuration endpoint settings.
*
* @internal
*/
const CREATE_OAUTH_IDP_CONFIG = new ApiSettings('/oauthIdpConfigs?oauthIdpConfigId={providerId}', 'POST')
// Set response validator.
.setResponseValidator((response: any) => {
// Response should always contain the OIDC provider resource name.
if (!validator.isNonEmptyString(response.name)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INTERNAL_ERROR,
'INTERNAL ASSERT FAILED: Unable to create new OIDC configuration',
);
}
});
/**
* Instantiates the update OIDC configuration endpoint settings.
*
* @internal
*/
const UPDATE_OAUTH_IDP_CONFIG = new ApiSettings('/oauthIdpConfigs/{providerId}?updateMask={updateMask}', 'PATCH')
// Set response validator.
.setResponseValidator((response: any) => {
// Response should always contain the configuration resource name.
if (!validator.isNonEmptyString(response.name)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INTERNAL_ERROR,
'INTERNAL ASSERT FAILED: Unable to update OIDC configuration',
);
}
});
/**
* Instantiates the list OIDC configuration endpoint settings.
*
* @internal
*/
const LIST_OAUTH_IDP_CONFIGS = new ApiSettings('/oauthIdpConfigs', 'GET')
// Set request validator.
.setRequestValidator((request: any) => {
// Validate next page token.
if (typeof request.pageToken !== 'undefined' &&
!validator.isNonEmptyString(request.pageToken)) {
throw new FirebaseAuthError(AuthClientErrorCode.INVALID_PAGE_TOKEN);
}
// Validate max results.
if (!validator.isNumber(request.pageSize) ||
request.pageSize <= 0 ||
request.pageSize > MAX_LIST_PROVIDER_CONFIGURATION_PAGE_SIZE) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_ARGUMENT,
'Required "maxResults" must be a positive integer that does not exceed ' +
`${MAX_LIST_PROVIDER_CONFIGURATION_PAGE_SIZE}.`,
);
}
});
/**
* Instantiates the retrieve SAML configuration endpoint settings.
*
* @internal
*/
const GET_INBOUND_SAML_CONFIG = new ApiSettings('/inboundSamlConfigs/{providerId}', 'GET')
// Set response validator.
.setResponseValidator((response: any) => {
// Response should always contain the SAML provider resource name.
if (!validator.isNonEmptyString(response.name)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INTERNAL_ERROR,
'INTERNAL ASSERT FAILED: Unable to get SAML configuration',
);
}
});
/**
* Instantiates the delete SAML configuration endpoint settings.
*
* @internal
*/
const DELETE_INBOUND_SAML_CONFIG = new ApiSettings('/inboundSamlConfigs/{providerId}', 'DELETE');
/**
* Instantiates the create SAML configuration endpoint settings.
*
* @internal
*/
const CREATE_INBOUND_SAML_CONFIG = new ApiSettings('/inboundSamlConfigs?inboundSamlConfigId={providerId}', 'POST')
// Set response validator.
.setResponseValidator((response: any) => {
// Response should always contain the SAML provider resource name.
if (!validator.isNonEmptyString(response.name)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INTERNAL_ERROR,
'INTERNAL ASSERT FAILED: Unable to create new SAML configuration',
);
}
});
/**
* Instantiates the update SAML configuration endpoint settings.
*
* @internal
*/
const UPDATE_INBOUND_SAML_CONFIG = new ApiSettings('/inboundSamlConfigs/{providerId}?updateMask={updateMask}', 'PATCH')
// Set response validator.
.setResponseValidator((response: any) => {
// Response should always contain the configuration resource name.
if (!validator.isNonEmptyString(response.name)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INTERNAL_ERROR,
'INTERNAL ASSERT FAILED: Unable to update SAML configuration',
);
}
});
/**
* Instantiates the list SAML configuration endpoint settings.
*
* @internal
*/
const LIST_INBOUND_SAML_CONFIGS = new ApiSettings('/inboundSamlConfigs', 'GET')
// Set request validator.
.setRequestValidator((request: any) => {
// Validate next page token.
if (typeof request.pageToken !== 'undefined' &&
!validator.isNonEmptyString(request.pageToken)) {
throw new FirebaseAuthError(AuthClientErrorCode.INVALID_PAGE_TOKEN);
}
// Validate max results.
if (!validator.isNumber(request.pageSize) ||
request.pageSize <= 0 ||
request.pageSize > MAX_LIST_PROVIDER_CONFIGURATION_PAGE_SIZE) {
throw new FirebaseAuthError(