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,18 @@
1
+ /*! firebase-admin v9.12.0 */
2
+ "use strict";
3
+ /*!
4
+ * Copyright 2020 Google Inc.
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,140 @@
1
+ /*! firebase-admin v9.12.0 */
2
+ "use strict";
3
+ /*!
4
+ * Copyright 2019 Google Inc.
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.TenantManager = void 0;
20
+ var auth_api_request_1 = require("./auth-api-request");
21
+ var auth_1 = require("./auth");
22
+ var tenant_1 = require("./tenant");
23
+ var error_1 = require("../utils/error");
24
+ var validator = require("../utils/validator");
25
+ /**
26
+ * Data structure used to help manage tenant related operations.
27
+ * This includes:
28
+ * - The ability to create, update, list, get and delete tenants for the underlying project.
29
+ * - Getting a TenantAwareAuth instance for running Auth related operations (user mgmt, provider config mgmt, etc)
30
+ * in the context of a specified tenant.
31
+ */
32
+ var TenantManager = /** @class */ (function () {
33
+ /**
34
+ * Initializes a TenantManager instance for a specified FirebaseApp.
35
+ * @param app The app for this TenantManager instance.
36
+ */
37
+ function TenantManager(app) {
38
+ this.app = app;
39
+ this.authRequestHandler = new auth_api_request_1.AuthRequestHandler(app);
40
+ this.tenantsMap = {};
41
+ }
42
+ /**
43
+ * Returns a TenantAwareAuth instance for the corresponding tenant ID.
44
+ *
45
+ * @param tenantId The tenant ID whose TenantAwareAuth is to be returned.
46
+ * @return The corresponding TenantAwareAuth instance.
47
+ */
48
+ TenantManager.prototype.authForTenant = function (tenantId) {
49
+ if (!validator.isNonEmptyString(tenantId)) {
50
+ throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_TENANT_ID);
51
+ }
52
+ if (typeof this.tenantsMap[tenantId] === 'undefined') {
53
+ this.tenantsMap[tenantId] = new auth_1.TenantAwareAuth(this.app, tenantId);
54
+ }
55
+ return this.tenantsMap[tenantId];
56
+ };
57
+ /**
58
+ * Looks up the tenant identified by the provided tenant ID and returns a promise that is
59
+ * fulfilled with the corresponding tenant if it is found.
60
+ *
61
+ * @param tenantId The tenant ID of the tenant to look up.
62
+ * @return A promise that resolves with the corresponding tenant.
63
+ */
64
+ TenantManager.prototype.getTenant = function (tenantId) {
65
+ return this.authRequestHandler.getTenant(tenantId)
66
+ .then(function (response) {
67
+ return new tenant_1.Tenant(response);
68
+ });
69
+ };
70
+ /**
71
+ * Exports a batch of tenant accounts. Batch size is determined by the maxResults argument.
72
+ * Starting point of the batch is determined by the pageToken argument.
73
+ *
74
+ * @param maxResults The page size, 1000 if undefined. This is also the maximum
75
+ * allowed limit.
76
+ * @param pageToken The next page token. If not specified, returns users starting
77
+ * without any offset.
78
+ * @return A promise that resolves with
79
+ * the current batch of downloaded tenants and the next page token. For the last page, an
80
+ * empty list of tenants and no page token are returned.
81
+ */
82
+ TenantManager.prototype.listTenants = function (maxResults, pageToken) {
83
+ return this.authRequestHandler.listTenants(maxResults, pageToken)
84
+ .then(function (response) {
85
+ // List of tenants to return.
86
+ var tenants = [];
87
+ // Convert each user response to a Tenant.
88
+ response.tenants.forEach(function (tenantResponse) {
89
+ tenants.push(new tenant_1.Tenant(tenantResponse));
90
+ });
91
+ // Return list of tenants and the next page token if available.
92
+ var result = {
93
+ tenants: tenants,
94
+ pageToken: response.nextPageToken,
95
+ };
96
+ // Delete result.pageToken if undefined.
97
+ if (typeof result.pageToken === 'undefined') {
98
+ delete result.pageToken;
99
+ }
100
+ return result;
101
+ });
102
+ };
103
+ /**
104
+ * Deletes the tenant identified by the provided tenant ID and returns a promise that is
105
+ * fulfilled when the tenant is found and successfully deleted.
106
+ *
107
+ * @param tenantId The tenant ID of the tenant to delete.
108
+ * @return A promise that resolves when the tenant is successfully deleted.
109
+ */
110
+ TenantManager.prototype.deleteTenant = function (tenantId) {
111
+ return this.authRequestHandler.deleteTenant(tenantId);
112
+ };
113
+ /**
114
+ * Creates a new tenant with the properties provided.
115
+ *
116
+ * @param tenantOptions The properties to set on the new tenant to be created.
117
+ * @return A promise that resolves with the newly created tenant.
118
+ */
119
+ TenantManager.prototype.createTenant = function (tenantOptions) {
120
+ return this.authRequestHandler.createTenant(tenantOptions)
121
+ .then(function (response) {
122
+ return new tenant_1.Tenant(response);
123
+ });
124
+ };
125
+ /**
126
+ * Updates an existing tenant identified by the tenant ID with the properties provided.
127
+ *
128
+ * @param tenantId The tenant identifier of the tenant to update.
129
+ * @param tenantOptions The properties to update on the existing tenant.
130
+ * @return A promise that resolves with the modified tenant.
131
+ */
132
+ TenantManager.prototype.updateTenant = function (tenantId, tenantOptions) {
133
+ return this.authRequestHandler.updateTenant(tenantId, tenantOptions)
134
+ .then(function (response) {
135
+ return new tenant_1.Tenant(response);
136
+ });
137
+ };
138
+ return TenantManager;
139
+ }());
140
+ exports.TenantManager = TenantManager;
@@ -0,0 +1,171 @@
1
+ /*! firebase-admin v9.12.0 */
2
+ "use strict";
3
+ /*!
4
+ * Copyright 2019 Google Inc.
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.Tenant = void 0;
20
+ var validator = require("../utils/validator");
21
+ var deep_copy_1 = require("../utils/deep-copy");
22
+ var error_1 = require("../utils/error");
23
+ var auth_config_1 = require("./auth-config");
24
+ /**
25
+ * Tenant class that defines a Firebase Auth tenant.
26
+ */
27
+ var Tenant = /** @class */ (function () {
28
+ /**
29
+ * The Tenant object constructor.
30
+ *
31
+ * @param response The server side response used to initialize the Tenant object.
32
+ * @constructor
33
+ */
34
+ function Tenant(response) {
35
+ var tenantId = Tenant.getTenantIdFromResourceName(response.name);
36
+ if (!tenantId) {
37
+ throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid tenant response');
38
+ }
39
+ this.tenantId = tenantId;
40
+ this.displayName = response.displayName;
41
+ try {
42
+ this.emailSignInConfig = new auth_config_1.EmailSignInConfig(response);
43
+ }
44
+ catch (e) {
45
+ // If allowPasswordSignup is undefined, it is disabled by default.
46
+ this.emailSignInConfig = new auth_config_1.EmailSignInConfig({
47
+ allowPasswordSignup: false,
48
+ });
49
+ }
50
+ this.anonymousSignInEnabled = !!response.enableAnonymousUser;
51
+ if (typeof response.mfaConfig !== 'undefined') {
52
+ this.multiFactorConfig = new auth_config_1.MultiFactorAuthConfig(response.mfaConfig);
53
+ }
54
+ if (typeof response.testPhoneNumbers !== 'undefined') {
55
+ this.testPhoneNumbers = deep_copy_1.deepCopy(response.testPhoneNumbers || {});
56
+ }
57
+ }
58
+ /**
59
+ * Builds the corresponding server request for a TenantOptions object.
60
+ *
61
+ * @param {TenantOptions} tenantOptions The properties to convert to a server request.
62
+ * @param {boolean} createRequest Whether this is a create request.
63
+ * @return {object} The equivalent server request.
64
+ */
65
+ Tenant.buildServerRequest = function (tenantOptions, createRequest) {
66
+ var _a;
67
+ Tenant.validate(tenantOptions, createRequest);
68
+ var request = {};
69
+ if (typeof tenantOptions.emailSignInConfig !== 'undefined') {
70
+ request = auth_config_1.EmailSignInConfig.buildServerRequest(tenantOptions.emailSignInConfig);
71
+ }
72
+ if (typeof tenantOptions.displayName !== 'undefined') {
73
+ request.displayName = tenantOptions.displayName;
74
+ }
75
+ if (typeof tenantOptions.anonymousSignInEnabled !== 'undefined') {
76
+ request.enableAnonymousUser = tenantOptions.anonymousSignInEnabled;
77
+ }
78
+ if (typeof tenantOptions.multiFactorConfig !== 'undefined') {
79
+ request.mfaConfig = auth_config_1.MultiFactorAuthConfig.buildServerRequest(tenantOptions.multiFactorConfig);
80
+ }
81
+ if (typeof tenantOptions.testPhoneNumbers !== 'undefined') {
82
+ // null will clear existing test phone numbers. Translate to empty object.
83
+ request.testPhoneNumbers = (_a = tenantOptions.testPhoneNumbers) !== null && _a !== void 0 ? _a : {};
84
+ }
85
+ return request;
86
+ };
87
+ /**
88
+ * Returns the tenant ID corresponding to the resource name if available.
89
+ *
90
+ * @param {string} resourceName The server side resource name
91
+ * @return {?string} The tenant ID corresponding to the resource, null otherwise.
92
+ */
93
+ Tenant.getTenantIdFromResourceName = function (resourceName) {
94
+ // name is of form projects/project1/tenants/tenant1
95
+ var matchTenantRes = resourceName.match(/\/tenants\/(.*)$/);
96
+ if (!matchTenantRes || matchTenantRes.length < 2) {
97
+ return null;
98
+ }
99
+ return matchTenantRes[1];
100
+ };
101
+ /**
102
+ * Validates a tenant options object. Throws an error on failure.
103
+ *
104
+ * @param {any} request The tenant options object to validate.
105
+ * @param {boolean} createRequest Whether this is a create request.
106
+ */
107
+ Tenant.validate = function (request, createRequest) {
108
+ var validKeys = {
109
+ displayName: true,
110
+ emailSignInConfig: true,
111
+ anonymousSignInEnabled: true,
112
+ multiFactorConfig: true,
113
+ testPhoneNumbers: true,
114
+ };
115
+ var label = createRequest ? 'CreateTenantRequest' : 'UpdateTenantRequest';
116
+ if (!validator.isNonNullObject(request)) {
117
+ throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, "\"" + label + "\" must be a valid non-null object.");
118
+ }
119
+ // Check for unsupported top level attributes.
120
+ for (var key in request) {
121
+ if (!(key in validKeys)) {
122
+ throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, "\"" + key + "\" is not a valid " + label + " parameter.");
123
+ }
124
+ }
125
+ // Validate displayName type if provided.
126
+ if (typeof request.displayName !== 'undefined' &&
127
+ !validator.isNonEmptyString(request.displayName)) {
128
+ throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, "\"" + label + ".displayName\" must be a valid non-empty string.");
129
+ }
130
+ // Validate emailSignInConfig type if provided.
131
+ if (typeof request.emailSignInConfig !== 'undefined') {
132
+ // This will throw an error if invalid.
133
+ auth_config_1.EmailSignInConfig.buildServerRequest(request.emailSignInConfig);
134
+ }
135
+ // Validate test phone numbers if provided.
136
+ if (typeof request.testPhoneNumbers !== 'undefined' &&
137
+ request.testPhoneNumbers !== null) {
138
+ auth_config_1.validateTestPhoneNumbers(request.testPhoneNumbers);
139
+ }
140
+ else if (request.testPhoneNumbers === null && createRequest) {
141
+ // null allowed only for update operations.
142
+ throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, "\"" + label + ".testPhoneNumbers\" must be a non-null object.");
143
+ }
144
+ // Validate multiFactorConfig type if provided.
145
+ if (typeof request.multiFactorConfig !== 'undefined') {
146
+ // This will throw an error if invalid.
147
+ auth_config_1.MultiFactorAuthConfig.buildServerRequest(request.multiFactorConfig);
148
+ }
149
+ };
150
+ /** @return {object} The plain object representation of the tenant. */
151
+ Tenant.prototype.toJSON = function () {
152
+ var _a, _b;
153
+ var json = {
154
+ tenantId: this.tenantId,
155
+ displayName: this.displayName,
156
+ emailSignInConfig: (_a = this.emailSignInConfig) === null || _a === void 0 ? void 0 : _a.toJSON(),
157
+ anonymousSignInEnabled: this.anonymousSignInEnabled,
158
+ multiFactorConfig: (_b = this.multiFactorConfig) === null || _b === void 0 ? void 0 : _b.toJSON(),
159
+ testPhoneNumbers: this.testPhoneNumbers,
160
+ };
161
+ if (typeof json.multiFactorConfig === 'undefined') {
162
+ delete json.multiFactorConfig;
163
+ }
164
+ if (typeof json.testPhoneNumbers === 'undefined') {
165
+ delete json.testPhoneNumbers;
166
+ }
167
+ return json;
168
+ };
169
+ return Tenant;
170
+ }());
171
+ exports.Tenant = Tenant;
@@ -0,0 +1,200 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.handleCryptoSignerError = exports.FirebaseTokenGenerator = exports.EmulatedSigner = exports.BLACKLISTED_CLAIMS = void 0;
21
+ var error_1 = require("../utils/error");
22
+ var crypto_signer_1 = require("../utils/crypto-signer");
23
+ var validator = require("../utils/validator");
24
+ var utils_1 = require("../utils");
25
+ var ALGORITHM_NONE = 'none';
26
+ var ONE_HOUR_IN_SECONDS = 60 * 60;
27
+ // List of blacklisted claims which cannot be provided when creating a custom token
28
+ exports.BLACKLISTED_CLAIMS = [
29
+ 'acr', 'amr', 'at_hash', 'aud', 'auth_time', 'azp', 'cnf', 'c_hash', 'exp', 'iat', 'iss', 'jti',
30
+ 'nbf', 'nonce',
31
+ ];
32
+ // Audience to use for Firebase Auth Custom tokens
33
+ var FIREBASE_AUDIENCE = 'https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit';
34
+ /**
35
+ * A CryptoSigner implementation that is used when communicating with the Auth emulator.
36
+ * It produces unsigned tokens.
37
+ */
38
+ var EmulatedSigner = /** @class */ (function () {
39
+ function EmulatedSigner() {
40
+ this.algorithm = ALGORITHM_NONE;
41
+ }
42
+ /**
43
+ * @inheritDoc
44
+ */
45
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
46
+ EmulatedSigner.prototype.sign = function (buffer) {
47
+ return Promise.resolve(Buffer.from(''));
48
+ };
49
+ /**
50
+ * @inheritDoc
51
+ */
52
+ EmulatedSigner.prototype.getAccountId = function () {
53
+ return Promise.resolve('firebase-auth-emulator@example.com');
54
+ };
55
+ return EmulatedSigner;
56
+ }());
57
+ exports.EmulatedSigner = EmulatedSigner;
58
+ /**
59
+ * Class for generating different types of Firebase Auth tokens (JWTs).
60
+ */
61
+ var FirebaseTokenGenerator = /** @class */ (function () {
62
+ /**
63
+ * @param tenantId The tenant ID to use for the generated Firebase Auth
64
+ * Custom token. If absent, then no tenant ID claim will be set in the
65
+ * resulting JWT.
66
+ */
67
+ function FirebaseTokenGenerator(signer, tenantId) {
68
+ this.tenantId = tenantId;
69
+ if (!validator.isNonNullObject(signer)) {
70
+ throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CREDENTIAL, 'INTERNAL ASSERT: Must provide a CryptoSigner to use FirebaseTokenGenerator.');
71
+ }
72
+ if (typeof this.tenantId !== 'undefined' && !validator.isNonEmptyString(this.tenantId)) {
73
+ throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '`tenantId` argument must be a non-empty string.');
74
+ }
75
+ this.signer = signer;
76
+ }
77
+ /**
78
+ * Creates a new Firebase Auth Custom token.
79
+ *
80
+ * @param uid The user ID to use for the generated Firebase Auth Custom token.
81
+ * @param developerClaims Optional developer claims to include in the generated Firebase
82
+ * Auth Custom token.
83
+ * @return A Promise fulfilled with a Firebase Auth Custom token signed with a
84
+ * service account key and containing the provided payload.
85
+ */
86
+ FirebaseTokenGenerator.prototype.createCustomToken = function (uid, developerClaims) {
87
+ var _this = this;
88
+ var errorMessage;
89
+ if (!validator.isNonEmptyString(uid)) {
90
+ errorMessage = '`uid` argument must be a non-empty string uid.';
91
+ }
92
+ else if (uid.length > 128) {
93
+ errorMessage = '`uid` argument must a uid with less than or equal to 128 characters.';
94
+ }
95
+ else if (!this.isDeveloperClaimsValid_(developerClaims)) {
96
+ errorMessage = '`developerClaims` argument must be a valid, non-null object containing the developer claims.';
97
+ }
98
+ if (errorMessage) {
99
+ throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, errorMessage);
100
+ }
101
+ var claims = {};
102
+ if (typeof developerClaims !== 'undefined') {
103
+ for (var key in developerClaims) {
104
+ /* istanbul ignore else */
105
+ if (Object.prototype.hasOwnProperty.call(developerClaims, key)) {
106
+ if (exports.BLACKLISTED_CLAIMS.indexOf(key) !== -1) {
107
+ throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, "Developer claim \"" + key + "\" is reserved and cannot be specified.");
108
+ }
109
+ claims[key] = developerClaims[key];
110
+ }
111
+ }
112
+ }
113
+ return this.signer.getAccountId().then(function (account) {
114
+ var header = {
115
+ alg: _this.signer.algorithm,
116
+ typ: 'JWT',
117
+ };
118
+ var iat = Math.floor(Date.now() / 1000);
119
+ var body = {
120
+ aud: FIREBASE_AUDIENCE,
121
+ iat: iat,
122
+ exp: iat + ONE_HOUR_IN_SECONDS,
123
+ iss: account,
124
+ sub: account,
125
+ uid: uid,
126
+ };
127
+ if (_this.tenantId) {
128
+ // eslint-disable-next-line @typescript-eslint/camelcase
129
+ body.tenant_id = _this.tenantId;
130
+ }
131
+ if (Object.keys(claims).length > 0) {
132
+ body.claims = claims;
133
+ }
134
+ var token = _this.encodeSegment(header) + "." + _this.encodeSegment(body);
135
+ var signPromise = _this.signer.sign(Buffer.from(token));
136
+ return Promise.all([token, signPromise]);
137
+ }).then(function (_a) {
138
+ var token = _a[0], signature = _a[1];
139
+ return token + "." + _this.encodeSegment(signature);
140
+ }).catch(function (err) {
141
+ throw handleCryptoSignerError(err);
142
+ });
143
+ };
144
+ FirebaseTokenGenerator.prototype.encodeSegment = function (segment) {
145
+ var buffer = (segment instanceof Buffer) ? segment : Buffer.from(JSON.stringify(segment));
146
+ return utils_1.toWebSafeBase64(buffer).replace(/=+$/, '');
147
+ };
148
+ /**
149
+ * Returns whether or not the provided developer claims are valid.
150
+ *
151
+ * @param {object} [developerClaims] Optional developer claims to validate.
152
+ * @return {boolean} True if the provided claims are valid; otherwise, false.
153
+ */
154
+ FirebaseTokenGenerator.prototype.isDeveloperClaimsValid_ = function (developerClaims) {
155
+ if (typeof developerClaims === 'undefined') {
156
+ return true;
157
+ }
158
+ return validator.isNonNullObject(developerClaims);
159
+ };
160
+ return FirebaseTokenGenerator;
161
+ }());
162
+ exports.FirebaseTokenGenerator = FirebaseTokenGenerator;
163
+ /**
164
+ * Creates a new FirebaseAuthError by extracting the error code, message and other relevant
165
+ * details from a CryptoSignerError.
166
+ *
167
+ * @param {Error} err The Error to convert into a FirebaseAuthError error
168
+ * @return {FirebaseAuthError} A Firebase Auth error that can be returned to the user.
169
+ */
170
+ function handleCryptoSignerError(err) {
171
+ if (!(err instanceof crypto_signer_1.CryptoSignerError)) {
172
+ return err;
173
+ }
174
+ if (err.code === crypto_signer_1.CryptoSignerErrorCode.SERVER_ERROR && validator.isNonNullObject(err.cause)) {
175
+ var httpError = err.cause;
176
+ var errorResponse = httpError.response.data;
177
+ if (validator.isNonNullObject(errorResponse) && errorResponse.error) {
178
+ var errorCode = errorResponse.error.status;
179
+ var description = 'Please refer to https://firebase.google.com/docs/auth/admin/create-custom-tokens ' +
180
+ 'for more details on how to use and troubleshoot this feature.';
181
+ var errorMsg = errorResponse.error.message + "; " + description;
182
+ return error_1.FirebaseAuthError.fromServerError(errorCode, errorMsg, errorResponse);
183
+ }
184
+ return new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'Error returned from server: ' + errorResponse + '. Additionally, an ' +
185
+ 'internal error occurred while attempting to extract the ' +
186
+ 'errorcode from the error.');
187
+ }
188
+ return new error_1.FirebaseAuthError(mapToAuthClientErrorCode(err.code), err.message);
189
+ }
190
+ exports.handleCryptoSignerError = handleCryptoSignerError;
191
+ function mapToAuthClientErrorCode(code) {
192
+ switch (code) {
193
+ case crypto_signer_1.CryptoSignerErrorCode.INVALID_CREDENTIAL:
194
+ return error_1.AuthClientErrorCode.INVALID_CREDENTIAL;
195
+ case crypto_signer_1.CryptoSignerErrorCode.INVALID_ARGUMENT:
196
+ return error_1.AuthClientErrorCode.INVALID_ARGUMENT;
197
+ default:
198
+ return error_1.AuthClientErrorCode.INTERNAL_ERROR;
199
+ }
200
+ }