firebase-admin 9.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +90 -0
  3. package/lib/app-check/app-check-api-client-internal.js +197 -0
  4. package/lib/app-check/app-check.js +79 -0
  5. package/lib/app-check/index.d.ts +160 -0
  6. package/lib/app-check/index.js +19 -0
  7. package/lib/app-check/token-generator.js +161 -0
  8. package/lib/app-check/token-verifier.js +152 -0
  9. package/lib/auth/action-code-settings-builder.js +118 -0
  10. package/lib/auth/auth-api-request.js +1856 -0
  11. package/lib/auth/auth-config.js +636 -0
  12. package/lib/auth/auth.js +836 -0
  13. package/lib/auth/identifier.js +40 -0
  14. package/lib/auth/index.d.ts +1927 -0
  15. package/lib/auth/index.js +18 -0
  16. package/lib/auth/tenant-manager.js +140 -0
  17. package/lib/auth/tenant.js +171 -0
  18. package/lib/auth/token-generator.js +200 -0
  19. package/lib/auth/token-verifier.js +259 -0
  20. package/lib/auth/user-import-builder.js +387 -0
  21. package/lib/auth/user-record.js +346 -0
  22. package/lib/credential/credential-internal.js +391 -0
  23. package/lib/credential/credential.js +44 -0
  24. package/lib/credential/index.d.ts +169 -0
  25. package/lib/credential/index.js +23 -0
  26. package/lib/database/database-internal.js +266 -0
  27. package/lib/database/index.d.ts +89 -0
  28. package/lib/database/index.js +31 -0
  29. package/lib/default-namespace.js +31 -0
  30. package/lib/firebase-app.js +349 -0
  31. package/lib/firebase-namespace-api.d.ts +243 -0
  32. package/lib/firebase-namespace-api.js +18 -0
  33. package/lib/firebase-namespace.d.ts +31 -0
  34. package/lib/firebase-namespace.js +417 -0
  35. package/lib/firestore/firestore-internal.js +105 -0
  36. package/lib/firestore/index.d.ts +50 -0
  37. package/lib/firestore/index.js +47 -0
  38. package/lib/index.d.ts +24 -0
  39. package/lib/index.js +27 -0
  40. package/lib/installations/index.d.ts +81 -0
  41. package/lib/installations/index.js +18 -0
  42. package/lib/installations/installations-request-handler.js +117 -0
  43. package/lib/installations/installations.js +62 -0
  44. package/lib/instance-id/index.d.ts +83 -0
  45. package/lib/instance-id/index.js +18 -0
  46. package/lib/instance-id/instance-id.js +87 -0
  47. package/lib/machine-learning/index.d.ts +249 -0
  48. package/lib/machine-learning/index.js +18 -0
  49. package/lib/machine-learning/machine-learning-api-client.js +304 -0
  50. package/lib/machine-learning/machine-learning-utils.js +62 -0
  51. package/lib/machine-learning/machine-learning.js +364 -0
  52. package/lib/messaging/batch-request-internal.js +129 -0
  53. package/lib/messaging/index.d.ts +1174 -0
  54. package/lib/messaging/index.js +18 -0
  55. package/lib/messaging/messaging-api-request-internal.js +128 -0
  56. package/lib/messaging/messaging-errors-internal.js +106 -0
  57. package/lib/messaging/messaging-internal.js +484 -0
  58. package/lib/messaging/messaging.js +846 -0
  59. package/lib/project-management/android-app.js +176 -0
  60. package/lib/project-management/index.d.ts +363 -0
  61. package/lib/project-management/index.js +41 -0
  62. package/lib/project-management/ios-app.js +88 -0
  63. package/lib/project-management/project-management-api-request-internal.js +273 -0
  64. package/lib/project-management/project-management.js +254 -0
  65. package/lib/remote-config/index.d.ts +369 -0
  66. package/lib/remote-config/index.js +18 -0
  67. package/lib/remote-config/remote-config-api-client-internal.js +407 -0
  68. package/lib/remote-config/remote-config.js +304 -0
  69. package/lib/security-rules/index.d.ts +216 -0
  70. package/lib/security-rules/index.js +18 -0
  71. package/lib/security-rules/security-rules-api-client-internal.js +237 -0
  72. package/lib/security-rules/security-rules-internal.js +41 -0
  73. package/lib/security-rules/security-rules.js +310 -0
  74. package/lib/storage/index.d.ts +60 -0
  75. package/lib/storage/index.js +18 -0
  76. package/lib/storage/storage.js +123 -0
  77. package/lib/utils/api-request.js +845 -0
  78. package/lib/utils/crypto-signer.js +237 -0
  79. package/lib/utils/deep-copy.js +78 -0
  80. package/lib/utils/error.js +1063 -0
  81. package/lib/utils/index.js +217 -0
  82. package/lib/utils/jwt.js +355 -0
  83. package/lib/utils/validator.js +271 -0
  84. package/package.json +122 -0
