/
auth-config.ts
1596 lines (1449 loc) · 49.7 KB
/
auth-config.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
/*!
* Copyright 2018 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 { deepCopy } from '../utils/deep-copy';
import { AuthClientErrorCode, FirebaseAuthError } from '../utils/error';
/**
* Interface representing base properties of a user-enrolled second factor for a
* `CreateRequest`.
*/
export interface BaseCreateMultiFactorInfoRequest {
/**
* The optional display name for an enrolled second factor.
*/
displayName?: string;
/**
* The type identifier of the second factor. For SMS second factors, this is `phone`.
*/
factorId: string;
}
/**
* Interface representing a phone specific user-enrolled second factor for a
* `CreateRequest`.
*/
export interface CreatePhoneMultiFactorInfoRequest extends BaseCreateMultiFactorInfoRequest {
/**
* The phone number associated with a phone second factor.
*/
phoneNumber: string;
}
/**
* Type representing the properties of a user-enrolled second factor
* for a `CreateRequest`.
*/
export type CreateMultiFactorInfoRequest = | CreatePhoneMultiFactorInfoRequest;
/**
* Interface representing common properties of a user-enrolled second factor
* for an `UpdateRequest`.
*/
export interface BaseUpdateMultiFactorInfoRequest {
/**
* The ID of the enrolled second factor. This ID is unique to the user. When not provided,
* a new one is provisioned by the Auth server.
*/
uid?: string;
/**
* The optional display name for an enrolled second factor.
*/
displayName?: string;
/**
* The optional date the second factor was enrolled, formatted as a UTC string.
*/
enrollmentTime?: string;
/**
* The type identifier of the second factor. For SMS second factors, this is `phone`.
*/
factorId: string;
}
/**
* Interface representing a phone specific user-enrolled second factor
* for an `UpdateRequest`.
*/
export interface UpdatePhoneMultiFactorInfoRequest extends BaseUpdateMultiFactorInfoRequest {
/**
* The phone number associated with a phone second factor.
*/
phoneNumber: string;
}
/**
* Type representing the properties of a user-enrolled second factor
* for an `UpdateRequest`.
*/
export type UpdateMultiFactorInfoRequest = | UpdatePhoneMultiFactorInfoRequest;
/**
* The multi-factor related user settings for create operations.
*/
export interface MultiFactorCreateSettings {
/**
* The created user's list of enrolled second factors.
*/
enrolledFactors: CreateMultiFactorInfoRequest[];
}
/**
* The multi-factor related user settings for update operations.
*/
export interface MultiFactorUpdateSettings {
/**
* The updated list of enrolled second factors. The provided list overwrites the user's
* existing list of second factors.
* When null is passed, all of the user's existing second factors are removed.
*/
enrolledFactors: UpdateMultiFactorInfoRequest[] | null;
}
/**
* Interface representing the properties to update on the provided user.
*/
export interface UpdateRequest {
/**
* Whether or not the user is disabled: `true` for disabled;
* `false` for enabled.
*/
disabled?: boolean;
/**
* The user's display name.
*/
displayName?: string | null;
/**
* The user's primary email.
*/
email?: string;
/**
* Whether or not the user's primary email is verified.
*/
emailVerified?: boolean;
/**
* The user's unhashed password.
*/
password?: string;
/**
* The user's primary phone number.
*/
phoneNumber?: string | null;
/**
* The user's photo URL.
*/
photoURL?: string | null;
/**
* The user's updated multi-factor related properties.
*/
multiFactor?: MultiFactorUpdateSettings;
/**
* Links this user to the specified provider.
*
* Linking a provider to an existing user account does not invalidate the
* refresh token of that account. In other words, the existing account
* would continue to be able to access resources, despite not having used
* the newly linked provider to log in. If you wish to force the user to
* authenticate with this new provider, you need to (a) revoke their
* refresh token (see
* https://firebase.google.com/docs/auth/admin/manage-sessions#revoke_refresh_tokens),
* and (b) ensure no other authentication methods are present on this
* account.
*/
providerToLink?: UserProvider;
/**
* Unlinks this user from the specified providers.
*/
providersToUnlink?: string[];
}
/**
* Represents a user identity provider that can be associated with a Firebase user.
*/
export interface UserProvider {
/**
* The user identifier for the linked provider.
*/
uid?: string;
/**
* The display name for the linked provider.
*/
displayName?: string;
/**
* The email for the linked provider.
*/
email?: string;
/**
* The phone number for the linked provider.
*/
phoneNumber?: string;
/**
* The photo URL for the linked provider.
*/
photoURL?: string;
/**
* The linked provider ID (for example, "google.com" for the Google provider).
*/
providerId?: string;
}
/**
* Interface representing the properties to set on a new user record to be
* created.
*/
export interface CreateRequest extends UpdateRequest {
/**
* The user's `uid`.
*/
uid?: string;
/**
* The user's multi-factor related properties.
*/
multiFactor?: MultiFactorCreateSettings;
}
/**
* The response interface for listing provider configs. This is only available
* when listing all identity providers' configurations via
* {@link BaseAuth.listProviderConfigs}.
*/
export interface ListProviderConfigResults {
/**
* The list of providers for the specified type in the current page.
*/
providerConfigs: AuthProviderConfig[];
/**
* The next page token, if available.
*/
pageToken?: string;
}
/**
* The filter interface used for listing provider configurations. This is used
* when specifying how to list configured identity providers via
* {@link BaseAuth.listProviderConfigs}.
*/
export interface AuthProviderConfigFilter {
/**
* The Auth provider configuration filter. This can be either `saml` or `oidc`.
* The former is used to look up SAML providers only, while the latter is used
* for OIDC providers.
*/
type: 'saml' | 'oidc';
/**
* The maximum number of results to return per page. The default and maximum is
* 100.
*/
maxResults?: number;
/**
* The next page token. When not specified, the lookup starts from the beginning
* of the list.
*/
pageToken?: string;
}
/**
* The request interface for updating a SAML Auth provider. This is used
* when updating a SAML provider's configuration via
* {@link BaseAuth.updateProviderConfig}.
*/
export interface SAMLUpdateAuthProviderRequest {
/**
* The SAML provider's updated display name. If not provided, the existing
* configuration's value is not modified.
*/
displayName?: string;
/**
* Whether the SAML provider is enabled or not. If not provided, the existing
* configuration's setting is not modified.
*/
enabled?: boolean;
/**
* The SAML provider's updated IdP entity ID. If not provided, the existing
* configuration's value is not modified.
*/
idpEntityId?: string;
/**
* The SAML provider's updated SSO URL. If not provided, the existing
* configuration's value is not modified.
*/
ssoURL?: string;
/**
* The SAML provider's updated list of X.509 certificated. If not provided, the
* existing configuration list is not modified.
*/
x509Certificates?: string[];
/**
* The SAML provider's updated RP entity ID. If not provided, the existing
* configuration's value is not modified.
*/
rpEntityId?: string;
/**
* The SAML provider's callback URL. If not provided, the existing
* configuration's value is not modified.
*/
callbackURL?: string;
}
/**
* The request interface for updating an OIDC Auth provider. This is used
* when updating an OIDC provider's configuration via
* {@link BaseAuth.updateProviderConfig}.
*/
export interface OIDCUpdateAuthProviderRequest {
/**
* The OIDC provider's updated display name. If not provided, the existing
* configuration's value is not modified.
*/
displayName?: string;
/**
* Whether the OIDC provider is enabled or not. If not provided, the existing
* configuration's setting is not modified.
*/
enabled?: boolean;
/**
* The OIDC provider's updated client ID. If not provided, the existing
* configuration's value is not modified.
*/
clientId?: string;
/**
* The OIDC provider's updated issuer. If not provided, the existing
* configuration's value is not modified.
*/
issuer?: string;
/**
* The OIDC provider's client secret to enable OIDC code flow.
* If not provided, the existing configuration's value is not modified.
*/
clientSecret?: string;
/**
* The OIDC provider's response object for OAuth authorization flow.
*/
responseType?: OAuthResponseType;
}
export type UpdateAuthProviderRequest =
SAMLUpdateAuthProviderRequest | OIDCUpdateAuthProviderRequest;
/** A maximum of 10 test phone number / code pairs can be configured. */
export const MAXIMUM_TEST_PHONE_NUMBERS = 10;
/** The server side SAML configuration request interface. */
export interface SAMLConfigServerRequest {
idpConfig?: {
idpEntityId?: string;
ssoUrl?: string;
idpCertificates?: Array<{
x509Certificate: string;
}>;
signRequest?: boolean;
};
spConfig?: {
spEntityId?: string;
callbackUri?: string;
};
displayName?: string;
enabled?: boolean;
[key: string]: any;
}
/** The server side SAML configuration response interface. */
export interface SAMLConfigServerResponse {
// Used when getting config.
// projects/${projectId}/inboundSamlConfigs/${providerId}
name?: string;
idpConfig?: {
idpEntityId?: string;
ssoUrl?: string;
idpCertificates?: Array<{
x509Certificate: string;
}>;
signRequest?: boolean;
};
spConfig?: {
spEntityId?: string;
callbackUri?: string;
};
displayName?: string;
enabled?: boolean;
}
/** The server side OIDC configuration request interface. */
export interface OIDCConfigServerRequest {
clientId?: string;
issuer?: string;
displayName?: string;
enabled?: boolean;
clientSecret?: string;
responseType?: OAuthResponseType;
[key: string]: any;
}
/** The server side OIDC configuration response interface. */
export interface OIDCConfigServerResponse {
// Used when getting config.
// projects/${projectId}/oauthIdpConfigs/${providerId}
name?: string;
clientId?: string;
issuer?: string;
displayName?: string;
enabled?: boolean;
clientSecret?: string;
responseType?: OAuthResponseType;
}
/** The server side email configuration request interface. */
export interface EmailSignInConfigServerRequest {
allowPasswordSignup?: boolean;
enableEmailLinkSignin?: boolean;
}
/** Identifies the server side second factor type. */
type AuthFactorServerType = 'PHONE_SMS';
/** Client Auth factor type to server auth factor type mapping. */
const AUTH_FACTOR_CLIENT_TO_SERVER_TYPE: {[key: string]: AuthFactorServerType} = {
phone: 'PHONE_SMS',
};
/** Server Auth factor type to client auth factor type mapping. */
const AUTH_FACTOR_SERVER_TO_CLIENT_TYPE: {[key: string]: AuthFactorType} =
Object.keys(AUTH_FACTOR_CLIENT_TO_SERVER_TYPE)
.reduce((res: {[key: string]: AuthFactorType}, key) => {
res[AUTH_FACTOR_CLIENT_TO_SERVER_TYPE[key]] = key as AuthFactorType;
return res;
}, {});
/** Server side multi-factor configuration. */
export interface MultiFactorAuthServerConfig {
state?: MultiFactorConfigState;
enabledProviders?: AuthFactorServerType[];
}
/**
* Identifies a second factor type.
*/
export type AuthFactorType = 'phone';
/**
* Identifies a multi-factor configuration state.
*/
export type MultiFactorConfigState = 'ENABLED' | 'DISABLED';
/**
* Interface representing a multi-factor configuration.
* This can be used to define whether multi-factor authentication is enabled
* or disabled and the list of second factor challenges that are supported.
*/
export interface MultiFactorConfig {
/**
* The multi-factor config state.
*/
state: MultiFactorConfigState;
/**
* The list of identifiers for enabled second factors.
* Currently only ‘phone’ is supported.
*/
factorIds?: AuthFactorType[];
}
/**
* Defines the multi-factor config class used to convert client side MultiFactorConfig
* to a format that is understood by the Auth server.
*/
export class MultiFactorAuthConfig implements MultiFactorConfig {
public readonly state: MultiFactorConfigState;
public readonly factorIds: AuthFactorType[];
/**
* Static method to convert a client side request to a MultiFactorAuthServerConfig.
* Throws an error if validation fails.
*
* @param options - The options object to convert to a server request.
* @returns The resulting server request.
* @internal
*/
public static buildServerRequest(options: MultiFactorConfig): MultiFactorAuthServerConfig {
const request: MultiFactorAuthServerConfig = {};
MultiFactorAuthConfig.validate(options);
if (Object.prototype.hasOwnProperty.call(options, 'state')) {
request.state = options.state;
}
if (Object.prototype.hasOwnProperty.call(options, 'factorIds')) {
(options.factorIds || []).forEach((factorId) => {
if (typeof request.enabledProviders === 'undefined') {
request.enabledProviders = [];
}
request.enabledProviders.push(AUTH_FACTOR_CLIENT_TO_SERVER_TYPE[factorId]);
});
// In case an empty array is passed. Ensure it gets populated so the array is cleared.
if (options.factorIds && options.factorIds.length === 0) {
request.enabledProviders = [];
}
}
return request;
}
/**
* Validates the MultiFactorConfig options object. Throws an error on failure.
*
* @param options - The options object to validate.
*/
private static validate(options: MultiFactorConfig): void {
const validKeys = {
state: true,
factorIds: true,
};
if (!validator.isNonNullObject(options)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_CONFIG,
'"MultiFactorConfig" must be a non-null object.',
);
}
// Check for unsupported top level attributes.
for (const key in options) {
if (!(key in validKeys)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_CONFIG,
`"${key}" is not a valid MultiFactorConfig parameter.`,
);
}
}
// Validate content.
if (typeof options.state !== 'undefined' &&
options.state !== 'ENABLED' &&
options.state !== 'DISABLED') {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_CONFIG,
'"MultiFactorConfig.state" must be either "ENABLED" or "DISABLED".',
);
}
if (typeof options.factorIds !== 'undefined') {
if (!validator.isArray(options.factorIds)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_CONFIG,
'"MultiFactorConfig.factorIds" must be an array of valid "AuthFactorTypes".',
);
}
// Validate content of array.
options.factorIds.forEach((factorId) => {
if (typeof AUTH_FACTOR_CLIENT_TO_SERVER_TYPE[factorId] === 'undefined') {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_CONFIG,
`"${factorId}" is not a valid "AuthFactorType".`,
);
}
});
}
}
/**
* The MultiFactorAuthConfig constructor.
*
* @param response - The server side response used to initialize the
* MultiFactorAuthConfig object.
* @constructor
* @internal
*/
constructor(response: MultiFactorAuthServerConfig) {
if (typeof response.state === 'undefined') {
throw new FirebaseAuthError(
AuthClientErrorCode.INTERNAL_ERROR,
'INTERNAL ASSERT FAILED: Invalid multi-factor configuration response');
}
this.state = response.state;
this.factorIds = [];
(response.enabledProviders || []).forEach((enabledProvider) => {
// Ignore unsupported types. It is possible the current admin SDK version is
// not up to date and newer backend types are supported.
if (typeof AUTH_FACTOR_SERVER_TO_CLIENT_TYPE[enabledProvider] !== 'undefined') {
this.factorIds.push(AUTH_FACTOR_SERVER_TO_CLIENT_TYPE[enabledProvider]);
}
})
}
/** @returns The plain object representation of the multi-factor config instance. */
public toJSON(): object {
return {
state: this.state,
factorIds: this.factorIds,
};
}
}
/**
* Validates the provided map of test phone number / code pairs.
* @param testPhoneNumbers - The phone number / code pairs to validate.
*/
export function validateTestPhoneNumbers(
testPhoneNumbers: {[phoneNumber: string]: string},
): void {
if (!validator.isObject(testPhoneNumbers)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_ARGUMENT,
'"testPhoneNumbers" must be a map of phone number / code pairs.',
);
}
if (Object.keys(testPhoneNumbers).length > MAXIMUM_TEST_PHONE_NUMBERS) {
throw new FirebaseAuthError(AuthClientErrorCode.MAXIMUM_TEST_PHONE_NUMBER_EXCEEDED);
}
for (const phoneNumber in testPhoneNumbers) {
// Validate phone number.
if (!validator.isPhoneNumber(phoneNumber)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_TESTING_PHONE_NUMBER,
`"${phoneNumber}" is not a valid E.164 standard compliant phone number.`
);
}
// Validate code.
if (!validator.isString(testPhoneNumbers[phoneNumber]) ||
!/^[\d]{6}$/.test(testPhoneNumbers[phoneNumber])) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_TESTING_PHONE_NUMBER,
`"${testPhoneNumbers[phoneNumber]}" is not a valid 6 digit code string.`
);
}
}
}
/**
* The email sign in provider configuration.
*/
export interface EmailSignInProviderConfig {
/**
* Whether email provider is enabled.
*/
enabled: boolean;
/**
* Whether password is required for email sign-in. When not required,
* email sign-in can be performed with password or via email link sign-in.
*/
passwordRequired?: boolean; // In the backend API, default is true if not provided
}
/**
* Defines the email sign-in config class used to convert client side EmailSignInConfig
* to a format that is understood by the Auth server.
*
* @internal
*/
export class EmailSignInConfig implements EmailSignInProviderConfig {
public readonly enabled: boolean;
public readonly passwordRequired?: boolean;
/**
* Static method to convert a client side request to a EmailSignInConfigServerRequest.
* Throws an error if validation fails.
*
* @param options - The options object to convert to a server request.
* @returns The resulting server request.
* @internal
*/
public static buildServerRequest(options: EmailSignInProviderConfig): EmailSignInConfigServerRequest {
const request: EmailSignInConfigServerRequest = {};
EmailSignInConfig.validate(options);
if (Object.prototype.hasOwnProperty.call(options, 'enabled')) {
request.allowPasswordSignup = options.enabled;
}
if (Object.prototype.hasOwnProperty.call(options, 'passwordRequired')) {
request.enableEmailLinkSignin = !options.passwordRequired;
}
return request;
}
/**
* Validates the EmailSignInConfig options object. Throws an error on failure.
*
* @param options - The options object to validate.
*/
private static validate(options: EmailSignInProviderConfig): void {
// TODO: Validate the request.
const validKeys = {
enabled: true,
passwordRequired: true,
};
if (!validator.isNonNullObject(options)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_ARGUMENT,
'"EmailSignInConfig" must be a non-null object.',
);
}
// Check for unsupported top level attributes.
for (const key in options) {
if (!(key in validKeys)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_ARGUMENT,
`"${key}" is not a valid EmailSignInConfig parameter.`,
);
}
}
// Validate content.
if (typeof options.enabled !== 'undefined' &&
!validator.isBoolean(options.enabled)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_ARGUMENT,
'"EmailSignInConfig.enabled" must be a boolean.',
);
}
if (typeof options.passwordRequired !== 'undefined' &&
!validator.isBoolean(options.passwordRequired)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_ARGUMENT,
'"EmailSignInConfig.passwordRequired" must be a boolean.',
);
}
}
/**
* The EmailSignInConfig constructor.
*
* @param response - The server side response used to initialize the
* EmailSignInConfig object.
* @constructor
*/
constructor(response: {[key: string]: any}) {
if (typeof response.allowPasswordSignup === 'undefined') {
throw new FirebaseAuthError(
AuthClientErrorCode.INTERNAL_ERROR,
'INTERNAL ASSERT FAILED: Invalid email sign-in configuration response');
}
this.enabled = response.allowPasswordSignup;
this.passwordRequired = !response.enableEmailLinkSignin;
}
/** @returns The plain object representation of the email sign-in config. */
public toJSON(): object {
return {
enabled: this.enabled,
passwordRequired: this.passwordRequired,
};
}
}
/**
* The base Auth provider configuration interface.
*/
export interface BaseAuthProviderConfig {
/**
* The provider ID defined by the developer.
* For a SAML provider, this is always prefixed by `saml.`.
* For an OIDC provider, this is always prefixed by `oidc.`.
*/
providerId: string;
/**
* The user-friendly display name to the current configuration. This name is
* also used as the provider label in the Cloud Console.
*/
displayName?: string;
/**
* Whether the provider configuration is enabled or disabled. A user
* cannot sign in using a disabled provider.
*/
enabled: boolean;
}
/**
* The
* [SAML](http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html)
* Auth provider configuration interface. A SAML provider can be created via
* {@link BaseAuth.createProviderConfig}.
*/
export interface SAMLAuthProviderConfig extends BaseAuthProviderConfig {
/**
* The SAML IdP entity identifier.
*/
idpEntityId: string;
/**
* The SAML IdP SSO URL. This must be a valid URL.
*/
ssoURL: string;
/**
* The list of SAML IdP X.509 certificates issued by CA for this provider.
* Multiple certificates are accepted to prevent outages during
* IdP key rotation (for example ADFS rotates every 10 days). When the Auth
* server receives a SAML response, it will match the SAML response with the
* certificate on record. Otherwise the response is rejected.
* Developers are expected to manage the certificate updates as keys are
* rotated.
*/
x509Certificates: string[];
/**
* The SAML relying party (service provider) entity ID.
* This is defined by the developer but needs to be provided to the SAML IdP.
*/
rpEntityId: string;
/**
* This is fixed and must always be the same as the OAuth redirect URL
* provisioned by Firebase Auth,
* `https://project-id.firebaseapp.com/__/auth/handler` unless a custom
* `authDomain` is used.
* The callback URL should also be provided to the SAML IdP during
* configuration.
*/
callbackURL?: string;
}
/**
* The interface representing OIDC provider's response object for OAuth
* authorization flow.
* One of the following settings is required:
* <ul>
* <li>Set <code>code</code> to <code>true</code> for the code flow.</li>
* <li>Set <code>idToken</code> to <code>true</code> for the ID token flow.</li>
* </ul>
*/
export interface OAuthResponseType {
/**
* Whether ID token is returned from IdP's authorization endpoint.
*/
idToken?: boolean;
/**
* Whether authorization code is returned from IdP's authorization endpoint.
*/
code?: boolean;
}
/**
* The [OIDC](https://openid.net/specs/openid-connect-core-1_0-final.html) Auth
* provider configuration interface. An OIDC provider can be created via
* {@link BaseAuth.createProviderConfig}.
*/
export interface OIDCAuthProviderConfig extends BaseAuthProviderConfig {
/**
* This is the required client ID used to confirm the audience of an OIDC
* provider's
* [ID token](https://openid.net/specs/openid-connect-core-1_0-final.html#IDToken).
*/
clientId: string;
/**
* This is the required provider issuer used to match the provider issuer of
* the ID token and to determine the corresponding OIDC discovery document, eg.
* [`/.well-known/openid-configuration`](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig).
* This is needed for the following:
* <ul>
* <li>To verify the provided issuer.</li>
* <li>Determine the authentication/authorization endpoint during the OAuth
* `id_token` authentication flow.</li>
* <li>To retrieve the public signing keys via `jwks_uri` to verify the OIDC
* provider's ID token's signature.</li>
* <li>To determine the claims_supported to construct the user attributes to be
* returned in the additional user info response.</li>
* </ul>
* ID token validation will be performed as defined in the
* [spec](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation).
*/
issuer: string;
/**
* The OIDC provider's client secret to enable OIDC code flow.
*/
clientSecret?: string;
/**
* The OIDC provider's response object for OAuth authorization flow.
*/
responseType?: OAuthResponseType;
}
/**
* The Auth provider configuration type.
* {@link BaseAuth.createProviderConfig}.
*/
export type AuthProviderConfig = SAMLAuthProviderConfig | OIDCAuthProviderConfig;
/**
* Defines the SAMLConfig class used to convert a client side configuration to its
* server side representation.
*
* @internal
*/
export class SAMLConfig implements SAMLAuthProviderConfig {
public readonly enabled: boolean;
public readonly displayName?: string;
public readonly providerId: string;
public readonly idpEntityId: string;
public readonly ssoURL: string;
public readonly x509Certificates: string[];
public readonly rpEntityId: string;
public readonly callbackURL?: string;
public readonly enableRequestSigning?: boolean;
/**
* Converts a client side request to a SAMLConfigServerRequest which is the format
* accepted by the backend server.
* Throws an error if validation fails. If the request is not a SAMLConfig request,
* returns null.
*
* @param options - The options object to convert to a server request.
* @param ignoreMissingFields - Whether to ignore missing fields.
* @returns The resulting server request or null if not valid.
*/
public static buildServerRequest(
options: Partial<SAMLAuthProviderConfig>,
ignoreMissingFields = false): SAMLConfigServerRequest | null {
const makeRequest = validator.isNonNullObject(options) &&
(options.providerId || ignoreMissingFields);
if (!makeRequest) {
return null;
}
const request: SAMLConfigServerRequest = {};
// Validate options.
SAMLConfig.validate(options, ignoreMissingFields);
request.enabled = options.enabled;
request.displayName = options.displayName;
// IdP config.
if (options.idpEntityId || options.ssoURL || options.x509Certificates) {
request.idpConfig = {
idpEntityId: options.idpEntityId,
ssoUrl: options.ssoURL,
signRequest: (options as any).enableRequestSigning,
idpCertificates: typeof options.x509Certificates === 'undefined' ? undefined : [],
};
if (options.x509Certificates) {
for (const cert of (options.x509Certificates || [])) {
request.idpConfig!.idpCertificates!.push({ x509Certificate: cert });
}
}
}
// RP config.
if (options.callbackURL || options.rpEntityId) {
request.spConfig = {
spEntityId: options.rpEntityId,
callbackUri: options.callbackURL,
};
}
return request;
}
/**
* Returns the provider ID corresponding to the resource name if available.
*
* @param resourceName - The server side resource name.