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,217 @@
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.transformMillisecondsToSecondsString = exports.generateUpdateMask = exports.formatString = exports.toWebSafeBase64 = exports.findProjectId = exports.getExplicitProjectId = exports.addReadonlyGetter = exports.renameProperties = exports.getSdkVersion = void 0;
21
+ var credential_internal_1 = require("../credential/credential-internal");
22
+ var validator = require("./validator");
23
+ var sdkVersion;
24
+ function getSdkVersion() {
25
+ if (!sdkVersion) {
26
+ var version = require('../../package.json').version; // eslint-disable-line @typescript-eslint/no-var-requires
27
+ sdkVersion = version;
28
+ }
29
+ return sdkVersion;
30
+ }
31
+ exports.getSdkVersion = getSdkVersion;
32
+ /**
33
+ * Renames properties on an object given a mapping from old to new property names.
34
+ *
35
+ * For example, this can be used to map underscore_cased properties to camelCase.
36
+ *
37
+ * @param {object} obj The object whose properties to rename.
38
+ * @param {object} keyMap The mapping from old to new property names.
39
+ */
40
+ function renameProperties(obj, keyMap) {
41
+ Object.keys(keyMap).forEach(function (oldKey) {
42
+ if (oldKey in obj) {
43
+ var newKey = keyMap[oldKey];
44
+ // The old key's value takes precedence over the new key's value.
45
+ obj[newKey] = obj[oldKey];
46
+ delete obj[oldKey];
47
+ }
48
+ });
49
+ }
50
+ exports.renameProperties = renameProperties;
51
+ /**
52
+ * Defines a new read-only property directly on an object and returns the object.
53
+ *
54
+ * @param {object} obj The object on which to define the property.
55
+ * @param {string} prop The name of the property to be defined or modified.
56
+ * @param {any} value The value associated with the property.
57
+ */
58
+ function addReadonlyGetter(obj, prop, value) {
59
+ Object.defineProperty(obj, prop, {
60
+ value: value,
61
+ // Make this property read-only.
62
+ writable: false,
63
+ // Include this property during enumeration of obj's properties.
64
+ enumerable: true,
65
+ });
66
+ }
67
+ exports.addReadonlyGetter = addReadonlyGetter;
68
+ /**
69
+ * Returns the Google Cloud project ID associated with a Firebase app, if it's explicitly
70
+ * specified in either the Firebase app options, credentials or the local environment.
71
+ * Otherwise returns null.
72
+ *
73
+ * @param app A Firebase app to get the project ID from.
74
+ *
75
+ * @return A project ID string or null.
76
+ */
77
+ function getExplicitProjectId(app) {
78
+ var options = app.options;
79
+ if (validator.isNonEmptyString(options.projectId)) {
80
+ return options.projectId;
81
+ }
82
+ var credential = app.options.credential;
83
+ if (credential instanceof credential_internal_1.ServiceAccountCredential) {
84
+ return credential.projectId;
85
+ }
86
+ var projectId = process.env.GOOGLE_CLOUD_PROJECT || process.env.GCLOUD_PROJECT;
87
+ if (validator.isNonEmptyString(projectId)) {
88
+ return projectId;
89
+ }
90
+ return null;
91
+ }
92
+ exports.getExplicitProjectId = getExplicitProjectId;
93
+ /**
94
+ * Determines the Google Cloud project ID associated with a Firebase app. This method
95
+ * first checks if a project ID is explicitly specified in either the Firebase app options,
96
+ * credentials or the local environment in that order. If no explicit project ID is
97
+ * configured, but the SDK has been initialized with ComputeEngineCredentials, this
98
+ * method attempts to discover the project ID from the local metadata service.
99
+ *
100
+ * @param app A Firebase app to get the project ID from.
101
+ *
102
+ * @return A project ID string or null.
103
+ */
104
+ function findProjectId(app) {
105
+ var projectId = getExplicitProjectId(app);
106
+ if (projectId) {
107
+ return Promise.resolve(projectId);
108
+ }
109
+ var credential = app.options.credential;
110
+ if (credential instanceof credential_internal_1.ComputeEngineCredential) {
111
+ return credential.getProjectId();
112
+ }
113
+ return Promise.resolve(null);
114
+ }
115
+ exports.findProjectId = findProjectId;
116
+ /**
117
+ * Encodes data using web-safe-base64.
118
+ *
119
+ * @param {Buffer} data The raw data byte input.
120
+ * @return {string} The base64-encoded result.
121
+ */
122
+ function toWebSafeBase64(data) {
123
+ return data.toString('base64').replace(/\//g, '_').replace(/\+/g, '-');
124
+ }
125
+ exports.toWebSafeBase64 = toWebSafeBase64;
126
+ /**
127
+ * Formats a string of form 'project/{projectId}/{api}' and replaces
128
+ * with corresponding arguments {projectId: '1234', api: 'resource'}
129
+ * and returns output: 'project/1234/resource'.
130
+ *
131
+ * @param {string} str The original string where the param need to be
132
+ * replaced.
133
+ * @param {object=} params The optional parameters to replace in the
134
+ * string.
135
+ * @return {string} The resulting formatted string.
136
+ */
137
+ function formatString(str, params) {
138
+ var formatted = str;
139
+ Object.keys(params || {}).forEach(function (key) {
140
+ formatted = formatted.replace(new RegExp('{' + key + '}', 'g'), params[key]);
141
+ });
142
+ return formatted;
143
+ }
144
+ exports.formatString = formatString;
145
+ /**
146
+ * Generates the update mask for the provided object.
147
+ * Note this will ignore the last key with value undefined.
148
+ *
149
+ * @param obj The object to generate the update mask for.
150
+ * @param terminalPaths The optional map of keys for maximum paths to traverse.
151
+ * Nested objects beyond that path will be ignored. This is useful for
152
+ * keys with variable object values.
153
+ * @param root The path so far.
154
+ * @return The computed update mask list.
155
+ */
156
+ function generateUpdateMask(obj, terminalPaths, root) {
157
+ if (terminalPaths === void 0) { terminalPaths = []; }
158
+ if (root === void 0) { root = ''; }
159
+ var updateMask = [];
160
+ if (!validator.isNonNullObject(obj)) {
161
+ return updateMask;
162
+ }
163
+ var _loop_1 = function (key) {
164
+ if (typeof obj[key] !== 'undefined') {
165
+ var nextPath = root ? root + "." + key : key;
166
+ // We hit maximum path.
167
+ // Consider switching to Set<string> if the list grows too large.
168
+ if (terminalPaths.indexOf(nextPath) !== -1) {
169
+ // Add key and stop traversing this branch.
170
+ updateMask.push(key);
171
+ }
172
+ else {
173
+ var maskList = generateUpdateMask(obj[key], terminalPaths, nextPath);
174
+ if (maskList.length > 0) {
175
+ maskList.forEach(function (mask) {
176
+ updateMask.push(key + "." + mask);
177
+ });
178
+ }
179
+ else {
180
+ updateMask.push(key);
181
+ }
182
+ }
183
+ }
184
+ };
185
+ for (var key in obj) {
186
+ _loop_1(key);
187
+ }
188
+ return updateMask;
189
+ }
190
+ exports.generateUpdateMask = generateUpdateMask;
191
+ /**
192
+ * Transforms milliseconds to a protobuf Duration type string.
193
+ * Returns the duration in seconds with up to nine fractional
194
+ * digits, terminated by 's'. Example: "3 seconds 0 nano seconds as 3s,
195
+ * 3 seconds 1 nano seconds as 3.000000001s".
196
+ *
197
+ * @param milliseconds The duration in milliseconds.
198
+ * @returns The resulting formatted string in seconds with up to nine fractional
199
+ * digits, terminated by 's'.
200
+ */
201
+ function transformMillisecondsToSecondsString(milliseconds) {
202
+ var duration;
203
+ var seconds = Math.floor(milliseconds / 1000);
204
+ var nanos = Math.floor((milliseconds - seconds * 1000) * 1000000);
205
+ if (nanos > 0) {
206
+ var nanoString = nanos.toString();
207
+ while (nanoString.length < 9) {
208
+ nanoString = '0' + nanoString;
209
+ }
210
+ duration = seconds + "." + nanoString + "s";
211
+ }
212
+ else {
213
+ duration = seconds + "s";
214
+ }
215
+ return duration;
216
+ }
217
+ exports.transformMillisecondsToSecondsString = transformMillisecondsToSecondsString;
@@ -0,0 +1,355 @@
1
+ /*! firebase-admin v9.12.0 */
2
+ "use strict";
3
+ /*!
4
+ * Copyright 2021 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
+ var __extends = (this && this.__extends) || (function () {
19
+ var extendStatics = function (d, b) {
20
+ extendStatics = Object.setPrototypeOf ||
21
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
22
+ function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23
+ return extendStatics(d, b);
24
+ };
25
+ return function (d, b) {
26
+ extendStatics(d, b);
27
+ function __() { this.constructor = d; }
28
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
29
+ };
30
+ })();
31
+ Object.defineProperty(exports, "__esModule", { value: true });
32
+ exports.JwtErrorCode = exports.JwtError = exports.decodeJwt = exports.verifyJwtSignature = exports.EmulatorSignatureVerifier = exports.PublicKeySignatureVerifier = exports.UrlKeyFetcher = exports.JwksFetcher = exports.ALGORITHM_RS256 = void 0;
33
+ var validator = require("./validator");
34
+ var jwt = require("jsonwebtoken");
35
+ var jwks = require("jwks-rsa");
36
+ var api_request_1 = require("../utils/api-request");
37
+ exports.ALGORITHM_RS256 = 'RS256';
38
+ // `jsonwebtoken` converts errors from the `getKey` callback to its own `JsonWebTokenError` type
39
+ // and prefixes the error message with the following. Use the prefix to identify errors thrown
40
+ // from the key provider callback.
41
+ // https://github.com/auth0/node-jsonwebtoken/blob/d71e383862fc735991fd2e759181480f066bf138/verify.js#L96
42
+ var JWT_CALLBACK_ERROR_PREFIX = 'error in secret or public key callback: ';
43
+ var NO_MATCHING_KID_ERROR_MESSAGE = 'no-matching-kid-error';
44
+ var NO_KID_IN_HEADER_ERROR_MESSAGE = 'no-kid-in-header-error';
45
+ var HOUR_IN_SECONDS = 3600;
46
+ var JwksFetcher = /** @class */ (function () {
47
+ function JwksFetcher(jwksUrl) {
48
+ this.publicKeysExpireAt = 0;
49
+ if (!validator.isURL(jwksUrl)) {
50
+ throw new Error('The provided JWKS URL is not a valid URL.');
51
+ }
52
+ this.client = jwks({
53
+ jwksUri: jwksUrl,
54
+ cache: false,
55
+ });
56
+ }
57
+ JwksFetcher.prototype.fetchPublicKeys = function () {
58
+ if (this.shouldRefresh()) {
59
+ return this.refresh();
60
+ }
61
+ return Promise.resolve(this.publicKeys);
62
+ };
63
+ JwksFetcher.prototype.shouldRefresh = function () {
64
+ return !this.publicKeys || this.publicKeysExpireAt <= Date.now();
65
+ };
66
+ JwksFetcher.prototype.refresh = function () {
67
+ var _this = this;
68
+ return this.client.getSigningKeys()
69
+ .then(function (signingKeys) {
70
+ // reset expire at from previous set of keys.
71
+ _this.publicKeysExpireAt = 0;
72
+ var newKeys = signingKeys.reduce(function (map, signingKey) {
73
+ map[signingKey.kid] = signingKey.getPublicKey();
74
+ return map;
75
+ }, {});
76
+ _this.publicKeysExpireAt = Date.now() + (HOUR_IN_SECONDS * 6 * 1000);
77
+ _this.publicKeys = newKeys;
78
+ return newKeys;
79
+ }).catch(function (err) {
80
+ throw new Error("Error fetching Json Web Keys: " + err.message);
81
+ });
82
+ };
83
+ return JwksFetcher;
84
+ }());
85
+ exports.JwksFetcher = JwksFetcher;
86
+ /**
87
+ * Class to fetch public keys from a client certificates URL.
88
+ */
89
+ var UrlKeyFetcher = /** @class */ (function () {
90
+ function UrlKeyFetcher(clientCertUrl, httpAgent) {
91
+ this.clientCertUrl = clientCertUrl;
92
+ this.httpAgent = httpAgent;
93
+ this.publicKeysExpireAt = 0;
94
+ if (!validator.isURL(clientCertUrl)) {
95
+ throw new Error('The provided public client certificate URL is not a valid URL.');
96
+ }
97
+ }
98
+ /**
99
+ * Fetches the public keys for the Google certs.
100
+ *
101
+ * @return A promise fulfilled with public keys for the Google certs.
102
+ */
103
+ UrlKeyFetcher.prototype.fetchPublicKeys = function () {
104
+ if (this.shouldRefresh()) {
105
+ return this.refresh();
106
+ }
107
+ return Promise.resolve(this.publicKeys);
108
+ };
109
+ /**
110
+ * Checks if the cached public keys need to be refreshed.
111
+ *
112
+ * @returns Whether the keys should be fetched from the client certs url or not.
113
+ */
114
+ UrlKeyFetcher.prototype.shouldRefresh = function () {
115
+ return !this.publicKeys || this.publicKeysExpireAt <= Date.now();
116
+ };
117
+ UrlKeyFetcher.prototype.refresh = function () {
118
+ var _this = this;
119
+ var client = new api_request_1.HttpClient();
120
+ var request = {
121
+ method: 'GET',
122
+ url: this.clientCertUrl,
123
+ httpAgent: this.httpAgent,
124
+ };
125
+ return client.send(request).then(function (resp) {
126
+ if (!resp.isJson() || resp.data.error) {
127
+ // Treat all non-json messages and messages with an 'error' field as
128
+ // error responses.
129
+ throw new api_request_1.HttpError(resp);
130
+ }
131
+ // reset expire at from previous set of keys.
132
+ _this.publicKeysExpireAt = 0;
133
+ if (Object.prototype.hasOwnProperty.call(resp.headers, 'cache-control')) {
134
+ var cacheControlHeader = resp.headers['cache-control'];
135
+ var parts = cacheControlHeader.split(',');
136
+ parts.forEach(function (part) {
137
+ var subParts = part.trim().split('=');
138
+ if (subParts[0] === 'max-age') {
139
+ var maxAge = +subParts[1];
140
+ _this.publicKeysExpireAt = Date.now() + (maxAge * 1000);
141
+ }
142
+ });
143
+ }
144
+ _this.publicKeys = resp.data;
145
+ return resp.data;
146
+ }).catch(function (err) {
147
+ if (err instanceof api_request_1.HttpError) {
148
+ var errorMessage = 'Error fetching public keys for Google certs: ';
149
+ var resp = err.response;
150
+ if (resp.isJson() && resp.data.error) {
151
+ errorMessage += "" + resp.data.error;
152
+ if (resp.data.error_description) {
153
+ errorMessage += ' (' + resp.data.error_description + ')';
154
+ }
155
+ }
156
+ else {
157
+ errorMessage += "" + resp.text;
158
+ }
159
+ throw new Error(errorMessage);
160
+ }
161
+ throw err;
162
+ });
163
+ };
164
+ return UrlKeyFetcher;
165
+ }());
166
+ exports.UrlKeyFetcher = UrlKeyFetcher;
167
+ /**
168
+ * Class for verifing JWT signature with a public key.
169
+ */
170
+ var PublicKeySignatureVerifier = /** @class */ (function () {
171
+ function PublicKeySignatureVerifier(keyFetcher) {
172
+ this.keyFetcher = keyFetcher;
173
+ if (!validator.isNonNullObject(keyFetcher)) {
174
+ throw new Error('The provided key fetcher is not an object or null.');
175
+ }
176
+ }
177
+ PublicKeySignatureVerifier.withCertificateUrl = function (clientCertUrl, httpAgent) {
178
+ return new PublicKeySignatureVerifier(new UrlKeyFetcher(clientCertUrl, httpAgent));
179
+ };
180
+ PublicKeySignatureVerifier.withJwksUrl = function (jwksUrl) {
181
+ return new PublicKeySignatureVerifier(new JwksFetcher(jwksUrl));
182
+ };
183
+ PublicKeySignatureVerifier.prototype.verify = function (token) {
184
+ var _this = this;
185
+ if (!validator.isString(token)) {
186
+ return Promise.reject(new JwtError(JwtErrorCode.INVALID_ARGUMENT, 'The provided token must be a string.'));
187
+ }
188
+ return verifyJwtSignature(token, getKeyCallback(this.keyFetcher), { algorithms: [exports.ALGORITHM_RS256] })
189
+ .catch(function (error) {
190
+ if (error.code === JwtErrorCode.NO_KID_IN_HEADER) {
191
+ // No kid in JWT header. Try with all the public keys.
192
+ return _this.verifyWithoutKid(token);
193
+ }
194
+ throw error;
195
+ });
196
+ };
197
+ PublicKeySignatureVerifier.prototype.verifyWithoutKid = function (token) {
198
+ var _this = this;
199
+ return this.keyFetcher.fetchPublicKeys()
200
+ .then(function (publicKeys) { return _this.verifyWithAllKeys(token, publicKeys); });
201
+ };
202
+ PublicKeySignatureVerifier.prototype.verifyWithAllKeys = function (token, keys) {
203
+ var promises = [];
204
+ Object.values(keys).forEach(function (key) {
205
+ var result = verifyJwtSignature(token, key)
206
+ .then(function () { return true; })
207
+ .catch(function (error) {
208
+ if (error.code === JwtErrorCode.TOKEN_EXPIRED) {
209
+ throw error;
210
+ }
211
+ return false;
212
+ });
213
+ promises.push(result);
214
+ });
215
+ return Promise.all(promises)
216
+ .then(function (result) {
217
+ if (result.every(function (r) { return r === false; })) {
218
+ throw new JwtError(JwtErrorCode.INVALID_SIGNATURE, 'Invalid token signature.');
219
+ }
220
+ });
221
+ };
222
+ return PublicKeySignatureVerifier;
223
+ }());
224
+ exports.PublicKeySignatureVerifier = PublicKeySignatureVerifier;
225
+ /**
226
+ * Class for verifing unsigned (emulator) JWTs.
227
+ */
228
+ var EmulatorSignatureVerifier = /** @class */ (function () {
229
+ function EmulatorSignatureVerifier() {
230
+ }
231
+ EmulatorSignatureVerifier.prototype.verify = function (token) {
232
+ // Signature checks skipped for emulator; no need to fetch public keys.
233
+ return verifyJwtSignature(token, '');
234
+ };
235
+ return EmulatorSignatureVerifier;
236
+ }());
237
+ exports.EmulatorSignatureVerifier = EmulatorSignatureVerifier;
238
+ /**
239
+ * Provides a callback to fetch public keys.
240
+ *
241
+ * @param fetcher KeyFetcher to fetch the keys from.
242
+ * @returns A callback function that can be used to get keys in `jsonwebtoken`.
243
+ */
244
+ function getKeyCallback(fetcher) {
245
+ return function (header, callback) {
246
+ if (!header.kid) {
247
+ callback(new Error(NO_KID_IN_HEADER_ERROR_MESSAGE));
248
+ }
249
+ var kid = header.kid || '';
250
+ fetcher.fetchPublicKeys().then(function (publicKeys) {
251
+ if (!Object.prototype.hasOwnProperty.call(publicKeys, kid)) {
252
+ callback(new Error(NO_MATCHING_KID_ERROR_MESSAGE));
253
+ }
254
+ else {
255
+ callback(null, publicKeys[kid]);
256
+ }
257
+ })
258
+ .catch(function (error) {
259
+ callback(error);
260
+ });
261
+ };
262
+ }
263
+ /**
264
+ * Verifies the signature of a JWT using the provided secret or a function to fetch
265
+ * the secret or public key.
266
+ *
267
+ * @param token The JWT to be verfied.
268
+ * @param secretOrPublicKey The secret or a function to fetch the secret or public key.
269
+ * @param options JWT verification options.
270
+ * @returns A Promise resolving for a token with a valid signature.
271
+ */
272
+ function verifyJwtSignature(token, secretOrPublicKey, options) {
273
+ if (!validator.isString(token)) {
274
+ return Promise.reject(new JwtError(JwtErrorCode.INVALID_ARGUMENT, 'The provided token must be a string.'));
275
+ }
276
+ return new Promise(function (resolve, reject) {
277
+ jwt.verify(token, secretOrPublicKey, options, function (error) {
278
+ if (!error) {
279
+ return resolve();
280
+ }
281
+ if (error.name === 'TokenExpiredError') {
282
+ return reject(new JwtError(JwtErrorCode.TOKEN_EXPIRED, 'The provided token has expired. Get a fresh token from your ' +
283
+ 'client app and try again.'));
284
+ }
285
+ else if (error.name === 'JsonWebTokenError') {
286
+ if (error.message && error.message.includes(JWT_CALLBACK_ERROR_PREFIX)) {
287
+ var message = error.message.split(JWT_CALLBACK_ERROR_PREFIX).pop() || 'Error fetching public keys.';
288
+ var code = JwtErrorCode.KEY_FETCH_ERROR;
289
+ if (message === NO_MATCHING_KID_ERROR_MESSAGE) {
290
+ code = JwtErrorCode.NO_MATCHING_KID;
291
+ }
292
+ else if (message === NO_KID_IN_HEADER_ERROR_MESSAGE) {
293
+ code = JwtErrorCode.NO_KID_IN_HEADER;
294
+ }
295
+ return reject(new JwtError(code, message));
296
+ }
297
+ }
298
+ return reject(new JwtError(JwtErrorCode.INVALID_SIGNATURE, error.message));
299
+ });
300
+ });
301
+ }
302
+ exports.verifyJwtSignature = verifyJwtSignature;
303
+ /**
304
+ * Decodes general purpose Firebase JWTs.
305
+ *
306
+ * @param jwtToken JWT token to be decoded.
307
+ * @returns Decoded token containing the header and payload.
308
+ */
309
+ function decodeJwt(jwtToken) {
310
+ if (!validator.isString(jwtToken)) {
311
+ return Promise.reject(new JwtError(JwtErrorCode.INVALID_ARGUMENT, 'The provided token must be a string.'));
312
+ }
313
+ var fullDecodedToken = jwt.decode(jwtToken, {
314
+ complete: true,
315
+ });
316
+ if (!fullDecodedToken) {
317
+ return Promise.reject(new JwtError(JwtErrorCode.INVALID_ARGUMENT, 'Decoding token failed.'));
318
+ }
319
+ var header = fullDecodedToken === null || fullDecodedToken === void 0 ? void 0 : fullDecodedToken.header;
320
+ var payload = fullDecodedToken === null || fullDecodedToken === void 0 ? void 0 : fullDecodedToken.payload;
321
+ return Promise.resolve({ header: header, payload: payload });
322
+ }
323
+ exports.decodeJwt = decodeJwt;
324
+ /**
325
+ * Jwt error code structure.
326
+ *
327
+ * @param code The error code.
328
+ * @param message The error message.
329
+ * @constructor
330
+ */
331
+ var JwtError = /** @class */ (function (_super) {
332
+ __extends(JwtError, _super);
333
+ function JwtError(code, message) {
334
+ var _this = _super.call(this, message) || this;
335
+ _this.code = code;
336
+ _this.message = message;
337
+ _this.__proto__ = JwtError.prototype;
338
+ return _this;
339
+ }
340
+ return JwtError;
341
+ }(Error));
342
+ exports.JwtError = JwtError;
343
+ /**
344
+ * JWT error codes.
345
+ */
346
+ var JwtErrorCode;
347
+ (function (JwtErrorCode) {
348
+ JwtErrorCode["INVALID_ARGUMENT"] = "invalid-argument";
349
+ JwtErrorCode["INVALID_CREDENTIAL"] = "invalid-credential";
350
+ JwtErrorCode["TOKEN_EXPIRED"] = "token-expired";
351
+ JwtErrorCode["INVALID_SIGNATURE"] = "invalid-token";
352
+ JwtErrorCode["NO_MATCHING_KID"] = "no-matching-kid-error";
353
+ JwtErrorCode["NO_KID_IN_HEADER"] = "no-kid-error";
354
+ JwtErrorCode["KEY_FETCH_ERROR"] = "key-fetch-error";
355
+ })(JwtErrorCode = exports.JwtErrorCode || (exports.JwtErrorCode = {}));