@@ -0,0 +1,836 @@
1
+ /*! firebase-admin v9.12.0 */
2
+ "use strict";
3
+ /*!
4
+ * @license
5
+ * Copyright 2017 Google Inc.
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+ var __extends = (this && this.__extends) || (function () {
20
+ var extendStatics = function (d, b) {
21
+ extendStatics = Object.setPrototypeOf ||
22
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23
+ function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24
+ return extendStatics(d, b);
25
+ };
26
+ return function (d, b) {
27
+ extendStatics(d, b);
28
+ function __() { this.constructor = d; }
29
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30
+ };
31
+ })();
32
+ Object.defineProperty(exports, "__esModule", { value: true });
33
+ exports.Auth = exports.TenantAwareAuth = exports.BaseAuth = void 0;
34
+ var deep_copy_1 = require("../utils/deep-copy");
35
+ var user_record_1 = require("./user-record");
36
+ var identifier_1 = require("./identifier");
37
+ var token_generator_1 = require("./token-generator");
38
+ var auth_api_request_1 = require("./auth-api-request");
39
+ var error_1 = require("../utils/error");
40
+ var utils = require("../utils/index");
41
+ var validator = require("../utils/validator");
42
+ var token_verifier_1 = require("./token-verifier");
43
+ var auth_config_1 = require("./auth-config");
44
+ var tenant_manager_1 = require("./tenant-manager");
45
+ var crypto_signer_1 = require("../utils/crypto-signer");
46
+ /**
47
+ * Base Auth class. Mainly used for user management APIs.
48
+ */
49
+ var BaseAuth = /** @class */ (function () {
50
+ /**
51
+ * The BaseAuth class constructor.
52
+ *
53
+ * @param app The FirebaseApp to associate with this Auth instance.
54
+ * @param authRequestHandler The RPC request handler for this instance.
55
+ * @param tokenGenerator Optional token generator. If not specified, a
56
+ * (non-tenant-aware) instance will be created. Use this paramter to
57
+ * specify a tenant-aware tokenGenerator.
58
+ * @constructor
59
+ */
60
+ function BaseAuth(app, authRequestHandler, tokenGenerator) {
61
+ this.authRequestHandler = authRequestHandler;
62
+ if (tokenGenerator) {
63
+ this.tokenGenerator = tokenGenerator;
64
+ }
65
+ else {
66
+ this.tokenGenerator = createFirebaseTokenGenerator(app);
67
+ }
68
+ this.sessionCookieVerifier = token_verifier_1.createSessionCookieVerifier(app);
69
+ this.idTokenVerifier = token_verifier_1.createIdTokenVerifier(app);
70
+ }
71
+ /**
72
+ * Creates a new custom token that can be sent back to a client to use with
73
+ * signInWithCustomToken().
74
+ *
75
+ * @param {string} uid The uid to use as the JWT subject.
76
+ * @param {object=} developerClaims Optional additional claims to include in the JWT payload.
77
+ *
78
+ * @return {Promise<string>} A JWT for the provided payload.
79
+ */
80
+ BaseAuth.prototype.createCustomToken = function (uid, developerClaims) {
81
+ return this.tokenGenerator.createCustomToken(uid, developerClaims);
82
+ };
83
+ /**
84
+ * Verifies a JWT auth token. Returns a promise with the token‘s claims.
85
+ * Rejects the promise if the token cannot be verified.
86
+ * If `checkRevoked` is set to true, first verifies whether the corresponding
87
+ * user is disabled.
88
+ * If yes, an `auth/user-disabled` error is thrown.
89
+ * If no, verifies if the session corresponding to the ID token was revoked.
90
+ * If the corresponding user's session was invalidated, an
91
+ * `auth/id-token-revoked` error is thrown.
92
+ * If not specified the check is not applied.
93
+ *
94
+ * @param {string} idToken The JWT to verify.
95
+ * @param {boolean=} checkRevoked Whether to check if the ID token is revoked.
96
+ * @return {Promise<DecodedIdToken>} A promise that will be fulfilled after
97
+ * a successful verification.
98
+ */
99
+ BaseAuth.prototype.verifyIdToken = function (idToken, checkRevoked) {
100
+ var _this = this;
101
+ if (checkRevoked === void 0) { checkRevoked = false; }
102
+ var isEmulator = auth_api_request_1.useEmulator();
103
+ return this.idTokenVerifier.verifyJWT(idToken, isEmulator)
104
+ .then(function (decodedIdToken) {
105
+ // Whether to check if the token was revoked.
106
+ if (checkRevoked || isEmulator) {
107
+ return _this.verifyDecodedJWTNotRevokedOrDisabled(decodedIdToken, error_1.AuthClientErrorCode.ID_TOKEN_REVOKED);
108
+ }
109
+ return decodedIdToken;
110
+ });
111
+ };
112
+ /**
113
+ * Looks up the user identified by the provided user id and returns a promise that is
114
+ * fulfilled with a user record for the given user if that user is found.
115
+ *
116
+ * @param {string} uid The uid of the user to look up.
117
+ * @return {Promise<UserRecord>} A promise that resolves with the corresponding user record.
118
+ */
119
+ BaseAuth.prototype.getUser = function (uid) {
120
+ return this.authRequestHandler.getAccountInfoByUid(uid)
121
+ .then(function (response) {
122
+ // Returns the user record populated with server response.
123
+ return new user_record_1.UserRecord(response.users[0]);
124
+ });
125
+ };
126
+ /**
127
+ * Looks up the user identified by the provided email and returns a promise that is
128
+ * fulfilled with a user record for the given user if that user is found.
129
+ *
130
+ * @param {string} email The email of the user to look up.
131
+ * @return {Promise<UserRecord>} A promise that resolves with the corresponding user record.
132
+ */
133
+ BaseAuth.prototype.getUserByEmail = function (email) {
134
+ return this.authRequestHandler.getAccountInfoByEmail(email)
135
+ .then(function (response) {
136
+ // Returns the user record populated with server response.
137
+ return new user_record_1.UserRecord(response.users[0]);
138
+ });
139
+ };
140
+ /**
141
+ * Looks up the user identified by the provided phone number and returns a promise that is
142
+ * fulfilled with a user record for the given user if that user is found.
143
+ *
144
+ * @param {string} phoneNumber The phone number of the user to look up.
145
+ * @return {Promise<UserRecord>} A promise that resolves with the corresponding user record.
146
+ */
147
+ BaseAuth.prototype.getUserByPhoneNumber = function (phoneNumber) {
148
+ return this.authRequestHandler.getAccountInfoByPhoneNumber(phoneNumber)
149
+ .then(function (response) {
150
+ // Returns the user record populated with server response.
151
+ return new user_record_1.UserRecord(response.users[0]);
152
+ });
153
+ };
154
+ /**
155
+ * Gets the user data for the user corresponding to a given provider id.
156
+ *
157
+ * See [Retrieve user data](/docs/auth/admin/manage-users#retrieve_user_data)
158
+ * for code samples and detailed documentation.
159
+ *
160
+ * @param providerId The provider ID, for example, "google.com" for the
161
+ * Google provider.
162
+ * @param uid The user identifier for the given provider.
163
+ *
164
+ * @return A promise fulfilled with the user data corresponding to the
165
+ * given provider id.
166
+ */
167
+ BaseAuth.prototype.getUserByProviderUid = function (providerId, uid) {
168
+ // Although we don't really advertise it, we want to also handle
169
+ // non-federated idps with this call. So if we detect one of them, we'll
170
+ // reroute this request appropriately.
171
+ if (providerId === 'phone') {
172
+ return this.getUserByPhoneNumber(uid);
173
+ }
174
+ else if (providerId === 'email') {
175
+ return this.getUserByEmail(uid);
176
+ }
177
+ return this.authRequestHandler.getAccountInfoByFederatedUid(providerId, uid)
178
+ .then(function (response) {
179
+ // Returns the user record populated with server response.
180
+ return new user_record_1.UserRecord(response.users[0]);
181
+ });
182
+ };
183
+ /**
184
+ * Gets the user data corresponding to the specified identifiers.
185
+ *
186
+ * There are no ordering guarantees; in particular, the nth entry in the result list is not
187
+ * guaranteed to correspond to the nth entry in the input parameters list.
188
+ *
189
+ * Only a maximum of 100 identifiers may be supplied. If more than 100 identifiers are supplied,
190
+ * this method will immediately throw a FirebaseAuthError.
191
+ *
192
+ * @param identifiers The identifiers used to indicate which user records should be returned. Must
193
+ * have <= 100 entries.
194
+ * @return {Promise<GetUsersResult>} A promise that resolves to the corresponding user records.
195
+ * @throws FirebaseAuthError If any of the identifiers are invalid or if more than 100
196
+ * identifiers are specified.
197
+ */
198
+ BaseAuth.prototype.getUsers = function (identifiers) {
199
+ if (!validator.isArray(identifiers)) {
200
+ throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '`identifiers` parameter must be an array');
201
+ }
202
+ return this.authRequestHandler
203
+ .getAccountInfoByIdentifiers(identifiers)
204
+ .then(function (response) {
205
+ /**
206
+ * Checks if the specified identifier is within the list of
207
+ * UserRecords.
208
+ */
209
+ var isUserFound = (function (id, userRecords) {
210
+ return !!userRecords.find(function (userRecord) {
211
+ if (identifier_1.isUidIdentifier(id)) {
212
+ return id.uid === userRecord.uid;
213
+ }
214
+ else if (identifier_1.isEmailIdentifier(id)) {
215
+ return id.email === userRecord.email;
216
+ }
217
+ else if (identifier_1.isPhoneIdentifier(id)) {
218
+ return id.phoneNumber === userRecord.phoneNumber;
219
+ }
220
+ else if (identifier_1.isProviderIdentifier(id)) {
221
+ var matchingUserInfo = userRecord.providerData.find(function (userInfo) {
222
+ return id.providerId === userInfo.providerId;
223
+ });
224
+ return !!matchingUserInfo && id.providerUid === matchingUserInfo.uid;
225
+ }
226
+ else {
227
+ throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'Unhandled identifier type');
228
+ }
229
+ });
230
+ });
231
+ var users = response.users ? response.users.map(function (user) { return new user_record_1.UserRecord(user); }) : [];
232
+ var notFound = identifiers.filter(function (id) { return !isUserFound(id, users); });
233
+ return { users: users, notFound: notFound };
234
+ });
235
+ };
236
+ /**
237
+ * Exports a batch of user accounts. Batch size is determined by the maxResults argument.
238
+ * Starting point of the batch is determined by the pageToken argument.
239
+ *
240
+ * @param {number=} maxResults The page size, 1000 if undefined. This is also the maximum
241
+ * allowed limit.
242
+ * @param {string=} pageToken The next page token. If not specified, returns users starting
243
+ * without any offset.
244
+ * @return {Promise<{users: UserRecord[], pageToken?: string}>} A promise that resolves with
245
+ * the current batch of downloaded users and the next page token. For the last page, an
246
+ * empty list of users and no page token are returned.
247
+ */
248
+ BaseAuth.prototype.listUsers = function (maxResults, pageToken) {
249
+ return this.authRequestHandler.downloadAccount(maxResults, pageToken)
250
+ .then(function (response) {
251
+ // List of users to return.
252
+ var users = [];
253
+ // Convert each user response to a UserRecord.
254
+ response.users.forEach(function (userResponse) {
255
+ users.push(new user_record_1.UserRecord(userResponse));
256
+ });
257
+ // Return list of user records and the next page token if available.
258
+ var result = {
259
+ users: users,
260
+ pageToken: response.nextPageToken,
261
+ };
262
+ // Delete result.pageToken if undefined.
263
+ if (typeof result.pageToken === 'undefined') {
264
+ delete result.pageToken;
265
+ }
266
+ return result;
267
+ });
268
+ };
269
+ /**
270
+ * Creates a new user with the properties provided.
271
+ *
272
+ * @param {CreateRequest} properties The properties to set on the new user record to be created.
273
+ * @return {Promise<UserRecord>} A promise that resolves with the newly created user record.
274
+ */
275
+ BaseAuth.prototype.createUser = function (properties) {
276
+ var _this = this;
277
+ return this.authRequestHandler.createNewAccount(properties)
278
+ .then(function (uid) {
279
+ // Return the corresponding user record.
280
+ return _this.getUser(uid);
281
+ })
282
+ .catch(function (error) {
283
+ if (error.code === 'auth/user-not-found') {
284
+ // Something must have happened after creating the user and then retrieving it.
285
+ throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'Unable to create the user record provided.');
286
+ }
287
+ throw error;
288
+ });
289
+ };
290
+ /**
291
+ * Deletes the user identified by the provided user id and returns a promise that is
292
+ * fulfilled when the user is found and successfully deleted.
293
+ *
294
+ * @param {string} uid The uid of the user to delete.
295
+ * @return {Promise<void>} A promise that resolves when the user is successfully deleted.
296
+ */
297
+ BaseAuth.prototype.deleteUser = function (uid) {
298
+ return this.authRequestHandler.deleteAccount(uid)
299
+ .then(function () {
300
+ // Return nothing on success.
301
+ });
302
+ };
303
+ BaseAuth.prototype.deleteUsers = function (uids) {
304
+ if (!validator.isArray(uids)) {
305
+ throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '`uids` parameter must be an array');
306
+ }
307
+ return this.authRequestHandler.deleteAccounts(uids, /*force=*/ true)
308
+ .then(function (batchDeleteAccountsResponse) {
309
+ var result = {
310
+ failureCount: 0,
311
+ successCount: uids.length,
312
+ errors: [],
313
+ };
314
+ if (!validator.isNonEmptyArray(batchDeleteAccountsResponse.errors)) {
315
+ return result;
316
+ }
317
+ result.failureCount = batchDeleteAccountsResponse.errors.length;
318
+ result.successCount = uids.length - batchDeleteAccountsResponse.errors.length;
319
+ result.errors = batchDeleteAccountsResponse.errors.map(function (batchDeleteErrorInfo) {
320
+ if (batchDeleteErrorInfo.index === undefined) {
321
+ throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'Corrupt BatchDeleteAccountsResponse detected');
322
+ }
323
+ var errMsgToError = function (msg) {
324
+ // We unconditionally set force=true, so the 'NOT_DISABLED' error
325
+ // should not be possible.
326
+ var code = msg && msg.startsWith('NOT_DISABLED') ?
327
+ error_1.AuthClientErrorCode.USER_NOT_DISABLED : error_1.AuthClientErrorCode.INTERNAL_ERROR;
328
+ return new error_1.FirebaseAuthError(code, batchDeleteErrorInfo.message);
329
+ };
330
+ return {
331
+ index: batchDeleteErrorInfo.index,
332
+ error: errMsgToError(batchDeleteErrorInfo.message),
333
+ };
334
+ });
335
+ return result;
336
+ });
337
+ };
338
+ /**
339
+ * Updates an existing user with the properties provided.
340
+ *
341
+ * @param {string} uid The uid identifier of the user to update.
342
+ * @param {UpdateRequest} properties The properties to update on the existing user.
343
+ * @return {Promise<UserRecord>} A promise that resolves with the modified user record.
344
+ */
345
+ BaseAuth.prototype.updateUser = function (uid, properties) {
346
+ var _this = this;
347
+ // Although we don't really advertise it, we want to also handle linking of
348
+ // non-federated idps with this call. So if we detect one of them, we'll
349
+ // adjust the properties parameter appropriately. This *does* imply that a
350
+ // conflict could arise, e.g. if the user provides a phoneNumber property,
351
+ // but also provides a providerToLink with a 'phone' provider id. In that
352
+ // case, we'll throw an error.
353
+ properties = deep_copy_1.deepCopy(properties);
354
+ if (properties === null || properties === void 0 ? void 0 : properties.providerToLink) {
355
+ if (properties.providerToLink.providerId === 'email') {
356
+ if (typeof properties.email !== 'undefined') {
357
+ throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, "Both UpdateRequest.email and UpdateRequest.providerToLink.providerId='email' were set. To "
358
+ + 'link to the email/password provider, only specify the UpdateRequest.email field.');
359
+ }
360
+ properties.email = properties.providerToLink.uid;
361
+ delete properties.providerToLink;
362
+ }
363
+ else if (properties.providerToLink.providerId === 'phone') {
364
+ if (typeof properties.phoneNumber !== 'undefined') {
365
+ throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, "Both UpdateRequest.phoneNumber and UpdateRequest.providerToLink.providerId='phone' were set. To "
366
+ + 'link to a phone provider, only specify the UpdateRequest.phoneNumber field.');
367
+ }
368
+ properties.phoneNumber = properties.providerToLink.uid;
369
+ delete properties.providerToLink;
370
+ }
371
+ }
372
+ if (properties === null || properties === void 0 ? void 0 : properties.providersToUnlink) {
373
+ if (properties.providersToUnlink.indexOf('phone') !== -1) {
374
+ // If we've been told to unlink the phone provider both via setting
375
+ // phoneNumber to null *and* by setting providersToUnlink to include
376
+ // 'phone', then we'll reject that. Though it might also be reasonable
377
+ // to relax this restriction and just unlink it.
378
+ if (properties.phoneNumber === null) {
379
+ throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, "Both UpdateRequest.phoneNumber=null and UpdateRequest.providersToUnlink=['phone'] were set. To "
380
+ + 'unlink from a phone provider, only specify the UpdateRequest.phoneNumber=null field.');
381
+ }
382
+ }
383
+ }
384
+ return this.authRequestHandler.updateExistingAccount(uid, properties)
385
+ .then(function (existingUid) {
386
+ // Return the corresponding user record.
387
+ return _this.getUser(existingUid);
388
+ });
389
+ };
390
+ /**
391
+ * Sets additional developer claims on an existing user identified by the provided UID.
392
+ *
393
+ * @param {string} uid The user to edit.
394
+ * @param {object} customUserClaims The developer claims to set.
395
+ * @return {Promise<void>} A promise that resolves when the operation completes
396
+ * successfully.
397
+ */
398
+ BaseAuth.prototype.setCustomUserClaims = function (uid, customUserClaims) {
399
+ return this.authRequestHandler.setCustomUserClaims(uid, customUserClaims)
400
+ .then(function () {
401
+ // Return nothing on success.
402
+ });
403
+ };
404
+ /**
405
+ * Revokes all refresh tokens for the specified user identified by the provided UID.
406
+ * In addition to revoking all refresh tokens for a user, all ID tokens issued before
407
+ * revocation will also be revoked on the Auth backend. Any request with an ID token
408
+ * generated before revocation will be rejected with a token expired error.
409
+ *
410
+ * @param {string} uid The user whose tokens are to be revoked.
411
+ * @return {Promise<void>} A promise that resolves when the operation completes
412
+ * successfully.
413
+ */
414
+ BaseAuth.prototype.revokeRefreshTokens = function (uid) {
415
+ return this.authRequestHandler.revokeRefreshTokens(uid)
416
+ .then(function () {
417
+ // Return nothing on success.
418
+ });
419
+ };
420
+ /**
421
+ * Imports the list of users provided to Firebase Auth. This is useful when
422
+ * migrating from an external authentication system without having to use the Firebase CLI SDK.
423
+ * At most, 1000 users are allowed to be imported one at a time.
424
+ * When importing a list of password users, UserImportOptions are required to be specified.
425
+ *
426
+ * @param {UserImportRecord[]} users The list of user records to import to Firebase Auth.
427
+ * @param {UserImportOptions=} options The user import options, required when the users provided
428
+ * include password credentials.
429
+ * @return {Promise<UserImportResult>} A promise that resolves when the operation completes
430
+ * with the result of the import. This includes the number of successful imports, the number
431
+ * of failed uploads and their corresponding errors.
432
+ */
433
+ BaseAuth.prototype.importUsers = function (users, options) {
434
+ return this.authRequestHandler.uploadAccount(users, options);
435
+ };
436
+ /**
437
+ * Creates a new Firebase session cookie with the specified options that can be used for
438
+ * session management (set as a server side session cookie with custom cookie policy).
439
+ * The session cookie JWT will have the same payload claims as the provided ID token.
440
+ *
441
+ * @param {string} idToken The Firebase ID token to exchange for a session cookie.
442
+ * @param {SessionCookieOptions} sessionCookieOptions The session cookie options which includes
443
+ * custom session duration.
444
+ *
445
+ * @return {Promise<string>} A promise that resolves on success with the created session cookie.
446
+ */
447
+ BaseAuth.prototype.createSessionCookie = function (idToken, sessionCookieOptions) {
448
+ // Return rejected promise if expiresIn is not available.
449
+ if (!validator.isNonNullObject(sessionCookieOptions) ||
450
+ !validator.isNumber(sessionCookieOptions.expiresIn)) {
451
+ return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_SESSION_COOKIE_DURATION));
452
+ }
453
+ return this.authRequestHandler.createSessionCookie(idToken, sessionCookieOptions.expiresIn);
454
+ };
455
+ /**
456
+ * Verifies a Firebase session cookie. Returns a promise with the token’s claims.
457
+ * Rejects the promise if the cookie could not be verified.
458
+ * If `checkRevoked` is set to true, first verifies whether the corresponding
459
+ * user is disabled:
460
+ * If yes, an `auth/user-disabled` error is thrown.
461
+ * If no, verifies if the session corresponding to the session cookie was
462
+ * revoked.
463
+ * If the corresponding user's session was invalidated, an
464
+ * `auth/session-cookie-revoked` error is thrown.
465
+ * If not specified the check is not performed.
466
+ *
467
+ * @param {string} sessionCookie The session cookie to verify.
468
+ * @param {boolean=} checkRevoked Whether to check if the session cookie is
469
+ * revoked.
470
+ * @return {Promise<DecodedIdToken>} A promise that will be fulfilled after
471
+ * a successful verification.
472
+ */
473
+ BaseAuth.prototype.verifySessionCookie = function (sessionCookie, checkRevoked) {
474
+ var _this = this;
475
+ if (checkRevoked === void 0) { checkRevoked = false; }
476
+ var isEmulator = auth_api_request_1.useEmulator();
477
+ return this.sessionCookieVerifier.verifyJWT(sessionCookie, isEmulator)
478
+ .then(function (decodedIdToken) {
479
+ // Whether to check if the cookie was revoked.
480
+ if (checkRevoked || isEmulator) {
481
+ return _this.verifyDecodedJWTNotRevokedOrDisabled(decodedIdToken, error_1.AuthClientErrorCode.SESSION_COOKIE_REVOKED);
482
+ }
483
+ return decodedIdToken;
484
+ });
485
+ };
486
+ /**
487
+ * Generates the out of band email action link for password reset flows for the
488
+ * email specified using the action code settings provided.
489
+ * Returns a promise that resolves with the generated link.
490
+ *
491
+ * @param {string} email The email of the user whose password is to be reset.
492
+ * @param {ActionCodeSettings=} actionCodeSettings The optional action code setings which defines whether
493
+ * the link is to be handled by a mobile app and the additional state information to be passed in the
494
+ * deep link, etc.
495
+ * @return {Promise<string>} A promise that resolves with the password reset link.
496
+ */
497
+ BaseAuth.prototype.generatePasswordResetLink = function (email, actionCodeSettings) {
498
+ return this.authRequestHandler.getEmailActionLink('PASSWORD_RESET', email, actionCodeSettings);
499
+ };
500
+ /**
501
+ * Generates the out of band email action link for email verification flows for the
502
+ * email specified using the action code settings provided.
503
+ * Returns a promise that resolves with the generated link.
504
+ *
505
+ * @param {string} email The email of the user to be verified.
506
+ * @param {ActionCodeSettings=} actionCodeSettings The optional action code setings which defines whether
507
+ * the link is to be handled by a mobile app and the additional state information to be passed in the
508
+ * deep link, etc.
509
+ * @return {Promise<string>} A promise that resolves with the email verification link.
510
+ */
511
+ BaseAuth.prototype.generateEmailVerificationLink = function (email, actionCodeSettings) {
512
+ return this.authRequestHandler.getEmailActionLink('VERIFY_EMAIL', email, actionCodeSettings);
513
+ };
514
+ /**
515
+ * Generates the out of band email action link for email link sign-in flows for the
516
+ * email specified using the action code settings provided.
517
+ * Returns a promise that resolves with the generated link.
518
+ *
519
+ * @param {string} email The email of the user signing in.
520
+ * @param {ActionCodeSettings} actionCodeSettings The required action code setings which defines whether
521
+ * the link is to be handled by a mobile app and the additional state information to be passed in the
522
+ * deep link, etc.
523
+ * @return {Promise<string>} A promise that resolves with the email sign-in link.
524
+ */
525
+ BaseAuth.prototype.generateSignInWithEmailLink = function (email, actionCodeSettings) {
526
+ return this.authRequestHandler.getEmailActionLink('EMAIL_SIGNIN', email, actionCodeSettings);
527
+ };
528
+ /**
529
+ * Returns the list of existing provider configuation matching the filter provided.
530
+ * At most, 100 provider configs are allowed to be imported at a time.
531
+ *
532
+ * @param {AuthProviderConfigFilter} options The provider config filter to apply.
533
+ * @return {Promise<ListProviderConfigResults>} A promise that resolves with the list of provider configs
534
+ * meeting the filter requirements.
535
+ */
536
+ BaseAuth.prototype.listProviderConfigs = function (options) {
537
+ var processResponse = function (response, providerConfigs) {
538
+ // Return list of provider configuration and the next page token if available.
539
+ var result = {
540
+ providerConfigs: providerConfigs,
541
+ };
542
+ // Delete result.pageToken if undefined.
543
+ if (Object.prototype.hasOwnProperty.call(response, 'nextPageToken')) {
544
+ result.pageToken = response.nextPageToken;
545
+ }
546
+ return result;
547
+ };
548
+ if (options && options.type === 'oidc') {
549
+ return this.authRequestHandler.listOAuthIdpConfigs(options.maxResults, options.pageToken)
550
+ .then(function (response) {
551
+ // List of provider configurations to return.
552
+ var providerConfigs = [];
553
+ // Convert each provider config response to a OIDCConfig.
554
+ response.oauthIdpConfigs.forEach(function (configResponse) {
555
+ providerConfigs.push(new auth_config_1.OIDCConfig(configResponse));
556
+ });
557
+ // Return list of provider configuration and the next page token if available.
558
+ return processResponse(response, providerConfigs);
559
+ });
560
+ }
561
+ else if (options && options.type === 'saml') {
562
+ return this.authRequestHandler.listInboundSamlConfigs(options.maxResults, options.pageToken)
563
+ .then(function (response) {
564
+ // List of provider configurations to return.
565
+ var providerConfigs = [];
566
+ // Convert each provider config response to a SAMLConfig.
567
+ response.inboundSamlConfigs.forEach(function (configResponse) {
568
+ providerConfigs.push(new auth_config_1.SAMLConfig(configResponse));
569
+ });
570
+ // Return list of provider configuration and the next page token if available.
571
+ return processResponse(response, providerConfigs);
572
+ });
573
+ }
574
+ return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"AuthProviderConfigFilter.type" must be either "saml" or "oidc"'));
575
+ };
576
+ /**
577
+ * Looks up an Auth provider configuration by ID.
578
+ * Returns a promise that resolves with the provider configuration corresponding to the provider ID specified.
579
+ *
580
+ * @param {string} providerId The provider ID corresponding to the provider config to return.
581
+ * @return {Promise<AuthProviderConfig>}
582
+ */
583
+ BaseAuth.prototype.getProviderConfig = function (providerId) {
584
+ if (auth_config_1.OIDCConfig.isProviderId(providerId)) {
585
+ return this.authRequestHandler.getOAuthIdpConfig(providerId)
586
+ .then(function (response) {
587
+ return new auth_config_1.OIDCConfig(response);
588
+ });
589
+ }
590
+ else if (auth_config_1.SAMLConfig.isProviderId(providerId)) {
591
+ return this.authRequestHandler.getInboundSamlConfig(providerId)
592
+ .then(function (response) {
593
+ return new auth_config_1.SAMLConfig(response);
594
+ });
595
+ }
596
+ return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PROVIDER_ID));
597
+ };
598
+ /**
599
+ * Deletes the provider configuration corresponding to the provider ID passed.
600
+ *
601
+ * @param {string} providerId The provider ID corresponding to the provider config to delete.
602
+ * @return {Promise<void>} A promise that resolves on completion.
603
+ */
604
+ BaseAuth.prototype.deleteProviderConfig = function (providerId) {
605
+ if (auth_config_1.OIDCConfig.isProviderId(providerId)) {
606
+ return this.authRequestHandler.deleteOAuthIdpConfig(providerId);
607
+ }
608
+ else if (auth_config_1.SAMLConfig.isProviderId(providerId)) {
609
+ return this.authRequestHandler.deleteInboundSamlConfig(providerId);
610
+ }
611
+ return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PROVIDER_ID));
612
+ };
613
+ /**
614
+ * Returns a promise that resolves with the updated AuthProviderConfig when the provider configuration corresponding
615
+ * to the provider ID specified is updated with the specified configuration.
616
+ *
617
+ * @param {string} providerId The provider ID corresponding to the provider config to update.
618
+ * @param {UpdateAuthProviderRequest} updatedConfig The updated configuration.
619
+ * @return {Promise<AuthProviderConfig>} A promise that resolves with the updated provider configuration.
620
+ */
621
+ BaseAuth.prototype.updateProviderConfig = function (providerId, updatedConfig) {
622
+ if (!validator.isNonNullObject(updatedConfig)) {
623
+ return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, 'Request is missing "UpdateAuthProviderRequest" configuration.'));
624
+ }
625
+ if (auth_config_1.OIDCConfig.isProviderId(providerId)) {
626
+ return this.authRequestHandler.updateOAuthIdpConfig(providerId, updatedConfig)
627
+ .then(function (response) {
628
+ return new auth_config_1.OIDCConfig(response);
629
+ });
630
+ }
631
+ else if (auth_config_1.SAMLConfig.isProviderId(providerId)) {
632
+ return this.authRequestHandler.updateInboundSamlConfig(providerId, updatedConfig)
633
+ .then(function (response) {
634
+ return new auth_config_1.SAMLConfig(response);
635
+ });
636
+ }
637
+ return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PROVIDER_ID));
638
+ };
639
+ /**
640
+ * Returns a promise that resolves with the newly created AuthProviderConfig when the new provider configuration is
641
+ * created.
642
+ * @param {AuthProviderConfig} config The provider configuration to create.
643
+ * @return {Promise<AuthProviderConfig>} A promise that resolves with the created provider configuration.
644
+ */
645
+ BaseAuth.prototype.createProviderConfig = function (config) {
646
+ if (!validator.isNonNullObject(config)) {
647
+ return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, 'Request is missing "AuthProviderConfig" configuration.'));
648
+ }
649
+ if (auth_config_1.OIDCConfig.isProviderId(config.providerId)) {
650
+ return this.authRequestHandler.createOAuthIdpConfig(config)
651
+ .then(function (response) {
652
+ return new auth_config_1.OIDCConfig(response);
653
+ });
654
+ }
655
+ else if (auth_config_1.SAMLConfig.isProviderId(config.providerId)) {
656
+ return this.authRequestHandler.createInboundSamlConfig(config)
657
+ .then(function (response) {
658
+ return new auth_config_1.SAMLConfig(response);
659
+ });
660
+ }
661
+ return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PROVIDER_ID));
662
+ };
663
+ /**
664
+ * Verifies the decoded Firebase issued JWT is not revoked or disabled. Returns a promise that
665
+ * resolves with the decoded claims on success. Rejects the promise with revocation error if revoked
666
+ * or user disabled.
667
+ *
668
+ * @param {DecodedIdToken} decodedIdToken The JWT's decoded claims.
669
+ * @param {ErrorInfo} revocationErrorInfo The revocation error info to throw on revocation
670
+ * detection.
671
+ * @return {Promise<DecodedIdToken>} A promise that will be fulfilled after a successful
672
+ * verification.
673
+ */
674
+ BaseAuth.prototype.verifyDecodedJWTNotRevokedOrDisabled = function (decodedIdToken, revocationErrorInfo) {
675
+ // Get tokens valid after time for the corresponding user.
676
+ return this.getUser(decodedIdToken.sub)
677
+ .then(function (user) {
678
+ if (user.disabled) {
679
+ throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.USER_DISABLED, 'The user record is disabled.');
680
+ }
681
+ // If no tokens valid after time available, token is not revoked.
682
+ if (user.tokensValidAfterTime) {
683
+ // Get the ID token authentication time and convert to milliseconds UTC.
684
+ var authTimeUtc = decodedIdToken.auth_time * 1000;
685
+ // Get user tokens valid after time in milliseconds UTC.
686
+ var validSinceUtc = new Date(user.tokensValidAfterTime).getTime();
687
+ // Check if authentication time is older than valid since time.
688
+ if (authTimeUtc < validSinceUtc) {
689
+ throw new error_1.FirebaseAuthError(revocationErrorInfo);
690
+ }
691
+ }
692
+ // All checks above passed. Return the decoded token.
693
+ return decodedIdToken;
694
+ });
695
+ };
696
+ return BaseAuth;
697
+ }());
698
+ exports.BaseAuth = BaseAuth;
699
+ /**
700
+ * The tenant aware Auth class.
701
+ */
702
+ var TenantAwareAuth = /** @class */ (function (_super) {
703
+ __extends(TenantAwareAuth, _super);
704
+ /**
705
+ * The TenantAwareAuth class constructor.
706
+ *
707
+ * @param {object} app The app that created this tenant.
708
+ * @param tenantId The corresponding tenant ID.
709
+ * @constructor
710
+ */
711
+ function TenantAwareAuth(app, tenantId) {
712
+ var _this = _super.call(this, app, new auth_api_request_1.TenantAwareAuthRequestHandler(app, tenantId), createFirebaseTokenGenerator(app, tenantId)) || this;
713
+ utils.addReadonlyGetter(_this, 'tenantId', tenantId);
714
+ return _this;
715
+ }
716
+ /**
717
+ * Verifies a JWT auth token. Returns a promise with the tokens claims. Rejects
718
+ * the promise if the token could not be verified. If checkRevoked is set to true,
719
+ * verifies if the session corresponding to the ID token was revoked. If the corresponding
720
+ * user's session was invalidated, an `auth/id-token-revoked` error is thrown. If not specified
721
+ * the check is not applied.
722
+ *
723
+ * @param {string} idToken The JWT to verify.
724
+ * @param {boolean=} checkRevoked Whether to check if the ID token is revoked.
725
+ * @return {Promise<DecodedIdToken>} A promise that will be fulfilled after a successful
726
+ * verification.
727
+ */
728
+ TenantAwareAuth.prototype.verifyIdToken = function (idToken, checkRevoked) {
729
+ var _this = this;
730
+ if (checkRevoked === void 0) { checkRevoked = false; }
731
+ return _super.prototype.verifyIdToken.call(this, idToken, checkRevoked)
732
+ .then(function (decodedClaims) {
733
+ // Validate tenant ID.
734
+ if (decodedClaims.firebase.tenant !== _this.tenantId) {
735
+ throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.MISMATCHING_TENANT_ID);
736
+ }
737
+ return decodedClaims;
738
+ });
739
+ };
740
+ /**
741
+ * Creates a new Firebase session cookie with the specified options that can be used for
742
+ * session management (set as a server side session cookie with custom cookie policy).
743
+ * The session cookie JWT will have the same payload claims as the provided ID token.
744
+ *
745
+ * @param {string} idToken The Firebase ID token to exchange for a session cookie.
746
+ * @param {SessionCookieOptions} sessionCookieOptions The session cookie options which includes
747
+ * custom session duration.
748
+ *
749
+ * @return {Promise<string>} A promise that resolves on success with the created session cookie.
750
+ */
751
+ TenantAwareAuth.prototype.createSessionCookie = function (idToken, sessionCookieOptions) {
752
+ var _this = this;
753
+ // Validate arguments before processing.
754
+ if (!validator.isNonEmptyString(idToken)) {
755
+ return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ID_TOKEN));
756
+ }
757
+ if (!validator.isNonNullObject(sessionCookieOptions) ||
758
+ !validator.isNumber(sessionCookieOptions.expiresIn)) {
759
+ return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_SESSION_COOKIE_DURATION));
760
+ }
761
+ // This will verify the ID token and then match the tenant ID before creating the session cookie.
762
+ return this.verifyIdToken(idToken)
763
+ .then(function () {
764
+ return _super.prototype.createSessionCookie.call(_this, idToken, sessionCookieOptions);
765
+ });
766
+ };
767
+ /**
768
+ * Verifies a Firebase session cookie. Returns a promise with the tokens claims. Rejects
769
+ * the promise if the token could not be verified. If checkRevoked is set to true,
770
+ * verifies if the session corresponding to the session cookie was revoked. If the corresponding
771
+ * user's session was invalidated, an `auth/session-cookie-revoked` error is thrown. If not
772
+ * specified the check is not performed.
773
+ *
774
+ * @param {string} sessionCookie The session cookie to verify.
775
+ * @param {boolean=} checkRevoked Whether to check if the session cookie is revoked.
776
+ * @return {Promise<DecodedIdToken>} A promise that will be fulfilled after a successful
777
+ * verification.
778
+ */
779
+ TenantAwareAuth.prototype.verifySessionCookie = function (sessionCookie, checkRevoked) {
780
+ var _this = this;
781
+ if (checkRevoked === void 0) { checkRevoked = false; }
782
+ return _super.prototype.verifySessionCookie.call(this, sessionCookie, checkRevoked)
783
+ .then(function (decodedClaims) {
784
+ if (decodedClaims.firebase.tenant !== _this.tenantId) {
785
+ throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.MISMATCHING_TENANT_ID);
786
+ }
787
+ return decodedClaims;
788
+ });
789
+ };
790
+ return TenantAwareAuth;
791
+ }(BaseAuth));
792
+ exports.TenantAwareAuth = TenantAwareAuth;
793
+ /**
794
+ * Auth service bound to the provided app.
795
+ * An Auth instance can have multiple tenants.
796
+ */
797
+ var Auth = /** @class */ (function (_super) {
798
+ __extends(Auth, _super);
799
+ /**
800
+ * @param {object} app The app for this Auth service.
801
+ * @constructor
802
+ */
803
+ function Auth(app) {
804
+ var _this = _super.call(this, app, new auth_api_request_1.AuthRequestHandler(app)) || this;
805
+ _this.app_ = app;
806
+ _this.tenantManager_ = new tenant_manager_1.TenantManager(app);
807
+ return _this;
808
+ }
809
+ Object.defineProperty(Auth.prototype, "app", {
810
+ /**
811
+ * Returns the app associated with this Auth instance.
812
+ *
813
+ * @return {FirebaseApp} The app associated with this Auth instance.
814
+ */
815
+ get: function () {
816
+ return this.app_;
817
+ },
818
+ enumerable: false,
819
+ configurable: true
820
+ });
821
+ /** @return The current Auth instance's tenant manager. */
822
+ Auth.prototype.tenantManager = function () {
823
+ return this.tenantManager_;
824
+ };
825
+ return Auth;
826
+ }(BaseAuth));
827
+ exports.Auth = Auth;
828
+ function createFirebaseTokenGenerator(app, tenantId) {
829
+ try {
830
+ var signer = auth_api_request_1.useEmulator() ? new token_generator_1.EmulatedSigner() : crypto_signer_1.cryptoSignerFromApp(app);
831
+ return new token_generator_1.FirebaseTokenGenerator(signer, tenantId);
832
+ }
833
+ catch (err) {
834
+ throw token_generator_1.handleCryptoSignerError(err);
835
+ }
836
+ }