mirror of
https://github.com/musix-org/musix-oss
synced 2025-06-17 10:46:01 +00:00
Modules
This commit is contained in:
117
node_modules/firebase-admin/lib/auth/action-code-settings-builder.js
generated
vendored
Normal file
117
node_modules/firebase-admin/lib/auth/action-code-settings-builder.js
generated
vendored
Normal file
@ -0,0 +1,117 @@
|
||||
/*! firebase-admin v8.9.2 */
|
||||
"use strict";
|
||||
/*!
|
||||
* Copyright 2018 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
var validator = require("../utils/validator");
|
||||
var error_1 = require("../utils/error");
|
||||
/**
|
||||
* Defines the ActionCodeSettings builder class used to convert the
|
||||
* ActionCodeSettings object to its corresponding server request.
|
||||
*/
|
||||
var ActionCodeSettingsBuilder = /** @class */ (function () {
|
||||
/**
|
||||
* ActionCodeSettingsBuilder constructor.
|
||||
*
|
||||
* @param {ActionCodeSettings} actionCodeSettings The ActionCodeSettings
|
||||
* object used to initiliaze this server request builder.
|
||||
* @constructor
|
||||
*/
|
||||
function ActionCodeSettingsBuilder(actionCodeSettings) {
|
||||
if (!validator.isNonNullObject(actionCodeSettings)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"ActionCodeSettings" must be a non-null object.');
|
||||
}
|
||||
if (typeof actionCodeSettings.url === 'undefined') {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.MISSING_CONTINUE_URI);
|
||||
}
|
||||
else if (!validator.isURL(actionCodeSettings.url)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONTINUE_URI);
|
||||
}
|
||||
this.continueUrl = actionCodeSettings.url;
|
||||
if (typeof actionCodeSettings.handleCodeInApp !== 'undefined' &&
|
||||
!validator.isBoolean(actionCodeSettings.handleCodeInApp)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"ActionCodeSettings.handleCodeInApp" must be a boolean.');
|
||||
}
|
||||
this.canHandleCodeInApp = actionCodeSettings.handleCodeInApp || false;
|
||||
if (typeof actionCodeSettings.dynamicLinkDomain !== 'undefined' &&
|
||||
!validator.isNonEmptyString(actionCodeSettings.dynamicLinkDomain)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_DYNAMIC_LINK_DOMAIN);
|
||||
}
|
||||
this.dynamicLinkDomain = actionCodeSettings.dynamicLinkDomain;
|
||||
if (typeof actionCodeSettings.iOS !== 'undefined') {
|
||||
if (!validator.isNonNullObject(actionCodeSettings.iOS)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"ActionCodeSettings.iOS" must be a valid non-null object.');
|
||||
}
|
||||
else if (typeof actionCodeSettings.iOS.bundleId === 'undefined') {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.MISSING_IOS_BUNDLE_ID);
|
||||
}
|
||||
else if (!validator.isNonEmptyString(actionCodeSettings.iOS.bundleId)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"ActionCodeSettings.iOS.bundleId" must be a valid non-empty string.');
|
||||
}
|
||||
this.ibi = actionCodeSettings.iOS.bundleId;
|
||||
}
|
||||
if (typeof actionCodeSettings.android !== 'undefined') {
|
||||
if (!validator.isNonNullObject(actionCodeSettings.android)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"ActionCodeSettings.android" must be a valid non-null object.');
|
||||
}
|
||||
else if (typeof actionCodeSettings.android.packageName === 'undefined') {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.MISSING_ANDROID_PACKAGE_NAME);
|
||||
}
|
||||
else if (!validator.isNonEmptyString(actionCodeSettings.android.packageName)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"ActionCodeSettings.android.packageName" must be a valid non-empty string.');
|
||||
}
|
||||
else if (typeof actionCodeSettings.android.minimumVersion !== 'undefined' &&
|
||||
!validator.isNonEmptyString(actionCodeSettings.android.minimumVersion)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"ActionCodeSettings.android.minimumVersion" must be a valid non-empty string.');
|
||||
}
|
||||
else if (typeof actionCodeSettings.android.installApp !== 'undefined' &&
|
||||
!validator.isBoolean(actionCodeSettings.android.installApp)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"ActionCodeSettings.android.installApp" must be a valid boolean.');
|
||||
}
|
||||
this.apn = actionCodeSettings.android.packageName;
|
||||
this.amv = actionCodeSettings.android.minimumVersion;
|
||||
this.installApp = actionCodeSettings.android.installApp || false;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Returns the corresponding constructed server request corresponding to the
|
||||
* current ActionCodeSettings.
|
||||
*
|
||||
* @return {EmailActionCodeRequest} The constructed EmailActionCodeRequest request.
|
||||
*/
|
||||
ActionCodeSettingsBuilder.prototype.buildRequest = function () {
|
||||
var request = {
|
||||
continueUrl: this.continueUrl,
|
||||
canHandleCodeInApp: this.canHandleCodeInApp,
|
||||
dynamicLinkDomain: this.dynamicLinkDomain,
|
||||
androidPackageName: this.apn,
|
||||
androidMinimumVersion: this.amv,
|
||||
androidInstallApp: this.installApp,
|
||||
iOSBundleId: this.ibi,
|
||||
};
|
||||
// Remove all null and undefined fields from request.
|
||||
for (var key in request) {
|
||||
if (request.hasOwnProperty(key)) {
|
||||
if (typeof request[key] === 'undefined' || request[key] === null) {
|
||||
delete request[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
return request;
|
||||
};
|
||||
return ActionCodeSettingsBuilder;
|
||||
}());
|
||||
exports.ActionCodeSettingsBuilder = ActionCodeSettingsBuilder;
|
1503
node_modules/firebase-admin/lib/auth/auth-api-request.js
generated
vendored
Normal file
1503
node_modules/firebase-admin/lib/auth/auth-api-request.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
447
node_modules/firebase-admin/lib/auth/auth-config.js
generated
vendored
Normal file
447
node_modules/firebase-admin/lib/auth/auth-config.js
generated
vendored
Normal file
@ -0,0 +1,447 @@
|
||||
/*! firebase-admin v8.9.2 */
|
||||
"use strict";
|
||||
/*!
|
||||
* Copyright 2018 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
var validator = require("../utils/validator");
|
||||
var deep_copy_1 = require("../utils/deep-copy");
|
||||
var error_1 = require("../utils/error");
|
||||
/**
|
||||
* Defines the email sign-in config class used to convert client side EmailSignInConfig
|
||||
* to a format that is understood by the Auth server.
|
||||
*/
|
||||
var EmailSignInConfig = /** @class */ (function () {
|
||||
/**
|
||||
* The EmailSignInConfig constructor.
|
||||
*
|
||||
* @param {any} response The server side response used to initialize the
|
||||
* EmailSignInConfig object.
|
||||
* @constructor
|
||||
*/
|
||||
function EmailSignInConfig(response) {
|
||||
if (typeof response.allowPasswordSignup === 'undefined') {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid email sign-in configuration response');
|
||||
}
|
||||
this.enabled = response.allowPasswordSignup;
|
||||
this.passwordRequired = !response.enableEmailLinkSignin;
|
||||
}
|
||||
/**
|
||||
* Static method to convert a client side request to a EmailSignInConfigServerRequest.
|
||||
* Throws an error if validation fails.
|
||||
*
|
||||
* @param {any} options The options object to convert to a server request.
|
||||
* @return {EmailSignInConfigServerRequest} The resulting server request.
|
||||
*/
|
||||
EmailSignInConfig.buildServerRequest = function (options) {
|
||||
var request = {};
|
||||
EmailSignInConfig.validate(options);
|
||||
if (options.hasOwnProperty('enabled')) {
|
||||
request.allowPasswordSignup = options.enabled;
|
||||
}
|
||||
if (options.hasOwnProperty('passwordRequired')) {
|
||||
request.enableEmailLinkSignin = !options.passwordRequired;
|
||||
}
|
||||
return request;
|
||||
};
|
||||
/**
|
||||
* Validates the EmailSignInConfig options object. Throws an error on failure.
|
||||
*
|
||||
* @param {any} options The options object to validate.
|
||||
*/
|
||||
EmailSignInConfig.validate = function (options) {
|
||||
// TODO: Validate the request.
|
||||
var validKeys = {
|
||||
enabled: true,
|
||||
passwordRequired: true,
|
||||
};
|
||||
if (!validator.isNonNullObject(options)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"EmailSignInConfig" must be a non-null object.');
|
||||
}
|
||||
// Check for unsupported top level attributes.
|
||||
for (var key in options) {
|
||||
if (!(key in validKeys)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, "\"" + key + "\" is not a valid EmailSignInConfig parameter.");
|
||||
}
|
||||
}
|
||||
// Validate content.
|
||||
if (typeof options.enabled !== 'undefined' &&
|
||||
!validator.isBoolean(options.enabled)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"EmailSignInConfig.enabled" must be a boolean.');
|
||||
}
|
||||
if (typeof options.passwordRequired !== 'undefined' &&
|
||||
!validator.isBoolean(options.passwordRequired)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"EmailSignInConfig.passwordRequired" must be a boolean.');
|
||||
}
|
||||
};
|
||||
/** @return {object} The plain object representation of the email sign-in config. */
|
||||
EmailSignInConfig.prototype.toJSON = function () {
|
||||
return {
|
||||
enabled: this.enabled,
|
||||
passwordRequired: this.passwordRequired,
|
||||
};
|
||||
};
|
||||
return EmailSignInConfig;
|
||||
}());
|
||||
exports.EmailSignInConfig = EmailSignInConfig;
|
||||
/**
|
||||
* Defines the SAMLConfig class used to convert a client side configuration to its
|
||||
* server side representation.
|
||||
*/
|
||||
var SAMLConfig = /** @class */ (function () {
|
||||
/**
|
||||
* The SAMLConfig constructor.
|
||||
*
|
||||
* @param {any} response The server side response used to initialize the SAMLConfig object.
|
||||
* @constructor
|
||||
*/
|
||||
function SAMLConfig(response) {
|
||||
if (!response ||
|
||||
!response.idpConfig ||
|
||||
!response.idpConfig.idpEntityId ||
|
||||
!response.idpConfig.ssoUrl ||
|
||||
!response.spConfig ||
|
||||
!response.spConfig.spEntityId ||
|
||||
!response.name ||
|
||||
!(validator.isString(response.name) &&
|
||||
SAMLConfig.getProviderIdFromResourceName(response.name))) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid SAML configuration response');
|
||||
}
|
||||
var providerId = SAMLConfig.getProviderIdFromResourceName(response.name);
|
||||
if (!providerId) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid SAML configuration response');
|
||||
}
|
||||
this.providerId = providerId;
|
||||
// RP config.
|
||||
this.rpEntityId = response.spConfig.spEntityId;
|
||||
this.callbackURL = response.spConfig.callbackUri;
|
||||
// IdP config.
|
||||
this.idpEntityId = response.idpConfig.idpEntityId;
|
||||
this.ssoURL = response.idpConfig.ssoUrl;
|
||||
this.enableRequestSigning = !!response.idpConfig.signRequest;
|
||||
var x509Certificates = [];
|
||||
for (var _i = 0, _a = (response.idpConfig.idpCertificates || []); _i < _a.length; _i++) {
|
||||
var cert = _a[_i];
|
||||
if (cert.x509Certificate) {
|
||||
x509Certificates.push(cert.x509Certificate);
|
||||
}
|
||||
}
|
||||
this.x509Certificates = x509Certificates;
|
||||
// When enabled is undefined, it takes its default value of false.
|
||||
this.enabled = !!response.enabled;
|
||||
this.displayName = response.displayName;
|
||||
}
|
||||
/**
|
||||
* Converts a client side request to a SAMLConfigServerRequest which is the format
|
||||
* accepted by the backend server.
|
||||
* Throws an error if validation fails. If the request is not a SAMLConfig request,
|
||||
* returns null.
|
||||
*
|
||||
* @param {SAMLAuthProviderRequest} options The options object to convert to a server request.
|
||||
* @param {boolean=} ignoreMissingFields Whether to ignore missing fields.
|
||||
* @return {?SAMLConfigServerRequest} The resulting server request or null if not valid.
|
||||
*/
|
||||
SAMLConfig.buildServerRequest = function (options, ignoreMissingFields) {
|
||||
if (ignoreMissingFields === void 0) { ignoreMissingFields = false; }
|
||||
var makeRequest = validator.isNonNullObject(options) &&
|
||||
(options.providerId || ignoreMissingFields);
|
||||
if (!makeRequest) {
|
||||
return null;
|
||||
}
|
||||
var request = {};
|
||||
// Validate options.
|
||||
SAMLConfig.validate(options, ignoreMissingFields);
|
||||
request.enabled = options.enabled;
|
||||
request.displayName = options.displayName;
|
||||
// IdP config.
|
||||
if (options.idpEntityId || options.ssoURL || options.x509Certificates) {
|
||||
request.idpConfig = {
|
||||
idpEntityId: options.idpEntityId,
|
||||
ssoUrl: options.ssoURL,
|
||||
signRequest: options.enableRequestSigning,
|
||||
idpCertificates: typeof options.x509Certificates === 'undefined' ? undefined : [],
|
||||
};
|
||||
if (options.x509Certificates) {
|
||||
for (var _i = 0, _a = (options.x509Certificates || []); _i < _a.length; _i++) {
|
||||
var cert = _a[_i];
|
||||
request.idpConfig.idpCertificates.push({ x509Certificate: cert });
|
||||
}
|
||||
}
|
||||
}
|
||||
// RP config.
|
||||
if (options.callbackURL || options.rpEntityId) {
|
||||
request.spConfig = {
|
||||
spEntityId: options.rpEntityId,
|
||||
callbackUri: options.callbackURL,
|
||||
};
|
||||
}
|
||||
return request;
|
||||
};
|
||||
/**
|
||||
* Returns the provider ID corresponding to the resource name if available.
|
||||
*
|
||||
* @param {string} resourceName The server side resource name.
|
||||
* @return {?string} The provider ID corresponding to the resource, null otherwise.
|
||||
*/
|
||||
SAMLConfig.getProviderIdFromResourceName = function (resourceName) {
|
||||
// name is of form projects/project1/inboundSamlConfigs/providerId1
|
||||
var matchProviderRes = resourceName.match(/\/inboundSamlConfigs\/(saml\..*)$/);
|
||||
if (!matchProviderRes || matchProviderRes.length < 2) {
|
||||
return null;
|
||||
}
|
||||
return matchProviderRes[1];
|
||||
};
|
||||
/**
|
||||
* @param {any} providerId The provider ID to check.
|
||||
* @return {boolean} Whether the provider ID corresponds to a SAML provider.
|
||||
*/
|
||||
SAMLConfig.isProviderId = function (providerId) {
|
||||
return validator.isNonEmptyString(providerId) && providerId.indexOf('saml.') === 0;
|
||||
};
|
||||
/**
|
||||
* Validates the SAMLConfig options object. Throws an error on failure.
|
||||
*
|
||||
* @param {SAMLAuthProviderRequest} options The options object to validate.
|
||||
* @param {boolean=} ignoreMissingFields Whether to ignore missing fields.
|
||||
*/
|
||||
SAMLConfig.validate = function (options, ignoreMissingFields) {
|
||||
if (ignoreMissingFields === void 0) { ignoreMissingFields = false; }
|
||||
var validKeys = {
|
||||
enabled: true,
|
||||
displayName: true,
|
||||
providerId: true,
|
||||
idpEntityId: true,
|
||||
ssoURL: true,
|
||||
x509Certificates: true,
|
||||
rpEntityId: true,
|
||||
callbackURL: true,
|
||||
enableRequestSigning: true,
|
||||
};
|
||||
if (!validator.isNonNullObject(options)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig" must be a valid non-null object.');
|
||||
}
|
||||
// Check for unsupported top level attributes.
|
||||
for (var key in options) {
|
||||
if (!(key in validKeys)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, "\"" + key + "\" is not a valid SAML config parameter.");
|
||||
}
|
||||
}
|
||||
// Required fields.
|
||||
if (validator.isNonEmptyString(options.providerId)) {
|
||||
if (options.providerId.indexOf('saml.') !== 0) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PROVIDER_ID, '"SAMLAuthProviderConfig.providerId" must be a valid non-empty string prefixed with "saml.".');
|
||||
}
|
||||
}
|
||||
else if (!ignoreMissingFields) {
|
||||
// providerId is required and not provided correctly.
|
||||
throw new error_1.FirebaseAuthError(!options.providerId ? error_1.AuthClientErrorCode.MISSING_PROVIDER_ID : error_1.AuthClientErrorCode.INVALID_PROVIDER_ID, '"SAMLAuthProviderConfig.providerId" must be a valid non-empty string prefixed with "saml.".');
|
||||
}
|
||||
if (!(ignoreMissingFields && typeof options.idpEntityId === 'undefined') &&
|
||||
!validator.isNonEmptyString(options.idpEntityId)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig.idpEntityId" must be a valid non-empty string.');
|
||||
}
|
||||
if (!(ignoreMissingFields && typeof options.ssoURL === 'undefined') &&
|
||||
!validator.isURL(options.ssoURL)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig.ssoURL" must be a valid URL string.');
|
||||
}
|
||||
if (!(ignoreMissingFields && typeof options.rpEntityId === 'undefined') &&
|
||||
!validator.isNonEmptyString(options.rpEntityId)) {
|
||||
throw new error_1.FirebaseAuthError(!options.rpEntityId ? error_1.AuthClientErrorCode.MISSING_SAML_RELYING_PARTY_CONFIG :
|
||||
error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig.rpEntityId" must be a valid non-empty string.');
|
||||
}
|
||||
if (!(ignoreMissingFields && typeof options.callbackURL === 'undefined') &&
|
||||
!validator.isURL(options.callbackURL)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig.callbackURL" must be a valid URL string.');
|
||||
}
|
||||
if (!(ignoreMissingFields && typeof options.x509Certificates === 'undefined') &&
|
||||
!validator.isArray(options.x509Certificates)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig.x509Certificates" must be a valid array of X509 certificate strings.');
|
||||
}
|
||||
(options.x509Certificates || []).forEach(function (cert) {
|
||||
if (!validator.isNonEmptyString(cert)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig.x509Certificates" must be a valid array of X509 certificate strings.');
|
||||
}
|
||||
});
|
||||
if (typeof options.enableRequestSigning !== 'undefined' &&
|
||||
!validator.isBoolean(options.enableRequestSigning)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig.enableRequestSigning" must be a boolean.');
|
||||
}
|
||||
if (typeof options.enabled !== 'undefined' &&
|
||||
!validator.isBoolean(options.enabled)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig.enabled" must be a boolean.');
|
||||
}
|
||||
if (typeof options.displayName !== 'undefined' &&
|
||||
!validator.isString(options.displayName)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"SAMLAuthProviderConfig.displayName" must be a valid string.');
|
||||
}
|
||||
};
|
||||
/** @return {SAMLAuthProviderConfig} The plain object representation of the SAMLConfig. */
|
||||
SAMLConfig.prototype.toJSON = function () {
|
||||
return {
|
||||
enabled: this.enabled,
|
||||
displayName: this.displayName,
|
||||
providerId: this.providerId,
|
||||
idpEntityId: this.idpEntityId,
|
||||
ssoURL: this.ssoURL,
|
||||
x509Certificates: deep_copy_1.deepCopy(this.x509Certificates),
|
||||
rpEntityId: this.rpEntityId,
|
||||
callbackURL: this.callbackURL,
|
||||
enableRequestSigning: this.enableRequestSigning,
|
||||
};
|
||||
};
|
||||
return SAMLConfig;
|
||||
}());
|
||||
exports.SAMLConfig = SAMLConfig;
|
||||
/**
|
||||
* Defines the OIDCConfig class used to convert a client side configuration to its
|
||||
* server side representation.
|
||||
*/
|
||||
var OIDCConfig = /** @class */ (function () {
|
||||
/**
|
||||
* The OIDCConfig constructor.
|
||||
*
|
||||
* @param {any} response The server side response used to initialize the OIDCConfig object.
|
||||
* @constructor
|
||||
*/
|
||||
function OIDCConfig(response) {
|
||||
if (!response ||
|
||||
!response.issuer ||
|
||||
!response.clientId ||
|
||||
!response.name ||
|
||||
!(validator.isString(response.name) &&
|
||||
OIDCConfig.getProviderIdFromResourceName(response.name))) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid OIDC configuration response');
|
||||
}
|
||||
var providerId = OIDCConfig.getProviderIdFromResourceName(response.name);
|
||||
if (!providerId) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid SAML configuration response');
|
||||
}
|
||||
this.providerId = providerId;
|
||||
this.clientId = response.clientId;
|
||||
this.issuer = response.issuer;
|
||||
// When enabled is undefined, it takes its default value of false.
|
||||
this.enabled = !!response.enabled;
|
||||
this.displayName = response.displayName;
|
||||
}
|
||||
/**
|
||||
* Converts a client side request to a OIDCConfigServerRequest which is the format
|
||||
* accepted by the backend server.
|
||||
* Throws an error if validation fails. If the request is not a OIDCConfig request,
|
||||
* returns null.
|
||||
*
|
||||
* @param {OIDCAuthProviderRequest} options The options object to convert to a server request.
|
||||
* @param {boolean=} ignoreMissingFields Whether to ignore missing fields.
|
||||
* @return {?OIDCConfigServerRequest} The resulting server request or null if not valid.
|
||||
*/
|
||||
OIDCConfig.buildServerRequest = function (options, ignoreMissingFields) {
|
||||
if (ignoreMissingFields === void 0) { ignoreMissingFields = false; }
|
||||
var makeRequest = validator.isNonNullObject(options) &&
|
||||
(options.providerId || ignoreMissingFields);
|
||||
if (!makeRequest) {
|
||||
return null;
|
||||
}
|
||||
var request = {};
|
||||
// Validate options.
|
||||
OIDCConfig.validate(options, ignoreMissingFields);
|
||||
request.enabled = options.enabled;
|
||||
request.displayName = options.displayName;
|
||||
request.issuer = options.issuer;
|
||||
request.clientId = options.clientId;
|
||||
return request;
|
||||
};
|
||||
/**
|
||||
* Returns the provider ID corresponding to the resource name if available.
|
||||
*
|
||||
* @param {string} resourceName The server side resource name
|
||||
* @return {?string} The provider ID corresponding to the resource, null otherwise.
|
||||
*/
|
||||
OIDCConfig.getProviderIdFromResourceName = function (resourceName) {
|
||||
// name is of form projects/project1/oauthIdpConfigs/providerId1
|
||||
var matchProviderRes = resourceName.match(/\/oauthIdpConfigs\/(oidc\..*)$/);
|
||||
if (!matchProviderRes || matchProviderRes.length < 2) {
|
||||
return null;
|
||||
}
|
||||
return matchProviderRes[1];
|
||||
};
|
||||
/**
|
||||
* @param {any} providerId The provider ID to check.
|
||||
* @return {boolean} Whether the provider ID corresponds to an OIDC provider.
|
||||
*/
|
||||
OIDCConfig.isProviderId = function (providerId) {
|
||||
return validator.isNonEmptyString(providerId) && providerId.indexOf('oidc.') === 0;
|
||||
};
|
||||
/**
|
||||
* Validates the OIDCConfig options object. Throws an error on failure.
|
||||
*
|
||||
* @param {OIDCAuthProviderRequest} options The options object to validate.
|
||||
* @param {boolean=} ignoreMissingFields Whether to ignore missing fields.
|
||||
*/
|
||||
OIDCConfig.validate = function (options, ignoreMissingFields) {
|
||||
if (ignoreMissingFields === void 0) { ignoreMissingFields = false; }
|
||||
var validKeys = {
|
||||
enabled: true,
|
||||
displayName: true,
|
||||
providerId: true,
|
||||
clientId: true,
|
||||
issuer: true,
|
||||
};
|
||||
if (!validator.isNonNullObject(options)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"OIDCAuthProviderConfig" must be a valid non-null object.');
|
||||
}
|
||||
// Check for unsupported top level attributes.
|
||||
for (var key in options) {
|
||||
if (!(key in validKeys)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, "\"" + key + "\" is not a valid OIDC config parameter.");
|
||||
}
|
||||
}
|
||||
// Required fields.
|
||||
if (validator.isNonEmptyString(options.providerId)) {
|
||||
if (options.providerId.indexOf('oidc.') !== 0) {
|
||||
throw new error_1.FirebaseAuthError(!options.providerId ? error_1.AuthClientErrorCode.MISSING_PROVIDER_ID : error_1.AuthClientErrorCode.INVALID_PROVIDER_ID, '"OIDCAuthProviderConfig.providerId" must be a valid non-empty string prefixed with "oidc.".');
|
||||
}
|
||||
}
|
||||
else if (!ignoreMissingFields) {
|
||||
throw new error_1.FirebaseAuthError(!options.providerId ? error_1.AuthClientErrorCode.MISSING_PROVIDER_ID : error_1.AuthClientErrorCode.INVALID_PROVIDER_ID, '"OIDCAuthProviderConfig.providerId" must be a valid non-empty string prefixed with "oidc.".');
|
||||
}
|
||||
if (!(ignoreMissingFields && typeof options.clientId === 'undefined') &&
|
||||
!validator.isNonEmptyString(options.clientId)) {
|
||||
throw new error_1.FirebaseAuthError(!options.clientId ? error_1.AuthClientErrorCode.MISSING_OAUTH_CLIENT_ID : error_1.AuthClientErrorCode.INVALID_OAUTH_CLIENT_ID, '"OIDCAuthProviderConfig.clientId" must be a valid non-empty string.');
|
||||
}
|
||||
if (!(ignoreMissingFields && typeof options.issuer === 'undefined') &&
|
||||
!validator.isURL(options.issuer)) {
|
||||
throw new error_1.FirebaseAuthError(!options.issuer ? error_1.AuthClientErrorCode.MISSING_ISSUER : error_1.AuthClientErrorCode.INVALID_CONFIG, '"OIDCAuthProviderConfig.issuer" must be a valid URL string.');
|
||||
}
|
||||
if (typeof options.enabled !== 'undefined' &&
|
||||
!validator.isBoolean(options.enabled)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"OIDCAuthProviderConfig.enabled" must be a boolean.');
|
||||
}
|
||||
if (typeof options.displayName !== 'undefined' &&
|
||||
!validator.isString(options.displayName)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, '"OIDCAuthProviderConfig.displayName" must be a valid string.');
|
||||
}
|
||||
};
|
||||
/** @return {OIDCAuthProviderConfig} The plain object representation of the OIDCConfig. */
|
||||
OIDCConfig.prototype.toJSON = function () {
|
||||
return {
|
||||
enabled: this.enabled,
|
||||
displayName: this.displayName,
|
||||
providerId: this.providerId,
|
||||
issuer: this.issuer,
|
||||
clientId: this.clientId,
|
||||
};
|
||||
};
|
||||
return OIDCConfig;
|
||||
}());
|
||||
exports.OIDCConfig = OIDCConfig;
|
674
node_modules/firebase-admin/lib/auth/auth.js
generated
vendored
Normal file
674
node_modules/firebase-admin/lib/auth/auth.js
generated
vendored
Normal file
@ -0,0 +1,674 @@
|
||||
/*! firebase-admin v8.9.2 */
|
||||
"use strict";
|
||||
/*!
|
||||
* Copyright 2017 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
var __extends = (this && this.__extends) || (function () {
|
||||
var extendStatics = function (d, b) {
|
||||
extendStatics = Object.setPrototypeOf ||
|
||||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
|
||||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
|
||||
return extendStatics(d, b);
|
||||
};
|
||||
return function (d, b) {
|
||||
extendStatics(d, b);
|
||||
function __() { this.constructor = d; }
|
||||
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
|
||||
};
|
||||
})();
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
var user_record_1 = require("./user-record");
|
||||
var token_generator_1 = require("./token-generator");
|
||||
var auth_api_request_1 = require("./auth-api-request");
|
||||
var error_1 = require("../utils/error");
|
||||
var utils = require("../utils/index");
|
||||
var validator = require("../utils/validator");
|
||||
var token_verifier_1 = require("./token-verifier");
|
||||
var auth_config_1 = require("./auth-config");
|
||||
var tenant_manager_1 = require("./tenant-manager");
|
||||
/**
|
||||
* Internals of an Auth instance.
|
||||
*/
|
||||
var AuthInternals = /** @class */ (function () {
|
||||
function AuthInternals() {
|
||||
}
|
||||
/**
|
||||
* Deletes the service and its associated resources.
|
||||
*
|
||||
* @return {Promise<()>} An empty Promise that will be fulfilled when the service is deleted.
|
||||
*/
|
||||
AuthInternals.prototype.delete = function () {
|
||||
// There are no resources to clean up
|
||||
return Promise.resolve(undefined);
|
||||
};
|
||||
return AuthInternals;
|
||||
}());
|
||||
/**
|
||||
* Base Auth class. Mainly used for user management APIs.
|
||||
*/
|
||||
var BaseAuth = /** @class */ (function () {
|
||||
/**
|
||||
* The BaseAuth class constructor.
|
||||
*
|
||||
* @param app The FirebaseApp to associate with this Auth instance.
|
||||
* @param authRequestHandler The RPC request handler for this instance.
|
||||
* @param tokenGenerator Optional token generator. If not specified, a
|
||||
* (non-tenant-aware) instance will be created. Use this paramter to
|
||||
* specify a tenant-aware tokenGenerator.
|
||||
* @constructor
|
||||
*/
|
||||
function BaseAuth(app, authRequestHandler, tokenGenerator) {
|
||||
this.authRequestHandler = authRequestHandler;
|
||||
if (tokenGenerator) {
|
||||
this.tokenGenerator = tokenGenerator;
|
||||
}
|
||||
else {
|
||||
var cryptoSigner = token_generator_1.cryptoSignerFromApp(app);
|
||||
this.tokenGenerator = new token_generator_1.FirebaseTokenGenerator(cryptoSigner);
|
||||
}
|
||||
this.sessionCookieVerifier = token_verifier_1.createSessionCookieVerifier(app);
|
||||
this.idTokenVerifier = token_verifier_1.createIdTokenVerifier(app);
|
||||
}
|
||||
/**
|
||||
* Creates a new custom token that can be sent back to a client to use with
|
||||
* signInWithCustomToken().
|
||||
*
|
||||
* @param {string} uid The uid to use as the JWT subject.
|
||||
* @param {object=} developerClaims Optional additional claims to include in the JWT payload.
|
||||
*
|
||||
* @return {Promise<string>} A JWT for the provided payload.
|
||||
*/
|
||||
BaseAuth.prototype.createCustomToken = function (uid, developerClaims) {
|
||||
return this.tokenGenerator.createCustomToken(uid, developerClaims);
|
||||
};
|
||||
/**
|
||||
* Verifies a JWT auth token. Returns a Promise with the tokens claims. Rejects
|
||||
* the promise if the token could not be verified. If checkRevoked is set to true,
|
||||
* verifies if the session corresponding to the ID token was revoked. If the corresponding
|
||||
* user's session was invalidated, an auth/id-token-revoked error is thrown. If not specified
|
||||
* the check is not applied.
|
||||
*
|
||||
* @param {string} idToken The JWT to verify.
|
||||
* @param {boolean=} checkRevoked Whether to check if the ID token is revoked.
|
||||
* @return {Promise<DecodedIdToken>} A Promise that will be fulfilled after a successful
|
||||
* verification.
|
||||
*/
|
||||
BaseAuth.prototype.verifyIdToken = function (idToken, checkRevoked) {
|
||||
var _this = this;
|
||||
if (checkRevoked === void 0) { checkRevoked = false; }
|
||||
return this.idTokenVerifier.verifyJWT(idToken)
|
||||
.then(function (decodedIdToken) {
|
||||
// Whether to check if the token was revoked.
|
||||
if (!checkRevoked) {
|
||||
return decodedIdToken;
|
||||
}
|
||||
return _this.verifyDecodedJWTNotRevoked(decodedIdToken, error_1.AuthClientErrorCode.ID_TOKEN_REVOKED);
|
||||
});
|
||||
};
|
||||
/**
|
||||
* Looks up the user identified by the provided user id and returns a promise that is
|
||||
* fulfilled with a user record for the given user if that user is found.
|
||||
*
|
||||
* @param {string} uid The uid of the user to look up.
|
||||
* @return {Promise<UserRecord>} A promise that resolves with the corresponding user record.
|
||||
*/
|
||||
BaseAuth.prototype.getUser = function (uid) {
|
||||
return this.authRequestHandler.getAccountInfoByUid(uid)
|
||||
.then(function (response) {
|
||||
// Returns the user record populated with server response.
|
||||
return new user_record_1.UserRecord(response.users[0]);
|
||||
});
|
||||
};
|
||||
/**
|
||||
* Looks up the user identified by the provided email and returns a promise that is
|
||||
* fulfilled with a user record for the given user if that user is found.
|
||||
*
|
||||
* @param {string} email The email of the user to look up.
|
||||
* @return {Promise<UserRecord>} A promise that resolves with the corresponding user record.
|
||||
*/
|
||||
BaseAuth.prototype.getUserByEmail = function (email) {
|
||||
return this.authRequestHandler.getAccountInfoByEmail(email)
|
||||
.then(function (response) {
|
||||
// Returns the user record populated with server response.
|
||||
return new user_record_1.UserRecord(response.users[0]);
|
||||
});
|
||||
};
|
||||
/**
|
||||
* Looks up the user identified by the provided phone number and returns a promise that is
|
||||
* fulfilled with a user record for the given user if that user is found.
|
||||
*
|
||||
* @param {string} phoneNumber The phone number of the user to look up.
|
||||
* @return {Promise<UserRecord>} A promise that resolves with the corresponding user record.
|
||||
*/
|
||||
BaseAuth.prototype.getUserByPhoneNumber = function (phoneNumber) {
|
||||
return this.authRequestHandler.getAccountInfoByPhoneNumber(phoneNumber)
|
||||
.then(function (response) {
|
||||
// Returns the user record populated with server response.
|
||||
return new user_record_1.UserRecord(response.users[0]);
|
||||
});
|
||||
};
|
||||
/**
|
||||
* Exports a batch of user accounts. Batch size is determined by the maxResults argument.
|
||||
* Starting point of the batch is determined by the pageToken argument.
|
||||
*
|
||||
* @param {number=} maxResults The page size, 1000 if undefined. This is also the maximum
|
||||
* allowed limit.
|
||||
* @param {string=} pageToken The next page token. If not specified, returns users starting
|
||||
* without any offset.
|
||||
* @return {Promise<{users: UserRecord[], pageToken?: string}>} A promise that resolves with
|
||||
* the current batch of downloaded users and the next page token. For the last page, an
|
||||
* empty list of users and no page token are returned.
|
||||
*/
|
||||
BaseAuth.prototype.listUsers = function (maxResults, pageToken) {
|
||||
return this.authRequestHandler.downloadAccount(maxResults, pageToken)
|
||||
.then(function (response) {
|
||||
// List of users to return.
|
||||
var users = [];
|
||||
// Convert each user response to a UserRecord.
|
||||
response.users.forEach(function (userResponse) {
|
||||
users.push(new user_record_1.UserRecord(userResponse));
|
||||
});
|
||||
// Return list of user records and the next page token if available.
|
||||
var result = {
|
||||
users: users,
|
||||
pageToken: response.nextPageToken,
|
||||
};
|
||||
// Delete result.pageToken if undefined.
|
||||
if (typeof result.pageToken === 'undefined') {
|
||||
delete result.pageToken;
|
||||
}
|
||||
return result;
|
||||
});
|
||||
};
|
||||
/**
|
||||
* Creates a new user with the properties provided.
|
||||
*
|
||||
* @param {CreateRequest} properties The properties to set on the new user record to be created.
|
||||
* @return {Promise<UserRecord>} A promise that resolves with the newly created user record.
|
||||
*/
|
||||
BaseAuth.prototype.createUser = function (properties) {
|
||||
var _this = this;
|
||||
return this.authRequestHandler.createNewAccount(properties)
|
||||
.then(function (uid) {
|
||||
// Return the corresponding user record.
|
||||
return _this.getUser(uid);
|
||||
})
|
||||
.catch(function (error) {
|
||||
if (error.code === 'auth/user-not-found') {
|
||||
// Something must have happened after creating the user and then retrieving it.
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'Unable to create the user record provided.');
|
||||
}
|
||||
throw error;
|
||||
});
|
||||
};
|
||||
/**
|
||||
* Deletes the user identified by the provided user id and returns a promise that is
|
||||
* fulfilled when the user is found and successfully deleted.
|
||||
*
|
||||
* @param {string} uid The uid of the user to delete.
|
||||
* @return {Promise<void>} A promise that resolves when the user is successfully deleted.
|
||||
*/
|
||||
BaseAuth.prototype.deleteUser = function (uid) {
|
||||
return this.authRequestHandler.deleteAccount(uid)
|
||||
.then(function (response) {
|
||||
// Return nothing on success.
|
||||
});
|
||||
};
|
||||
/**
|
||||
* Updates an existing user with the properties provided.
|
||||
*
|
||||
* @param {string} uid The uid identifier of the user to update.
|
||||
* @param {UpdateRequest} properties The properties to update on the existing user.
|
||||
* @return {Promise<UserRecord>} A promise that resolves with the modified user record.
|
||||
*/
|
||||
BaseAuth.prototype.updateUser = function (uid, properties) {
|
||||
var _this = this;
|
||||
return this.authRequestHandler.updateExistingAccount(uid, properties)
|
||||
.then(function (existingUid) {
|
||||
// Return the corresponding user record.
|
||||
return _this.getUser(existingUid);
|
||||
});
|
||||
};
|
||||
/**
|
||||
* Sets additional developer claims on an existing user identified by the provided UID.
|
||||
*
|
||||
* @param {string} uid The user to edit.
|
||||
* @param {object} customUserClaims The developer claims to set.
|
||||
* @return {Promise<void>} A promise that resolves when the operation completes
|
||||
* successfully.
|
||||
*/
|
||||
BaseAuth.prototype.setCustomUserClaims = function (uid, customUserClaims) {
|
||||
return this.authRequestHandler.setCustomUserClaims(uid, customUserClaims)
|
||||
.then(function (existingUid) {
|
||||
// Return nothing on success.
|
||||
});
|
||||
};
|
||||
/**
|
||||
* Revokes all refresh tokens for the specified user identified by the provided UID.
|
||||
* In addition to revoking all refresh tokens for a user, all ID tokens issued before
|
||||
* revocation will also be revoked on the Auth backend. Any request with an ID token
|
||||
* generated before revocation will be rejected with a token expired error.
|
||||
*
|
||||
* @param {string} uid The user whose tokens are to be revoked.
|
||||
* @return {Promise<void>} A promise that resolves when the operation completes
|
||||
* successfully.
|
||||
*/
|
||||
BaseAuth.prototype.revokeRefreshTokens = function (uid) {
|
||||
return this.authRequestHandler.revokeRefreshTokens(uid)
|
||||
.then(function (existingUid) {
|
||||
// Return nothing on success.
|
||||
});
|
||||
};
|
||||
/**
|
||||
* Imports the list of users provided to Firebase Auth. This is useful when
|
||||
* migrating from an external authentication system without having to use the Firebase CLI SDK.
|
||||
* At most, 1000 users are allowed to be imported one at a time.
|
||||
* When importing a list of password users, UserImportOptions are required to be specified.
|
||||
*
|
||||
* @param {UserImportRecord[]} users The list of user records to import to Firebase Auth.
|
||||
* @param {UserImportOptions=} options The user import options, required when the users provided
|
||||
* include password credentials.
|
||||
* @return {Promise<UserImportResult>} A promise that resolves when the operation completes
|
||||
* with the result of the import. This includes the number of successful imports, the number
|
||||
* of failed uploads and their corresponding errors.
|
||||
*/
|
||||
BaseAuth.prototype.importUsers = function (users, options) {
|
||||
return this.authRequestHandler.uploadAccount(users, options);
|
||||
};
|
||||
/**
|
||||
* Creates a new Firebase session cookie with the specified options that can be used for
|
||||
* session management (set as a server side session cookie with custom cookie policy).
|
||||
* The session cookie JWT will have the same payload claims as the provided ID token.
|
||||
*
|
||||
* @param {string} idToken The Firebase ID token to exchange for a session cookie.
|
||||
* @param {SessionCookieOptions} sessionCookieOptions The session cookie options which includes
|
||||
* custom session duration.
|
||||
*
|
||||
* @return {Promise<string>} A promise that resolves on success with the created session cookie.
|
||||
*/
|
||||
BaseAuth.prototype.createSessionCookie = function (idToken, sessionCookieOptions) {
|
||||
// Return rejected promise if expiresIn is not available.
|
||||
if (!validator.isNonNullObject(sessionCookieOptions) ||
|
||||
!validator.isNumber(sessionCookieOptions.expiresIn)) {
|
||||
return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_SESSION_COOKIE_DURATION));
|
||||
}
|
||||
return this.authRequestHandler.createSessionCookie(idToken, sessionCookieOptions.expiresIn);
|
||||
};
|
||||
/**
|
||||
* Verifies a Firebase session cookie. Returns a Promise with the tokens claims. Rejects
|
||||
* the promise if the token could not be verified. If checkRevoked is set to true,
|
||||
* verifies if the session corresponding to the session cookie was revoked. If the corresponding
|
||||
* user's session was invalidated, an auth/session-cookie-revoked error is thrown. If not
|
||||
* specified the check is not performed.
|
||||
*
|
||||
* @param {string} sessionCookie The session cookie to verify.
|
||||
* @param {boolean=} checkRevoked Whether to check if the session cookie is revoked.
|
||||
* @return {Promise<DecodedIdToken>} A Promise that will be fulfilled after a successful
|
||||
* verification.
|
||||
*/
|
||||
BaseAuth.prototype.verifySessionCookie = function (sessionCookie, checkRevoked) {
|
||||
var _this = this;
|
||||
if (checkRevoked === void 0) { checkRevoked = false; }
|
||||
return this.sessionCookieVerifier.verifyJWT(sessionCookie)
|
||||
.then(function (decodedIdToken) {
|
||||
// Whether to check if the token was revoked.
|
||||
if (!checkRevoked) {
|
||||
return decodedIdToken;
|
||||
}
|
||||
return _this.verifyDecodedJWTNotRevoked(decodedIdToken, error_1.AuthClientErrorCode.SESSION_COOKIE_REVOKED);
|
||||
});
|
||||
};
|
||||
/**
|
||||
* Generates the out of band email action link for password reset flows for the
|
||||
* email specified using the action code settings provided.
|
||||
* Returns a promise that resolves with the generated link.
|
||||
*
|
||||
* @param {string} email The email of the user whose password is to be reset.
|
||||
* @param {ActionCodeSettings=} actionCodeSettings The optional action code setings which defines whether
|
||||
* the link is to be handled by a mobile app and the additional state information to be passed in the
|
||||
* deep link, etc.
|
||||
* @return {Promise<string>} A promise that resolves with the password reset link.
|
||||
*/
|
||||
BaseAuth.prototype.generatePasswordResetLink = function (email, actionCodeSettings) {
|
||||
return this.authRequestHandler.getEmailActionLink('PASSWORD_RESET', email, actionCodeSettings);
|
||||
};
|
||||
/**
|
||||
* Generates the out of band email action link for email verification flows for the
|
||||
* email specified using the action code settings provided.
|
||||
* Returns a promise that resolves with the generated link.
|
||||
*
|
||||
* @param {string} email The email of the user to be verified.
|
||||
* @param {ActionCodeSettings=} actionCodeSettings The optional action code setings which defines whether
|
||||
* the link is to be handled by a mobile app and the additional state information to be passed in the
|
||||
* deep link, etc.
|
||||
* @return {Promise<string>} A promise that resolves with the email verification link.
|
||||
*/
|
||||
BaseAuth.prototype.generateEmailVerificationLink = function (email, actionCodeSettings) {
|
||||
return this.authRequestHandler.getEmailActionLink('VERIFY_EMAIL', email, actionCodeSettings);
|
||||
};
|
||||
/**
|
||||
* Generates the out of band email action link for email link sign-in flows for the
|
||||
* email specified using the action code settings provided.
|
||||
* Returns a promise that resolves with the generated link.
|
||||
*
|
||||
* @param {string} email The email of the user signing in.
|
||||
* @param {ActionCodeSettings} actionCodeSettings The required action code setings which defines whether
|
||||
* the link is to be handled by a mobile app and the additional state information to be passed in the
|
||||
* deep link, etc.
|
||||
* @return {Promise<string>} A promise that resolves with the email sign-in link.
|
||||
*/
|
||||
BaseAuth.prototype.generateSignInWithEmailLink = function (email, actionCodeSettings) {
|
||||
return this.authRequestHandler.getEmailActionLink('EMAIL_SIGNIN', email, actionCodeSettings);
|
||||
};
|
||||
/**
|
||||
* Returns the list of existing provider configuation matching the filter provided.
|
||||
* At most, 100 provider configs are allowed to be imported at a time.
|
||||
*
|
||||
* @param {AuthProviderConfigFilter} options The provider config filter to apply.
|
||||
* @return {Promise<ListProviderConfigResults>} A promise that resolves with the list of provider configs
|
||||
* meeting the filter requirements.
|
||||
*/
|
||||
BaseAuth.prototype.listProviderConfigs = function (options) {
|
||||
var processResponse = function (response, providerConfigs) {
|
||||
// Return list of provider configuration and the next page token if available.
|
||||
var result = {
|
||||
providerConfigs: providerConfigs,
|
||||
};
|
||||
// Delete result.pageToken if undefined.
|
||||
if (response.hasOwnProperty('nextPageToken')) {
|
||||
result.pageToken = response.nextPageToken;
|
||||
}
|
||||
return result;
|
||||
};
|
||||
if (options && options.type === 'oidc') {
|
||||
return this.authRequestHandler.listOAuthIdpConfigs(options.maxResults, options.pageToken)
|
||||
.then(function (response) {
|
||||
// List of provider configurations to return.
|
||||
var providerConfigs = [];
|
||||
// Convert each provider config response to a OIDCConfig.
|
||||
response.oauthIdpConfigs.forEach(function (configResponse) {
|
||||
providerConfigs.push(new auth_config_1.OIDCConfig(configResponse));
|
||||
});
|
||||
// Return list of provider configuration and the next page token if available.
|
||||
return processResponse(response, providerConfigs);
|
||||
});
|
||||
}
|
||||
else if (options && options.type === 'saml') {
|
||||
return this.authRequestHandler.listInboundSamlConfigs(options.maxResults, options.pageToken)
|
||||
.then(function (response) {
|
||||
// List of provider configurations to return.
|
||||
var providerConfigs = [];
|
||||
// Convert each provider config response to a SAMLConfig.
|
||||
response.inboundSamlConfigs.forEach(function (configResponse) {
|
||||
providerConfigs.push(new auth_config_1.SAMLConfig(configResponse));
|
||||
});
|
||||
// Return list of provider configuration and the next page token if available.
|
||||
return processResponse(response, providerConfigs);
|
||||
});
|
||||
}
|
||||
return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, "\"AuthProviderConfigFilter.type\" must be either \"saml' or \"oidc\""));
|
||||
};
|
||||
/**
|
||||
* Looks up an Auth provider configuration by ID.
|
||||
* Returns a promise that resolves with the provider configuration corresponding to the provider ID specified.
|
||||
*
|
||||
* @param {string} providerId The provider ID corresponding to the provider config to return.
|
||||
* @return {Promise<AuthProviderConfig>}
|
||||
*/
|
||||
BaseAuth.prototype.getProviderConfig = function (providerId) {
|
||||
if (auth_config_1.OIDCConfig.isProviderId(providerId)) {
|
||||
return this.authRequestHandler.getOAuthIdpConfig(providerId)
|
||||
.then(function (response) {
|
||||
return new auth_config_1.OIDCConfig(response);
|
||||
});
|
||||
}
|
||||
else if (auth_config_1.SAMLConfig.isProviderId(providerId)) {
|
||||
return this.authRequestHandler.getInboundSamlConfig(providerId)
|
||||
.then(function (response) {
|
||||
return new auth_config_1.SAMLConfig(response);
|
||||
});
|
||||
}
|
||||
return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PROVIDER_ID));
|
||||
};
|
||||
/**
|
||||
* Deletes the provider configuration corresponding to the provider ID passed.
|
||||
*
|
||||
* @param {string} providerId The provider ID corresponding to the provider config to delete.
|
||||
* @return {Promise<void>} A promise that resolves on completion.
|
||||
*/
|
||||
BaseAuth.prototype.deleteProviderConfig = function (providerId) {
|
||||
if (auth_config_1.OIDCConfig.isProviderId(providerId)) {
|
||||
return this.authRequestHandler.deleteOAuthIdpConfig(providerId);
|
||||
}
|
||||
else if (auth_config_1.SAMLConfig.isProviderId(providerId)) {
|
||||
return this.authRequestHandler.deleteInboundSamlConfig(providerId);
|
||||
}
|
||||
return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PROVIDER_ID));
|
||||
};
|
||||
/**
|
||||
* Returns a promise that resolves with the updated AuthProviderConfig when the provider configuration corresponding
|
||||
* to the provider ID specified is updated with the specified configuration.
|
||||
*
|
||||
* @param {string} providerId The provider ID corresponding to the provider config to update.
|
||||
* @param {UpdateAuthProviderRequest} updatedConfig The updated configuration.
|
||||
* @return {Promise<AuthProviderConfig>} A promise that resolves with the updated provider configuration.
|
||||
*/
|
||||
BaseAuth.prototype.updateProviderConfig = function (providerId, updatedConfig) {
|
||||
if (!validator.isNonNullObject(updatedConfig)) {
|
||||
return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, 'Request is missing "UpdateAuthProviderRequest" configuration.'));
|
||||
}
|
||||
if (auth_config_1.OIDCConfig.isProviderId(providerId)) {
|
||||
return this.authRequestHandler.updateOAuthIdpConfig(providerId, updatedConfig)
|
||||
.then(function (response) {
|
||||
return new auth_config_1.OIDCConfig(response);
|
||||
});
|
||||
}
|
||||
else if (auth_config_1.SAMLConfig.isProviderId(providerId)) {
|
||||
return this.authRequestHandler.updateInboundSamlConfig(providerId, updatedConfig)
|
||||
.then(function (response) {
|
||||
return new auth_config_1.SAMLConfig(response);
|
||||
});
|
||||
}
|
||||
return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PROVIDER_ID));
|
||||
};
|
||||
/**
|
||||
* Returns a promise that resolves with the newly created AuthProviderConfig when the new provider configuration is
|
||||
* created.
|
||||
* @param {AuthProviderConfig} config The provider configuration to create.
|
||||
* @return {Promise<AuthProviderConfig>} A promise that resolves with the created provider configuration.
|
||||
*/
|
||||
BaseAuth.prototype.createProviderConfig = function (config) {
|
||||
if (!validator.isNonNullObject(config)) {
|
||||
return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CONFIG, 'Request is missing "AuthProviderConfig" configuration.'));
|
||||
}
|
||||
if (auth_config_1.OIDCConfig.isProviderId(config.providerId)) {
|
||||
return this.authRequestHandler.createOAuthIdpConfig(config)
|
||||
.then(function (response) {
|
||||
return new auth_config_1.OIDCConfig(response);
|
||||
});
|
||||
}
|
||||
else if (auth_config_1.SAMLConfig.isProviderId(config.providerId)) {
|
||||
return this.authRequestHandler.createInboundSamlConfig(config)
|
||||
.then(function (response) {
|
||||
return new auth_config_1.SAMLConfig(response);
|
||||
});
|
||||
}
|
||||
return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PROVIDER_ID));
|
||||
};
|
||||
/**
|
||||
* Verifies the decoded Firebase issued JWT is not revoked. Returns a promise that resolves
|
||||
* with the decoded claims on success. Rejects the promise with revocation error if revoked.
|
||||
*
|
||||
* @param {DecodedIdToken} decodedIdToken The JWT's decoded claims.
|
||||
* @param {ErrorInfo} revocationErrorInfo The revocation error info to throw on revocation
|
||||
* detection.
|
||||
* @return {Promise<DecodedIdToken>} A Promise that will be fulfilled after a successful
|
||||
* verification.
|
||||
*/
|
||||
BaseAuth.prototype.verifyDecodedJWTNotRevoked = function (decodedIdToken, revocationErrorInfo) {
|
||||
// Get tokens valid after time for the corresponding user.
|
||||
return this.getUser(decodedIdToken.sub)
|
||||
.then(function (user) {
|
||||
// If no tokens valid after time available, token is not revoked.
|
||||
if (user.tokensValidAfterTime) {
|
||||
// Get the ID token authentication time and convert to milliseconds UTC.
|
||||
var authTimeUtc = decodedIdToken.auth_time * 1000;
|
||||
// Get user tokens valid after time in milliseconds UTC.
|
||||
var validSinceUtc = new Date(user.tokensValidAfterTime).getTime();
|
||||
// Check if authentication time is older than valid since time.
|
||||
if (authTimeUtc < validSinceUtc) {
|
||||
throw new error_1.FirebaseAuthError(revocationErrorInfo);
|
||||
}
|
||||
}
|
||||
// All checks above passed. Return the decoded token.
|
||||
return decodedIdToken;
|
||||
});
|
||||
};
|
||||
return BaseAuth;
|
||||
}());
|
||||
exports.BaseAuth = BaseAuth;
|
||||
/**
|
||||
* The tenant aware Auth class.
|
||||
*/
|
||||
var TenantAwareAuth = /** @class */ (function (_super) {
|
||||
__extends(TenantAwareAuth, _super);
|
||||
/**
|
||||
* The TenantAwareAuth class constructor.
|
||||
*
|
||||
* @param {object} app The app that created this tenant.
|
||||
* @param tenantId The corresponding tenant ID.
|
||||
* @constructor
|
||||
*/
|
||||
function TenantAwareAuth(app, tenantId) {
|
||||
var _this = this;
|
||||
var cryptoSigner = token_generator_1.cryptoSignerFromApp(app);
|
||||
var tokenGenerator = new token_generator_1.FirebaseTokenGenerator(cryptoSigner, tenantId);
|
||||
_this = _super.call(this, app, new auth_api_request_1.TenantAwareAuthRequestHandler(app, tenantId), tokenGenerator) || this;
|
||||
utils.addReadonlyGetter(_this, 'tenantId', tenantId);
|
||||
return _this;
|
||||
}
|
||||
/**
|
||||
* Verifies a JWT auth token. Returns a Promise with the tokens claims. Rejects
|
||||
* the promise if the token could not be verified. If checkRevoked is set to true,
|
||||
* verifies if the session corresponding to the ID token was revoked. If the corresponding
|
||||
* user's session was invalidated, an auth/id-token-revoked error is thrown. If not specified
|
||||
* the check is not applied.
|
||||
*
|
||||
* @param {string} idToken The JWT to verify.
|
||||
* @param {boolean=} checkRevoked Whether to check if the ID token is revoked.
|
||||
* @return {Promise<DecodedIdToken>} A Promise that will be fulfilled after a successful
|
||||
* verification.
|
||||
*/
|
||||
TenantAwareAuth.prototype.verifyIdToken = function (idToken, checkRevoked) {
|
||||
var _this = this;
|
||||
if (checkRevoked === void 0) { checkRevoked = false; }
|
||||
return _super.prototype.verifyIdToken.call(this, idToken, checkRevoked)
|
||||
.then(function (decodedClaims) {
|
||||
// Validate tenant ID.
|
||||
if (decodedClaims.firebase.tenant !== _this.tenantId) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.MISMATCHING_TENANT_ID);
|
||||
}
|
||||
return decodedClaims;
|
||||
});
|
||||
};
|
||||
/**
|
||||
* Creates a new Firebase session cookie with the specified options that can be used for
|
||||
* session management (set as a server side session cookie with custom cookie policy).
|
||||
* The session cookie JWT will have the same payload claims as the provided ID token.
|
||||
*
|
||||
* @param {string} idToken The Firebase ID token to exchange for a session cookie.
|
||||
* @param {SessionCookieOptions} sessionCookieOptions The session cookie options which includes
|
||||
* custom session duration.
|
||||
*
|
||||
* @return {Promise<string>} A promise that resolves on success with the created session cookie.
|
||||
*/
|
||||
TenantAwareAuth.prototype.createSessionCookie = function (idToken, sessionCookieOptions) {
|
||||
var _this = this;
|
||||
// Validate arguments before processing.
|
||||
if (!validator.isNonEmptyString(idToken)) {
|
||||
return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ID_TOKEN));
|
||||
}
|
||||
if (!validator.isNonNullObject(sessionCookieOptions) ||
|
||||
!validator.isNumber(sessionCookieOptions.expiresIn)) {
|
||||
return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_SESSION_COOKIE_DURATION));
|
||||
}
|
||||
// This will verify the ID token and then match the tenant ID before creating the session cookie.
|
||||
return this.verifyIdToken(idToken)
|
||||
.then(function (decodedIdTokenClaims) {
|
||||
return _super.prototype.createSessionCookie.call(_this, idToken, sessionCookieOptions);
|
||||
});
|
||||
};
|
||||
/**
|
||||
* Verifies a Firebase session cookie. Returns a Promise with the tokens claims. Rejects
|
||||
* the promise if the token could not be verified. If checkRevoked is set to true,
|
||||
* verifies if the session corresponding to the session cookie was revoked. If the corresponding
|
||||
* user's session was invalidated, an auth/session-cookie-revoked error is thrown. If not
|
||||
* specified the check is not performed.
|
||||
*
|
||||
* @param {string} sessionCookie The session cookie to verify.
|
||||
* @param {boolean=} checkRevoked Whether to check if the session cookie is revoked.
|
||||
* @return {Promise<DecodedIdToken>} A Promise that will be fulfilled after a successful
|
||||
* verification.
|
||||
*/
|
||||
TenantAwareAuth.prototype.verifySessionCookie = function (sessionCookie, checkRevoked) {
|
||||
var _this = this;
|
||||
if (checkRevoked === void 0) { checkRevoked = false; }
|
||||
return _super.prototype.verifySessionCookie.call(this, sessionCookie, checkRevoked)
|
||||
.then(function (decodedClaims) {
|
||||
if (decodedClaims.firebase.tenant !== _this.tenantId) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.MISMATCHING_TENANT_ID);
|
||||
}
|
||||
return decodedClaims;
|
||||
});
|
||||
};
|
||||
return TenantAwareAuth;
|
||||
}(BaseAuth));
|
||||
exports.TenantAwareAuth = TenantAwareAuth;
|
||||
/**
|
||||
* Auth service bound to the provided app.
|
||||
* An Auth instance can have multiple tenants.
|
||||
*/
|
||||
var Auth = /** @class */ (function (_super) {
|
||||
__extends(Auth, _super);
|
||||
/**
|
||||
* @param {object} app The app for this Auth service.
|
||||
* @constructor
|
||||
*/
|
||||
function Auth(app) {
|
||||
var _this = _super.call(this, app, new auth_api_request_1.AuthRequestHandler(app)) || this;
|
||||
_this.INTERNAL = new AuthInternals();
|
||||
_this.app_ = app;
|
||||
_this.tenantManager_ = new tenant_manager_1.TenantManager(app);
|
||||
return _this;
|
||||
}
|
||||
Object.defineProperty(Auth.prototype, "app", {
|
||||
/**
|
||||
* Returns the app associated with this Auth instance.
|
||||
*
|
||||
* @return {FirebaseApp} The app associated with this Auth instance.
|
||||
*/
|
||||
get: function () {
|
||||
return this.app_;
|
||||
},
|
||||
enumerable: true,
|
||||
configurable: true
|
||||
});
|
||||
/** @return The current Auth instance's tenant manager. */
|
||||
Auth.prototype.tenantManager = function () {
|
||||
return this.tenantManager_;
|
||||
};
|
||||
return Auth;
|
||||
}(BaseAuth));
|
||||
exports.Auth = Auth;
|
389
node_modules/firebase-admin/lib/auth/credential.js
generated
vendored
Normal file
389
node_modules/firebase-admin/lib/auth/credential.js
generated
vendored
Normal file
@ -0,0 +1,389 @@
|
||||
/*! firebase-admin v8.9.2 */
|
||||
"use strict";
|
||||
/*!
|
||||
* Copyright 2017 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
// Use untyped import syntax for Node built-ins
|
||||
var fs = require("fs");
|
||||
var os = require("os");
|
||||
var path = require("path");
|
||||
var error_1 = require("../utils/error");
|
||||
var api_request_1 = require("../utils/api-request");
|
||||
var util = require("../utils/validator");
|
||||
var GOOGLE_TOKEN_AUDIENCE = 'https://accounts.google.com/o/oauth2/token';
|
||||
var GOOGLE_AUTH_TOKEN_HOST = 'accounts.google.com';
|
||||
var GOOGLE_AUTH_TOKEN_PATH = '/o/oauth2/token';
|
||||
// NOTE: the Google Metadata Service uses HTTP over a vlan
|
||||
var GOOGLE_METADATA_SERVICE_HOST = 'metadata.google.internal';
|
||||
var GOOGLE_METADATA_SERVICE_TOKEN_PATH = '/computeMetadata/v1/instance/service-accounts/default/token';
|
||||
var GOOGLE_METADATA_SERVICE_PROJECT_ID_PATH = '/computeMetadata/v1/project/project-id';
|
||||
var configDir = (function () {
|
||||
// Windows has a dedicated low-rights location for apps at ~/Application Data
|
||||
var sys = os.platform();
|
||||
if (sys && sys.length >= 3 && sys.substring(0, 3).toLowerCase() === 'win') {
|
||||
return process.env.APPDATA;
|
||||
}
|
||||
// On *nix the gcloud cli creates a . dir.
|
||||
return process.env.HOME && path.resolve(process.env.HOME, '.config');
|
||||
})();
|
||||
var GCLOUD_CREDENTIAL_SUFFIX = 'gcloud/application_default_credentials.json';
|
||||
var GCLOUD_CREDENTIAL_PATH = configDir && path.resolve(configDir, GCLOUD_CREDENTIAL_SUFFIX);
|
||||
var REFRESH_TOKEN_HOST = 'www.googleapis.com';
|
||||
var REFRESH_TOKEN_PATH = '/oauth2/v4/token';
|
||||
var ONE_HOUR_IN_SECONDS = 60 * 60;
|
||||
var JWT_ALGORITHM = 'RS256';
|
||||
/**
|
||||
* Implementation of Credential that uses a service account.
|
||||
*/
|
||||
var ServiceAccountCredential = /** @class */ (function () {
|
||||
/**
|
||||
* Creates a new ServiceAccountCredential from the given parameters.
|
||||
*
|
||||
* @param serviceAccountPathOrObject Service account json object or path to a service account json file.
|
||||
* @param httpAgent Optional http.Agent to use when calling the remote token server.
|
||||
* @param implicit An optinal boolean indicating whether this credential was implicitly discovered from the
|
||||
* environment, as opposed to being explicitly specified by the developer.
|
||||
*
|
||||
* @constructor
|
||||
*/
|
||||
function ServiceAccountCredential(serviceAccountPathOrObject, httpAgent, implicit) {
|
||||
if (implicit === void 0) { implicit = false; }
|
||||
this.httpAgent = httpAgent;
|
||||
this.implicit = implicit;
|
||||
var serviceAccount = (typeof serviceAccountPathOrObject === 'string') ?
|
||||
ServiceAccount.fromPath(serviceAccountPathOrObject)
|
||||
: new ServiceAccount(serviceAccountPathOrObject);
|
||||
this.projectId = serviceAccount.projectId;
|
||||
this.privateKey = serviceAccount.privateKey;
|
||||
this.clientEmail = serviceAccount.clientEmail;
|
||||
this.httpClient = new api_request_1.HttpClient();
|
||||
}
|
||||
ServiceAccountCredential.prototype.getAccessToken = function () {
|
||||
var token = this.createAuthJwt_();
|
||||
var postData = 'grant_type=urn%3Aietf%3Aparams%3Aoauth%3A' +
|
||||
'grant-type%3Ajwt-bearer&assertion=' + token;
|
||||
var request = {
|
||||
method: 'POST',
|
||||
url: "https://" + GOOGLE_AUTH_TOKEN_HOST + GOOGLE_AUTH_TOKEN_PATH,
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
data: postData,
|
||||
httpAgent: this.httpAgent,
|
||||
};
|
||||
return requestAccessToken(this.httpClient, request);
|
||||
};
|
||||
ServiceAccountCredential.prototype.createAuthJwt_ = function () {
|
||||
var claims = {
|
||||
scope: [
|
||||
'https://www.googleapis.com/auth/cloud-platform',
|
||||
'https://www.googleapis.com/auth/firebase.database',
|
||||
'https://www.googleapis.com/auth/firebase.messaging',
|
||||
'https://www.googleapis.com/auth/identitytoolkit',
|
||||
'https://www.googleapis.com/auth/userinfo.email',
|
||||
].join(' '),
|
||||
};
|
||||
var jwt = require('jsonwebtoken');
|
||||
// This method is actually synchronous so we can capture and return the buffer.
|
||||
return jwt.sign(claims, this.privateKey, {
|
||||
audience: GOOGLE_TOKEN_AUDIENCE,
|
||||
expiresIn: ONE_HOUR_IN_SECONDS,
|
||||
issuer: this.clientEmail,
|
||||
algorithm: JWT_ALGORITHM,
|
||||
});
|
||||
};
|
||||
return ServiceAccountCredential;
|
||||
}());
|
||||
exports.ServiceAccountCredential = ServiceAccountCredential;
|
||||
/**
|
||||
* A struct containing the properties necessary to use service account JSON credentials.
|
||||
*/
|
||||
var ServiceAccount = /** @class */ (function () {
|
||||
function ServiceAccount(json) {
|
||||
if (!util.isNonNullObject(json)) {
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, 'Service account must be an object.');
|
||||
}
|
||||
copyAttr(this, json, 'projectId', 'project_id');
|
||||
copyAttr(this, json, 'privateKey', 'private_key');
|
||||
copyAttr(this, json, 'clientEmail', 'client_email');
|
||||
var errorMessage;
|
||||
if (!util.isNonEmptyString(this.projectId)) {
|
||||
errorMessage = 'Service account object must contain a string "project_id" property.';
|
||||
}
|
||||
else if (!util.isNonEmptyString(this.privateKey)) {
|
||||
errorMessage = 'Service account object must contain a string "private_key" property.';
|
||||
}
|
||||
else if (!util.isNonEmptyString(this.clientEmail)) {
|
||||
errorMessage = 'Service account object must contain a string "client_email" property.';
|
||||
}
|
||||
if (typeof errorMessage !== 'undefined') {
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, errorMessage);
|
||||
}
|
||||
var forge = require('node-forge');
|
||||
try {
|
||||
forge.pki.privateKeyFromPem(this.privateKey);
|
||||
}
|
||||
catch (error) {
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, 'Failed to parse private key: ' + error);
|
||||
}
|
||||
}
|
||||
ServiceAccount.fromPath = function (filePath) {
|
||||
try {
|
||||
return new ServiceAccount(JSON.parse(fs.readFileSync(filePath, 'utf8')));
|
||||
}
|
||||
catch (error) {
|
||||
// Throw a nicely formed error message if the file contents cannot be parsed
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, 'Failed to parse service account json file: ' + error);
|
||||
}
|
||||
};
|
||||
return ServiceAccount;
|
||||
}());
|
||||
/**
|
||||
* Implementation of Credential that gets access tokens from the metadata service available
|
||||
* in the Google Cloud Platform. This authenticates the process as the default service account
|
||||
* of an App Engine instance or Google Compute Engine machine.
|
||||
*/
|
||||
var ComputeEngineCredential = /** @class */ (function () {
|
||||
function ComputeEngineCredential(httpAgent) {
|
||||
this.httpClient = new api_request_1.HttpClient();
|
||||
this.httpAgent = httpAgent;
|
||||
}
|
||||
ComputeEngineCredential.prototype.getAccessToken = function () {
|
||||
var request = this.buildRequest(GOOGLE_METADATA_SERVICE_TOKEN_PATH);
|
||||
return requestAccessToken(this.httpClient, request);
|
||||
};
|
||||
ComputeEngineCredential.prototype.getProjectId = function () {
|
||||
var _this = this;
|
||||
if (this.projectId) {
|
||||
return Promise.resolve(this.projectId);
|
||||
}
|
||||
var request = this.buildRequest(GOOGLE_METADATA_SERVICE_PROJECT_ID_PATH);
|
||||
return this.httpClient.send(request)
|
||||
.then(function (resp) {
|
||||
_this.projectId = resp.text;
|
||||
return _this.projectId;
|
||||
})
|
||||
.catch(function (err) {
|
||||
var detail = (err instanceof api_request_1.HttpError) ? getDetailFromResponse(err.response) : err.message;
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, "Failed to determine project ID: " + detail);
|
||||
});
|
||||
};
|
||||
ComputeEngineCredential.prototype.buildRequest = function (urlPath) {
|
||||
return {
|
||||
method: 'GET',
|
||||
url: "http://" + GOOGLE_METADATA_SERVICE_HOST + urlPath,
|
||||
headers: {
|
||||
'Metadata-Flavor': 'Google',
|
||||
},
|
||||
httpAgent: this.httpAgent,
|
||||
};
|
||||
};
|
||||
return ComputeEngineCredential;
|
||||
}());
|
||||
exports.ComputeEngineCredential = ComputeEngineCredential;
|
||||
/**
|
||||
* Implementation of Credential that gets access tokens from refresh tokens.
|
||||
*/
|
||||
var RefreshTokenCredential = /** @class */ (function () {
|
||||
/**
|
||||
* Creates a new RefreshTokenCredential from the given parameters.
|
||||
*
|
||||
* @param refreshTokenPathOrObject Refresh token json object or path to a refresh token (user credentials) json file.
|
||||
* @param httpAgent Optional http.Agent to use when calling the remote token server.
|
||||
* @param implicit An optinal boolean indicating whether this credential was implicitly discovered from the
|
||||
* environment, as opposed to being explicitly specified by the developer.
|
||||
*
|
||||
* @constructor
|
||||
*/
|
||||
function RefreshTokenCredential(refreshTokenPathOrObject, httpAgent, implicit) {
|
||||
if (implicit === void 0) { implicit = false; }
|
||||
this.httpAgent = httpAgent;
|
||||
this.implicit = implicit;
|
||||
this.refreshToken = (typeof refreshTokenPathOrObject === 'string') ?
|
||||
RefreshToken.fromPath(refreshTokenPathOrObject)
|
||||
: new RefreshToken(refreshTokenPathOrObject);
|
||||
this.httpClient = new api_request_1.HttpClient();
|
||||
}
|
||||
RefreshTokenCredential.prototype.getAccessToken = function () {
|
||||
var postData = 'client_id=' + this.refreshToken.clientId + '&' +
|
||||
'client_secret=' + this.refreshToken.clientSecret + '&' +
|
||||
'refresh_token=' + this.refreshToken.refreshToken + '&' +
|
||||
'grant_type=refresh_token';
|
||||
var request = {
|
||||
method: 'POST',
|
||||
url: "https://" + REFRESH_TOKEN_HOST + REFRESH_TOKEN_PATH,
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
data: postData,
|
||||
httpAgent: this.httpAgent,
|
||||
};
|
||||
return requestAccessToken(this.httpClient, request);
|
||||
};
|
||||
return RefreshTokenCredential;
|
||||
}());
|
||||
exports.RefreshTokenCredential = RefreshTokenCredential;
|
||||
var RefreshToken = /** @class */ (function () {
|
||||
function RefreshToken(json) {
|
||||
copyAttr(this, json, 'clientId', 'client_id');
|
||||
copyAttr(this, json, 'clientSecret', 'client_secret');
|
||||
copyAttr(this, json, 'refreshToken', 'refresh_token');
|
||||
copyAttr(this, json, 'type', 'type');
|
||||
var errorMessage;
|
||||
if (!util.isNonEmptyString(this.clientId)) {
|
||||
errorMessage = 'Refresh token must contain a "client_id" property.';
|
||||
}
|
||||
else if (!util.isNonEmptyString(this.clientSecret)) {
|
||||
errorMessage = 'Refresh token must contain a "client_secret" property.';
|
||||
}
|
||||
else if (!util.isNonEmptyString(this.refreshToken)) {
|
||||
errorMessage = 'Refresh token must contain a "refresh_token" property.';
|
||||
}
|
||||
else if (!util.isNonEmptyString(this.type)) {
|
||||
errorMessage = 'Refresh token must contain a "type" property.';
|
||||
}
|
||||
if (typeof errorMessage !== 'undefined') {
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, errorMessage);
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Tries to load a RefreshToken from a path. Throws if the path doesn't exist or the
|
||||
* data at the path is invalid.
|
||||
*/
|
||||
RefreshToken.fromPath = function (filePath) {
|
||||
try {
|
||||
return new RefreshToken(JSON.parse(fs.readFileSync(filePath, 'utf8')));
|
||||
}
|
||||
catch (error) {
|
||||
// Throw a nicely formed error message if the file contents cannot be parsed
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, 'Failed to parse refresh token file: ' + error);
|
||||
}
|
||||
};
|
||||
return RefreshToken;
|
||||
}());
|
||||
function getApplicationDefault(httpAgent) {
|
||||
if (process.env.GOOGLE_APPLICATION_CREDENTIALS) {
|
||||
return credentialFromFile(process.env.GOOGLE_APPLICATION_CREDENTIALS, httpAgent);
|
||||
}
|
||||
// It is OK to not have this file. If it is present, it must be valid.
|
||||
if (GCLOUD_CREDENTIAL_PATH) {
|
||||
var refreshToken = readCredentialFile(GCLOUD_CREDENTIAL_PATH, true);
|
||||
if (refreshToken) {
|
||||
return new RefreshTokenCredential(refreshToken, httpAgent, true);
|
||||
}
|
||||
}
|
||||
return new ComputeEngineCredential(httpAgent);
|
||||
}
|
||||
exports.getApplicationDefault = getApplicationDefault;
|
||||
/**
|
||||
* Checks if the given credential was loaded via the application default credentials mechanism. This
|
||||
* includes all ComputeEngineCredential instances, and the ServiceAccountCredential and RefreshTokenCredential
|
||||
* instances that were loaded from well-known files or environment variables, rather than being explicitly
|
||||
* instantiated.
|
||||
*
|
||||
* @param credential The credential instance to check.
|
||||
*/
|
||||
function isApplicationDefault(credential) {
|
||||
return credential instanceof ComputeEngineCredential ||
|
||||
(credential instanceof ServiceAccountCredential && credential.implicit) ||
|
||||
(credential instanceof RefreshTokenCredential && credential.implicit);
|
||||
}
|
||||
exports.isApplicationDefault = isApplicationDefault;
|
||||
/**
|
||||
* Copies the specified property from one object to another.
|
||||
*
|
||||
* If no property exists by the given "key", looks for a property identified by "alt", and copies it instead.
|
||||
* This can be used to implement behaviors such as "copy property myKey or my_key".
|
||||
*
|
||||
* @param to Target object to copy the property into.
|
||||
* @param from Source object to copy the property from.
|
||||
* @param key Name of the property to copy.
|
||||
* @param alt Alternative name of the property to copy.
|
||||
*/
|
||||
function copyAttr(to, from, key, alt) {
|
||||
var tmp = from[key] || from[alt];
|
||||
if (typeof tmp !== 'undefined') {
|
||||
to[key] = tmp;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Obtain a new OAuth2 token by making a remote service call.
|
||||
*/
|
||||
function requestAccessToken(client, request) {
|
||||
return client.send(request).then(function (resp) {
|
||||
var json = resp.data;
|
||||
if (!json.access_token || !json.expires_in) {
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, "Unexpected response while fetching access token: " + JSON.stringify(json));
|
||||
}
|
||||
return json;
|
||||
}).catch(function (err) {
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, getErrorMessage(err));
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Constructs a human-readable error message from the given Error.
|
||||
*/
|
||||
function getErrorMessage(err) {
|
||||
var detail = (err instanceof api_request_1.HttpError) ? getDetailFromResponse(err.response) : err.message;
|
||||
return "Error fetching access token: " + detail;
|
||||
}
|
||||
/**
|
||||
* Extracts details from the given HTTP error response, and returns a human-readable description. If
|
||||
* the response is JSON-formatted, looks up the error and error_description fields sent by the
|
||||
* Google Auth servers. Otherwise returns the entire response payload as the error detail.
|
||||
*/
|
||||
function getDetailFromResponse(response) {
|
||||
if (response.isJson() && response.data.error) {
|
||||
var json = response.data;
|
||||
var detail = json.error;
|
||||
if (json.error_description) {
|
||||
detail += ' (' + json.error_description + ')';
|
||||
}
|
||||
return detail;
|
||||
}
|
||||
return response.text || 'Missing error payload';
|
||||
}
|
||||
function credentialFromFile(filePath, httpAgent) {
|
||||
var credentialsFile = readCredentialFile(filePath);
|
||||
if (typeof credentialsFile !== 'object' || credentialsFile === null) {
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, 'Failed to parse contents of the credentials file as an object');
|
||||
}
|
||||
if (credentialsFile.type === 'service_account') {
|
||||
return new ServiceAccountCredential(credentialsFile, httpAgent, true);
|
||||
}
|
||||
if (credentialsFile.type === 'authorized_user') {
|
||||
return new RefreshTokenCredential(credentialsFile, httpAgent, true);
|
||||
}
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, 'Invalid contents in the credentials file');
|
||||
}
|
||||
function readCredentialFile(filePath, ignoreMissing) {
|
||||
var fileText;
|
||||
try {
|
||||
fileText = fs.readFileSync(filePath, 'utf8');
|
||||
}
|
||||
catch (error) {
|
||||
if (ignoreMissing) {
|
||||
return null;
|
||||
}
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, "Failed to read credentials from file " + filePath + ": " + error);
|
||||
}
|
||||
try {
|
||||
return JSON.parse(fileText);
|
||||
}
|
||||
catch (error) {
|
||||
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, 'Failed to parse contents of the credentials file as an object: ' + error);
|
||||
}
|
||||
}
|
139
node_modules/firebase-admin/lib/auth/tenant-manager.js
generated
vendored
Normal file
139
node_modules/firebase-admin/lib/auth/tenant-manager.js
generated
vendored
Normal file
@ -0,0 +1,139 @@
|
||||
/*! firebase-admin v8.9.2 */
|
||||
"use strict";
|
||||
/*!
|
||||
* Copyright 2019 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
var auth_api_request_1 = require("./auth-api-request");
|
||||
var auth_1 = require("./auth");
|
||||
var tenant_1 = require("./tenant");
|
||||
var error_1 = require("../utils/error");
|
||||
var validator = require("../utils/validator");
|
||||
/**
|
||||
* Data structure used to help manage tenant related operations.
|
||||
* This includes:
|
||||
* - The ability to create, update, list, get and delete tenants for the underlying project.
|
||||
* - Getting a TenantAwareAuth instance for running Auth related operations (user mgmt, provider config mgmt, etc)
|
||||
* in the context of a specified tenant.
|
||||
*/
|
||||
var TenantManager = /** @class */ (function () {
|
||||
/**
|
||||
* Initializes a TenantManager instance for a specified FirebaseApp.
|
||||
* @param app The app for this TenantManager instance.
|
||||
*/
|
||||
function TenantManager(app) {
|
||||
this.app = app;
|
||||
this.authRequestHandler = new auth_api_request_1.AuthRequestHandler(app);
|
||||
this.tenantsMap = {};
|
||||
}
|
||||
/**
|
||||
* Returns a TenantAwareAuth instance for the corresponding tenant ID.
|
||||
*
|
||||
* @param tenantId The tenant ID whose TenantAwareAuth is to be returned.
|
||||
* @return The corresponding TenantAwareAuth instance.
|
||||
*/
|
||||
TenantManager.prototype.authForTenant = function (tenantId) {
|
||||
if (!validator.isNonEmptyString(tenantId)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_TENANT_ID);
|
||||
}
|
||||
if (typeof this.tenantsMap[tenantId] === 'undefined') {
|
||||
this.tenantsMap[tenantId] = new auth_1.TenantAwareAuth(this.app, tenantId);
|
||||
}
|
||||
return this.tenantsMap[tenantId];
|
||||
};
|
||||
/**
|
||||
* Looks up the tenant identified by the provided tenant ID and returns a promise that is
|
||||
* fulfilled with the corresponding tenant if it is found.
|
||||
*
|
||||
* @param tenantId The tenant ID of the tenant to look up.
|
||||
* @return A promise that resolves with the corresponding tenant.
|
||||
*/
|
||||
TenantManager.prototype.getTenant = function (tenantId) {
|
||||
return this.authRequestHandler.getTenant(tenantId)
|
||||
.then(function (response) {
|
||||
return new tenant_1.Tenant(response);
|
||||
});
|
||||
};
|
||||
/**
|
||||
* Exports a batch of tenant accounts. Batch size is determined by the maxResults argument.
|
||||
* Starting point of the batch is determined by the pageToken argument.
|
||||
*
|
||||
* @param maxResults The page size, 1000 if undefined. This is also the maximum
|
||||
* allowed limit.
|
||||
* @param pageToken The next page token. If not specified, returns users starting
|
||||
* without any offset.
|
||||
* @return A promise that resolves with
|
||||
* the current batch of downloaded tenants and the next page token. For the last page, an
|
||||
* empty list of tenants and no page token are returned.
|
||||
*/
|
||||
TenantManager.prototype.listTenants = function (maxResults, pageToken) {
|
||||
return this.authRequestHandler.listTenants(maxResults, pageToken)
|
||||
.then(function (response) {
|
||||
// List of tenants to return.
|
||||
var tenants = [];
|
||||
// Convert each user response to a Tenant.
|
||||
response.tenants.forEach(function (tenantResponse) {
|
||||
tenants.push(new tenant_1.Tenant(tenantResponse));
|
||||
});
|
||||
// Return list of tenants and the next page token if available.
|
||||
var result = {
|
||||
tenants: tenants,
|
||||
pageToken: response.nextPageToken,
|
||||
};
|
||||
// Delete result.pageToken if undefined.
|
||||
if (typeof result.pageToken === 'undefined') {
|
||||
delete result.pageToken;
|
||||
}
|
||||
return result;
|
||||
});
|
||||
};
|
||||
/**
|
||||
* Deletes the tenant identified by the provided tenant ID and returns a promise that is
|
||||
* fulfilled when the tenant is found and successfully deleted.
|
||||
*
|
||||
* @param tenantId The tenant ID of the tenant to delete.
|
||||
* @return A promise that resolves when the tenant is successfully deleted.
|
||||
*/
|
||||
TenantManager.prototype.deleteTenant = function (tenantId) {
|
||||
return this.authRequestHandler.deleteTenant(tenantId);
|
||||
};
|
||||
/**
|
||||
* Creates a new tenant with the properties provided.
|
||||
*
|
||||
* @param tenantOptions The properties to set on the new tenant to be created.
|
||||
* @return A promise that resolves with the newly created tenant.
|
||||
*/
|
||||
TenantManager.prototype.createTenant = function (tenantOptions) {
|
||||
return this.authRequestHandler.createTenant(tenantOptions)
|
||||
.then(function (response) {
|
||||
return new tenant_1.Tenant(response);
|
||||
});
|
||||
};
|
||||
/**
|
||||
* Updates an existing tenant identified by the tenant ID with the properties provided.
|
||||
*
|
||||
* @param tenantId The tenant identifier of the tenant to update.
|
||||
* @param tenantOptions The properties to update on the existing tenant.
|
||||
* @return A promise that resolves with the modified tenant.
|
||||
*/
|
||||
TenantManager.prototype.updateTenant = function (tenantId, tenantOptions) {
|
||||
return this.authRequestHandler.updateTenant(tenantId, tenantOptions)
|
||||
.then(function (response) {
|
||||
return new tenant_1.Tenant(response);
|
||||
});
|
||||
};
|
||||
return TenantManager;
|
||||
}());
|
||||
exports.TenantManager = TenantManager;
|
123
node_modules/firebase-admin/lib/auth/tenant.js
generated
vendored
Normal file
123
node_modules/firebase-admin/lib/auth/tenant.js
generated
vendored
Normal file
@ -0,0 +1,123 @@
|
||||
/*! firebase-admin v8.9.2 */
|
||||
"use strict";
|
||||
/*!
|
||||
* Copyright 2019 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
var validator = require("../utils/validator");
|
||||
var error_1 = require("../utils/error");
|
||||
var auth_config_1 = require("./auth-config");
|
||||
/**
|
||||
* Tenant class that defines a Firebase Auth tenant.
|
||||
*/
|
||||
var Tenant = /** @class */ (function () {
|
||||
/**
|
||||
* The Tenant object constructor.
|
||||
*
|
||||
* @param {any} response The server side response used to initialize the Tenant object.
|
||||
* @constructor
|
||||
*/
|
||||
function Tenant(response) {
|
||||
var tenantId = Tenant.getTenantIdFromResourceName(response.name);
|
||||
if (!tenantId) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid tenant response');
|
||||
}
|
||||
this.tenantId = tenantId;
|
||||
this.displayName = response.displayName;
|
||||
try {
|
||||
this.emailSignInConfig = new auth_config_1.EmailSignInConfig(response);
|
||||
}
|
||||
catch (e) {
|
||||
// If allowPasswordSignup is undefined, it is disabled by default.
|
||||
this.emailSignInConfig = new auth_config_1.EmailSignInConfig({
|
||||
allowPasswordSignup: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Builds the corresponding server request for a TenantOptions object.
|
||||
*
|
||||
* @param {TenantOptions} tenantOptions The properties to convert to a server request.
|
||||
* @param {boolean} createRequest Whether this is a create request.
|
||||
* @return {object} The equivalent server request.
|
||||
*/
|
||||
Tenant.buildServerRequest = function (tenantOptions, createRequest) {
|
||||
Tenant.validate(tenantOptions, createRequest);
|
||||
var request = {};
|
||||
if (typeof tenantOptions.emailSignInConfig !== 'undefined') {
|
||||
request = auth_config_1.EmailSignInConfig.buildServerRequest(tenantOptions.emailSignInConfig);
|
||||
}
|
||||
if (typeof tenantOptions.displayName !== 'undefined') {
|
||||
request.displayName = tenantOptions.displayName;
|
||||
}
|
||||
return request;
|
||||
};
|
||||
/**
|
||||
* Returns the tenant ID corresponding to the resource name if available.
|
||||
*
|
||||
* @param {string} resourceName The server side resource name
|
||||
* @return {?string} The tenant ID corresponding to the resource, null otherwise.
|
||||
*/
|
||||
Tenant.getTenantIdFromResourceName = function (resourceName) {
|
||||
// name is of form projects/project1/tenants/tenant1
|
||||
var matchTenantRes = resourceName.match(/\/tenants\/(.*)$/);
|
||||
if (!matchTenantRes || matchTenantRes.length < 2) {
|
||||
return null;
|
||||
}
|
||||
return matchTenantRes[1];
|
||||
};
|
||||
/**
|
||||
* Validates a tenant options object. Throws an error on failure.
|
||||
*
|
||||
* @param {any} request The tenant options object to validate.
|
||||
* @param {boolean} createRequest Whether this is a create request.
|
||||
*/
|
||||
Tenant.validate = function (request, createRequest) {
|
||||
var validKeys = {
|
||||
displayName: true,
|
||||
emailSignInConfig: true,
|
||||
};
|
||||
var label = createRequest ? 'CreateTenantRequest' : 'UpdateTenantRequest';
|
||||
if (!validator.isNonNullObject(request)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, "\"" + label + "\" must be a valid non-null object.");
|
||||
}
|
||||
// Check for unsupported top level attributes.
|
||||
for (var key in request) {
|
||||
if (!(key in validKeys)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, "\"" + key + "\" is not a valid " + label + " parameter.");
|
||||
}
|
||||
}
|
||||
// Validate displayName type if provided.
|
||||
if (typeof request.displayName !== 'undefined' &&
|
||||
!validator.isNonEmptyString(request.displayName)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, "\"" + label + ".displayName\" must be a valid non-empty string.");
|
||||
}
|
||||
// Validate emailSignInConfig type if provided.
|
||||
if (typeof request.emailSignInConfig !== 'undefined') {
|
||||
// This will throw an error if invalid.
|
||||
auth_config_1.EmailSignInConfig.buildServerRequest(request.emailSignInConfig);
|
||||
}
|
||||
};
|
||||
/** @return {object} The plain object representation of the tenant. */
|
||||
Tenant.prototype.toJSON = function () {
|
||||
return {
|
||||
tenantId: this.tenantId,
|
||||
displayName: this.displayName,
|
||||
emailSignInConfig: this.emailSignInConfig && this.emailSignInConfig.toJSON(),
|
||||
};
|
||||
};
|
||||
return Tenant;
|
||||
}());
|
||||
exports.Tenant = Tenant;
|
265
node_modules/firebase-admin/lib/auth/token-generator.js
generated
vendored
Normal file
265
node_modules/firebase-admin/lib/auth/token-generator.js
generated
vendored
Normal file
@ -0,0 +1,265 @@
|
||||
/*! firebase-admin v8.9.2 */
|
||||
"use strict";
|
||||
/*!
|
||||
* Copyright 2017 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
var credential_1 = require("./credential");
|
||||
var error_1 = require("../utils/error");
|
||||
var api_request_1 = require("../utils/api-request");
|
||||
var validator = require("../utils/validator");
|
||||
var utils_1 = require("../utils");
|
||||
var ALGORITHM_RS256 = 'RS256';
|
||||
var ONE_HOUR_IN_SECONDS = 60 * 60;
|
||||
// List of blacklisted claims which cannot be provided when creating a custom token
|
||||
exports.BLACKLISTED_CLAIMS = [
|
||||
'acr', 'amr', 'at_hash', 'aud', 'auth_time', 'azp', 'cnf', 'c_hash', 'exp', 'iat', 'iss', 'jti',
|
||||
'nbf', 'nonce',
|
||||
];
|
||||
// Audience to use for Firebase Auth Custom tokens
|
||||
var FIREBASE_AUDIENCE = 'https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit';
|
||||
/**
|
||||
* A CryptoSigner implementation that uses an explicitly specified service account private key to
|
||||
* sign data. Performs all operations locally, and does not make any RPC calls.
|
||||
*/
|
||||
var ServiceAccountSigner = /** @class */ (function () {
|
||||
/**
|
||||
* Creates a new CryptoSigner instance from the given service account credential.
|
||||
*
|
||||
* @param {ServiceAccountCredential} credential A service account credential.
|
||||
*/
|
||||
function ServiceAccountSigner(credential) {
|
||||
this.credential = credential;
|
||||
if (!credential) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CREDENTIAL, 'INTERNAL ASSERT: Must provide a service account credential to initialize ServiceAccountSigner.');
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
ServiceAccountSigner.prototype.sign = function (buffer) {
|
||||
var crypto = require('crypto');
|
||||
var sign = crypto.createSign('RSA-SHA256');
|
||||
sign.update(buffer);
|
||||
return Promise.resolve(sign.sign(this.credential.privateKey));
|
||||
};
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
ServiceAccountSigner.prototype.getAccountId = function () {
|
||||
return Promise.resolve(this.credential.clientEmail);
|
||||
};
|
||||
return ServiceAccountSigner;
|
||||
}());
|
||||
exports.ServiceAccountSigner = ServiceAccountSigner;
|
||||
/**
|
||||
* A CryptoSigner implementation that uses the remote IAM service to sign data. If initialized without
|
||||
* a service account ID, attempts to discover a service account ID by consulting the local Metadata
|
||||
* service. This will succeed in managed environments like Google Cloud Functions and App Engine.
|
||||
*
|
||||
* @see https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts/signBlob
|
||||
* @see https://cloud.google.com/compute/docs/storing-retrieving-metadata
|
||||
*/
|
||||
var IAMSigner = /** @class */ (function () {
|
||||
function IAMSigner(httpClient, serviceAccountId) {
|
||||
if (!httpClient) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, 'INTERNAL ASSERT: Must provide a HTTP client to initialize IAMSigner.');
|
||||
}
|
||||
if (typeof serviceAccountId !== 'undefined' && !validator.isNonEmptyString(serviceAccountId)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, 'INTERNAL ASSERT: Service account ID must be undefined or a non-empty string.');
|
||||
}
|
||||
this.httpClient = httpClient;
|
||||
this.serviceAccountId = serviceAccountId;
|
||||
}
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
IAMSigner.prototype.sign = function (buffer) {
|
||||
var _this = this;
|
||||
return this.getAccountId().then(function (serviceAccount) {
|
||||
var request = {
|
||||
method: 'POST',
|
||||
url: "https://iam.googleapis.com/v1/projects/-/serviceAccounts/" + serviceAccount + ":signBlob",
|
||||
data: { bytesToSign: buffer.toString('base64') },
|
||||
};
|
||||
return _this.httpClient.send(request);
|
||||
}).then(function (response) {
|
||||
// Response from IAM is base64 encoded. Decode it into a buffer and return.
|
||||
return Buffer.from(response.data.signature, 'base64');
|
||||
}).catch(function (err) {
|
||||
if (err instanceof api_request_1.HttpError) {
|
||||
var error = err.response.data;
|
||||
if (validator.isNonNullObject(error) && error.error) {
|
||||
var errorCode = error.error.status;
|
||||
var description = 'Please refer to https://firebase.google.com/docs/auth/admin/create-custom-tokens ' +
|
||||
'for more details on how to use and troubleshoot this feature.';
|
||||
var errorMsg = error.error.message + "; " + description;
|
||||
throw error_1.FirebaseAuthError.fromServerError(errorCode, errorMsg, error);
|
||||
}
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'Error returned from server: ' + error + '. Additionally, an ' +
|
||||
'internal error occurred while attempting to extract the ' +
|
||||
'errorcode from the error.');
|
||||
}
|
||||
throw err;
|
||||
});
|
||||
};
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
IAMSigner.prototype.getAccountId = function () {
|
||||
var _this = this;
|
||||
if (validator.isNonEmptyString(this.serviceAccountId)) {
|
||||
return Promise.resolve(this.serviceAccountId);
|
||||
}
|
||||
var request = {
|
||||
method: 'GET',
|
||||
url: 'http://metadata/computeMetadata/v1/instance/service-accounts/default/email',
|
||||
headers: {
|
||||
'Metadata-Flavor': 'Google',
|
||||
},
|
||||
};
|
||||
var client = new api_request_1.HttpClient();
|
||||
return client.send(request).then(function (response) {
|
||||
if (!response.text) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'HTTP Response missing payload');
|
||||
}
|
||||
_this.serviceAccountId = response.text;
|
||||
return response.text;
|
||||
}).catch(function (err) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CREDENTIAL, "Failed to determine service account. Make sure to initialize " +
|
||||
"the SDK with a service account credential. Alternatively specify a service " +
|
||||
("account with iam.serviceAccounts.signBlob permission. Original error: " + err));
|
||||
});
|
||||
};
|
||||
return IAMSigner;
|
||||
}());
|
||||
exports.IAMSigner = IAMSigner;
|
||||
/**
|
||||
* Create a new CryptoSigner instance for the given app. If the app has been initialized with a service
|
||||
* account credential, creates a ServiceAccountSigner. Otherwise creates an IAMSigner.
|
||||
*
|
||||
* @param {FirebaseApp} app A FirebaseApp instance.
|
||||
* @return {CryptoSigner} A CryptoSigner instance.
|
||||
*/
|
||||
function cryptoSignerFromApp(app) {
|
||||
var credential = app.options.credential;
|
||||
if (credential instanceof credential_1.ServiceAccountCredential) {
|
||||
return new ServiceAccountSigner(credential);
|
||||
}
|
||||
return new IAMSigner(new api_request_1.AuthorizedHttpClient(app), app.options.serviceAccountId);
|
||||
}
|
||||
exports.cryptoSignerFromApp = cryptoSignerFromApp;
|
||||
/**
|
||||
* Class for generating different types of Firebase Auth tokens (JWTs).
|
||||
*/
|
||||
var FirebaseTokenGenerator = /** @class */ (function () {
|
||||
/**
|
||||
* @param tenantId The tenant ID to use for the generated Firebase Auth
|
||||
* Custom token. If absent, then no tenant ID claim will be set in the
|
||||
* resulting JWT.
|
||||
*/
|
||||
function FirebaseTokenGenerator(signer, tenantId) {
|
||||
this.tenantId = tenantId;
|
||||
if (!validator.isNonNullObject(signer)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CREDENTIAL, 'INTERNAL ASSERT: Must provide a CryptoSigner to use FirebaseTokenGenerator.');
|
||||
}
|
||||
if (typeof tenantId !== 'undefined' && !validator.isNonEmptyString(tenantId)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '`tenantId` argument must be a non-empty string.');
|
||||
}
|
||||
this.signer = signer;
|
||||
}
|
||||
/**
|
||||
* Creates a new Firebase Auth Custom token.
|
||||
*
|
||||
* @param uid The user ID to use for the generated Firebase Auth Custom token.
|
||||
* @param developerClaims Optional developer claims to include in the generated Firebase
|
||||
* Auth Custom token.
|
||||
* @return A Promise fulfilled with a Firebase Auth Custom token signed with a
|
||||
* service account key and containing the provided payload.
|
||||
*/
|
||||
FirebaseTokenGenerator.prototype.createCustomToken = function (uid, developerClaims) {
|
||||
var _this = this;
|
||||
var errorMessage;
|
||||
if (!validator.isNonEmptyString(uid)) {
|
||||
errorMessage = '`uid` argument must be a non-empty string uid.';
|
||||
}
|
||||
else if (uid.length > 128) {
|
||||
errorMessage = '`uid` argument must a uid with less than or equal to 128 characters.';
|
||||
}
|
||||
else if (!this.isDeveloperClaimsValid_(developerClaims)) {
|
||||
errorMessage = '`developerClaims` argument must be a valid, non-null object containing the developer claims.';
|
||||
}
|
||||
if (errorMessage) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, errorMessage);
|
||||
}
|
||||
var claims = {};
|
||||
if (typeof developerClaims !== 'undefined') {
|
||||
for (var key in developerClaims) {
|
||||
/* istanbul ignore else */
|
||||
if (developerClaims.hasOwnProperty(key)) {
|
||||
if (exports.BLACKLISTED_CLAIMS.indexOf(key) !== -1) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, "Developer claim \"" + key + "\" is reserved and cannot be specified.");
|
||||
}
|
||||
claims[key] = developerClaims[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
return this.signer.getAccountId().then(function (account) {
|
||||
var header = {
|
||||
alg: ALGORITHM_RS256,
|
||||
typ: 'JWT',
|
||||
};
|
||||
var iat = Math.floor(Date.now() / 1000);
|
||||
var body = {
|
||||
aud: FIREBASE_AUDIENCE,
|
||||
iat: iat,
|
||||
exp: iat + ONE_HOUR_IN_SECONDS,
|
||||
iss: account,
|
||||
sub: account,
|
||||
uid: uid,
|
||||
};
|
||||
if (_this.tenantId) {
|
||||
body.tenant_id = _this.tenantId;
|
||||
}
|
||||
if (Object.keys(claims).length > 0) {
|
||||
body.claims = claims;
|
||||
}
|
||||
var token = _this.encodeSegment(header) + "." + _this.encodeSegment(body);
|
||||
var signPromise = _this.signer.sign(Buffer.from(token));
|
||||
return Promise.all([token, signPromise]);
|
||||
}).then(function (_a) {
|
||||
var token = _a[0], signature = _a[1];
|
||||
return token + "." + _this.encodeSegment(signature);
|
||||
});
|
||||
};
|
||||
FirebaseTokenGenerator.prototype.encodeSegment = function (segment) {
|
||||
var buffer = (segment instanceof Buffer) ? segment : Buffer.from(JSON.stringify(segment));
|
||||
return utils_1.toWebSafeBase64(buffer).replace(/\=+$/, '');
|
||||
};
|
||||
/**
|
||||
* Returns whether or not the provided developer claims are valid.
|
||||
*
|
||||
* @param {object} [developerClaims] Optional developer claims to validate.
|
||||
* @return {boolean} True if the provided claims are valid; otherwise, false.
|
||||
*/
|
||||
FirebaseTokenGenerator.prototype.isDeveloperClaimsValid_ = function (developerClaims) {
|
||||
if (typeof developerClaims === 'undefined') {
|
||||
return true;
|
||||
}
|
||||
return validator.isNonNullObject(developerClaims);
|
||||
};
|
||||
return FirebaseTokenGenerator;
|
||||
}());
|
||||
exports.FirebaseTokenGenerator = FirebaseTokenGenerator;
|
301
node_modules/firebase-admin/lib/auth/token-verifier.js
generated
vendored
Normal file
301
node_modules/firebase-admin/lib/auth/token-verifier.js
generated
vendored
Normal file
@ -0,0 +1,301 @@
|
||||
/*! firebase-admin v8.9.2 */
|
||||
"use strict";
|
||||
/*!
|
||||
* Copyright 2018 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
var error_1 = require("../utils/error");
|
||||
var util = require("../utils/index");
|
||||
var validator = require("../utils/validator");
|
||||
var jwt = require("jsonwebtoken");
|
||||
var api_request_1 = require("../utils/api-request");
|
||||
// Audience to use for Firebase Auth Custom tokens
|
||||
var FIREBASE_AUDIENCE = 'https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit';
|
||||
exports.ALGORITHM_RS256 = 'RS256';
|
||||
// URL containing the public keys for the Google certs (whose private keys are used to sign Firebase
|
||||
// Auth ID tokens)
|
||||
var CLIENT_CERT_URL = 'https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com';
|
||||
// URL containing the public keys for Firebase session cookies. This will be updated to a different URL soon.
|
||||
var SESSION_COOKIE_CERT_URL = 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/publicKeys';
|
||||
/** User facing token information related to the Firebase ID token. */
|
||||
exports.ID_TOKEN_INFO = {
|
||||
url: 'https://firebase.google.com/docs/auth/admin/verify-id-tokens',
|
||||
verifyApiName: 'verifyIdToken()',
|
||||
jwtName: 'Firebase ID token',
|
||||
shortName: 'ID token',
|
||||
expiredErrorCode: error_1.AuthClientErrorCode.ID_TOKEN_EXPIRED,
|
||||
};
|
||||
/** User facing token information related to the Firebase session cookie. */
|
||||
exports.SESSION_COOKIE_INFO = {
|
||||
url: 'https://firebase.google.com/docs/auth/admin/manage-cookies',
|
||||
verifyApiName: 'verifySessionCookie()',
|
||||
jwtName: 'Firebase session cookie',
|
||||
shortName: 'session cookie',
|
||||
expiredErrorCode: error_1.AuthClientErrorCode.SESSION_COOKIE_EXPIRED,
|
||||
};
|
||||
/**
|
||||
* Class for verifying general purpose Firebase JWTs. This verifies ID tokens and session cookies.
|
||||
*/
|
||||
var FirebaseTokenVerifier = /** @class */ (function () {
|
||||
function FirebaseTokenVerifier(clientCertUrl, algorithm, issuer, tokenInfo, app) {
|
||||
this.clientCertUrl = clientCertUrl;
|
||||
this.algorithm = algorithm;
|
||||
this.issuer = issuer;
|
||||
this.tokenInfo = tokenInfo;
|
||||
this.app = app;
|
||||
if (!validator.isURL(clientCertUrl)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, "The provided public client certificate URL is an invalid URL.");
|
||||
}
|
||||
else if (!validator.isNonEmptyString(algorithm)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, "The provided JWT algorithm is an empty string.");
|
||||
}
|
||||
else if (!validator.isURL(issuer)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, "The provided JWT issuer is an invalid URL.");
|
||||
}
|
||||
else if (!validator.isNonNullObject(tokenInfo)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, "The provided JWT information is not an object or null.");
|
||||
}
|
||||
else if (!validator.isURL(tokenInfo.url)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, "The provided JWT verification documentation URL is invalid.");
|
||||
}
|
||||
else if (!validator.isNonEmptyString(tokenInfo.verifyApiName)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, "The JWT verify API name must be a non-empty string.");
|
||||
}
|
||||
else if (!validator.isNonEmptyString(tokenInfo.jwtName)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, "The JWT public full name must be a non-empty string.");
|
||||
}
|
||||
else if (!validator.isNonEmptyString(tokenInfo.shortName)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, "The JWT public short name must be a non-empty string.");
|
||||
}
|
||||
else if (!validator.isNonNullObject(tokenInfo.expiredErrorCode) || !('code' in tokenInfo.expiredErrorCode)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, "The JWT expiration error code must be a non-null ErrorInfo object.");
|
||||
}
|
||||
this.shortNameArticle = tokenInfo.shortName.charAt(0).match(/[aeiou]/i) ? 'an' : 'a';
|
||||
// For backward compatibility, the project ID is validated in the verification call.
|
||||
}
|
||||
/**
|
||||
* Verifies the format and signature of a Firebase Auth JWT token.
|
||||
*
|
||||
* @param {string} jwtToken The Firebase Auth JWT token to verify.
|
||||
* @return {Promise<DecodedIdToken>} A promise fulfilled with the decoded claims of the Firebase Auth ID
|
||||
* token.
|
||||
*/
|
||||
FirebaseTokenVerifier.prototype.verifyJWT = function (jwtToken) {
|
||||
var _this = this;
|
||||
if (!validator.isString(jwtToken)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, "First argument to " + this.tokenInfo.verifyApiName + " must be a " + this.tokenInfo.jwtName + " string.");
|
||||
}
|
||||
return util.findProjectId(this.app)
|
||||
.then(function (projectId) {
|
||||
return _this.verifyJWTWithProjectId(jwtToken, projectId);
|
||||
});
|
||||
};
|
||||
FirebaseTokenVerifier.prototype.verifyJWTWithProjectId = function (jwtToken, projectId) {
|
||||
var _this = this;
|
||||
if (!validator.isNonEmptyString(projectId)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CREDENTIAL, "Must initialize app with a cert credential or set your Firebase project ID as the " +
|
||||
("GOOGLE_CLOUD_PROJECT environment variable to call " + this.tokenInfo.verifyApiName + "."));
|
||||
}
|
||||
var fullDecodedToken = jwt.decode(jwtToken, {
|
||||
complete: true,
|
||||
});
|
||||
var header = fullDecodedToken && fullDecodedToken.header;
|
||||
var payload = fullDecodedToken && fullDecodedToken.payload;
|
||||
var projectIdMatchMessage = " Make sure the " + this.tokenInfo.shortName + " comes from the same " +
|
||||
"Firebase project as the service account used to authenticate this SDK.";
|
||||
var verifyJwtTokenDocsMessage = " See " + this.tokenInfo.url + " " +
|
||||
("for details on how to retrieve " + this.shortNameArticle + " " + this.tokenInfo.shortName + ".");
|
||||
var errorMessage;
|
||||
if (!fullDecodedToken) {
|
||||
errorMessage = "Decoding " + this.tokenInfo.jwtName + " failed. Make sure you passed the entire string JWT " +
|
||||
("which represents " + this.shortNameArticle + " " + this.tokenInfo.shortName + ".") + verifyJwtTokenDocsMessage;
|
||||
}
|
||||
else if (typeof header.kid === 'undefined') {
|
||||
var isCustomToken = (payload.aud === FIREBASE_AUDIENCE);
|
||||
var isLegacyCustomToken = (header.alg === 'HS256' && payload.v === 0 && 'd' in payload && 'uid' in payload.d);
|
||||
if (isCustomToken) {
|
||||
errorMessage = this.tokenInfo.verifyApiName + " expects " + this.shortNameArticle + " " +
|
||||
(this.tokenInfo.shortName + ", but was given a custom token.");
|
||||
}
|
||||
else if (isLegacyCustomToken) {
|
||||
errorMessage = this.tokenInfo.verifyApiName + " expects " + this.shortNameArticle + " " +
|
||||
(this.tokenInfo.shortName + ", but was given a legacy custom token.");
|
||||
}
|
||||
else {
|
||||
errorMessage = 'Firebase ID token has no "kid" claim.';
|
||||
}
|
||||
errorMessage += verifyJwtTokenDocsMessage;
|
||||
}
|
||||
else if (header.alg !== this.algorithm) {
|
||||
errorMessage = this.tokenInfo.jwtName + " has incorrect algorithm. Expected \"" + this.algorithm + "\" but got " +
|
||||
"\"" + header.alg + "\"." + verifyJwtTokenDocsMessage;
|
||||
}
|
||||
else if (payload.aud !== projectId) {
|
||||
errorMessage = this.tokenInfo.jwtName + " has incorrect \"aud\" (audience) claim. Expected \"" +
|
||||
projectId + "\" but got \"" + payload.aud + "\"." + projectIdMatchMessage +
|
||||
verifyJwtTokenDocsMessage;
|
||||
}
|
||||
else if (payload.iss !== this.issuer + projectId) {
|
||||
errorMessage = this.tokenInfo.jwtName + " has incorrect \"iss\" (issuer) claim. Expected " +
|
||||
("\"" + this.issuer + "\"") + projectId + "\" but got \"" +
|
||||
payload.iss + "\"." + projectIdMatchMessage + verifyJwtTokenDocsMessage;
|
||||
}
|
||||
else if (typeof payload.sub !== 'string') {
|
||||
errorMessage = this.tokenInfo.jwtName + " has no \"sub\" (subject) claim." + verifyJwtTokenDocsMessage;
|
||||
}
|
||||
else if (payload.sub === '') {
|
||||
errorMessage = this.tokenInfo.jwtName + " has an empty string \"sub\" (subject) claim." + verifyJwtTokenDocsMessage;
|
||||
}
|
||||
else if (payload.sub.length > 128) {
|
||||
errorMessage = this.tokenInfo.jwtName + " has \"sub\" (subject) claim longer than 128 characters." +
|
||||
verifyJwtTokenDocsMessage;
|
||||
}
|
||||
if (errorMessage) {
|
||||
return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, errorMessage));
|
||||
}
|
||||
return this.fetchPublicKeys().then(function (publicKeys) {
|
||||
if (!publicKeys.hasOwnProperty(header.kid)) {
|
||||
return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, _this.tokenInfo.jwtName + " has \"kid\" claim which does not correspond to a known public key. " +
|
||||
("Most likely the " + _this.tokenInfo.shortName + " is expired, so get a fresh token from your ") +
|
||||
"client app and try again."));
|
||||
}
|
||||
else {
|
||||
return _this.verifyJwtSignatureWithKey(jwtToken, publicKeys[header.kid]);
|
||||
}
|
||||
});
|
||||
};
|
||||
/**
|
||||
* Verifies the JWT signature using the provided public key.
|
||||
* @param {string} jwtToken The JWT token to verify.
|
||||
* @param {string} publicKey The public key certificate.
|
||||
* @return {Promise<DecodedIdToken>} A promise that resolves with the decoded JWT claims on successful
|
||||
* verification.
|
||||
*/
|
||||
FirebaseTokenVerifier.prototype.verifyJwtSignatureWithKey = function (jwtToken, publicKey) {
|
||||
var _this = this;
|
||||
var verifyJwtTokenDocsMessage = " See " + this.tokenInfo.url + " " +
|
||||
("for details on how to retrieve " + this.shortNameArticle + " " + this.tokenInfo.shortName + ".");
|
||||
return new Promise(function (resolve, reject) {
|
||||
jwt.verify(jwtToken, publicKey, {
|
||||
algorithms: [_this.algorithm],
|
||||
}, function (error, decodedToken) {
|
||||
if (error) {
|
||||
if (error.name === 'TokenExpiredError') {
|
||||
var errorMessage = _this.tokenInfo.jwtName + " has expired. Get a fresh " + _this.tokenInfo.shortName +
|
||||
(" from your client app and try again (auth/" + _this.tokenInfo.expiredErrorCode.code + ").") +
|
||||
verifyJwtTokenDocsMessage;
|
||||
return reject(new error_1.FirebaseAuthError(_this.tokenInfo.expiredErrorCode, errorMessage));
|
||||
}
|
||||
else if (error.name === 'JsonWebTokenError') {
|
||||
var errorMessage = _this.tokenInfo.jwtName + " has invalid signature." + verifyJwtTokenDocsMessage;
|
||||
return reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, errorMessage));
|
||||
}
|
||||
return reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, error.message));
|
||||
}
|
||||
else {
|
||||
// TODO(rsgowman): I think the typing on jwt.verify is wrong. It claims that this can be either a string or an
|
||||
// object, but the code always seems to call it as an object. Investigate and upstream typing changes if this
|
||||
// is actually correct.
|
||||
if (typeof decodedToken === 'string') {
|
||||
return reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, "Unexpected decodedToken. Expected an object but got a string: '" + decodedToken + "'"));
|
||||
}
|
||||
else {
|
||||
var decodedIdToken = decodedToken;
|
||||
decodedIdToken.uid = decodedIdToken.sub;
|
||||
resolve(decodedIdToken);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
/**
|
||||
* Fetches the public keys for the Google certs.
|
||||
*
|
||||
* @return {Promise<object>} A promise fulfilled with public keys for the Google certs.
|
||||
*/
|
||||
FirebaseTokenVerifier.prototype.fetchPublicKeys = function () {
|
||||
var _this = this;
|
||||
var publicKeysExist = (typeof this.publicKeys !== 'undefined');
|
||||
var publicKeysExpiredExists = (typeof this.publicKeysExpireAt !== 'undefined');
|
||||
var publicKeysStillValid = (publicKeysExpiredExists && Date.now() < this.publicKeysExpireAt);
|
||||
if (publicKeysExist && publicKeysStillValid) {
|
||||
return Promise.resolve(this.publicKeys);
|
||||
}
|
||||
var client = new api_request_1.HttpClient();
|
||||
var request = {
|
||||
method: 'GET',
|
||||
url: this.clientCertUrl,
|
||||
httpAgent: this.app.options.httpAgent,
|
||||
};
|
||||
return client.send(request).then(function (resp) {
|
||||
if (!resp.isJson() || resp.data.error) {
|
||||
// Treat all non-json messages and messages with an 'error' field as
|
||||
// error responses.
|
||||
throw new api_request_1.HttpError(resp);
|
||||
}
|
||||
if (resp.headers.hasOwnProperty('cache-control')) {
|
||||
var cacheControlHeader = resp.headers['cache-control'];
|
||||
var parts = cacheControlHeader.split(',');
|
||||
parts.forEach(function (part) {
|
||||
var subParts = part.trim().split('=');
|
||||
if (subParts[0] === 'max-age') {
|
||||
var maxAge = +subParts[1];
|
||||
_this.publicKeysExpireAt = Date.now() + (maxAge * 1000);
|
||||
}
|
||||
});
|
||||
}
|
||||
_this.publicKeys = resp.data;
|
||||
return resp.data;
|
||||
}).catch(function (err) {
|
||||
if (err instanceof api_request_1.HttpError) {
|
||||
var errorMessage = 'Error fetching public keys for Google certs: ';
|
||||
var resp = err.response;
|
||||
if (resp.isJson() && resp.data.error) {
|
||||
errorMessage += "" + resp.data.error;
|
||||
if (resp.data.error_description) {
|
||||
errorMessage += ' (' + resp.data.error_description + ')';
|
||||
}
|
||||
}
|
||||
else {
|
||||
errorMessage += "" + resp.text;
|
||||
}
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, errorMessage);
|
||||
}
|
||||
throw err;
|
||||
});
|
||||
};
|
||||
return FirebaseTokenVerifier;
|
||||
}());
|
||||
exports.FirebaseTokenVerifier = FirebaseTokenVerifier;
|
||||
/**
|
||||
* Creates a new FirebaseTokenVerifier to verify Firebase ID tokens.
|
||||
*
|
||||
* @param {FirebaseApp} app Firebase app instance.
|
||||
* @return {FirebaseTokenVerifier}
|
||||
*/
|
||||
function createIdTokenVerifier(app) {
|
||||
return new FirebaseTokenVerifier(CLIENT_CERT_URL, exports.ALGORITHM_RS256, 'https://securetoken.google.com/', exports.ID_TOKEN_INFO, app);
|
||||
}
|
||||
exports.createIdTokenVerifier = createIdTokenVerifier;
|
||||
/**
|
||||
* Creates a new FirebaseTokenVerifier to verify Firebase session cookies.
|
||||
*
|
||||
* @param {FirebaseApp} app Firebase app instance.
|
||||
* @return {FirebaseTokenVerifier}
|
||||
*/
|
||||
function createSessionCookieVerifier(app) {
|
||||
return new FirebaseTokenVerifier(SESSION_COOKIE_CERT_URL, exports.ALGORITHM_RS256, 'https://session.firebase.google.com/', exports.SESSION_COOKIE_INFO, app);
|
||||
}
|
||||
exports.createSessionCookieVerifier = createSessionCookieVerifier;
|
329
node_modules/firebase-admin/lib/auth/user-import-builder.js
generated
vendored
Normal file
329
node_modules/firebase-admin/lib/auth/user-import-builder.js
generated
vendored
Normal file
@ -0,0 +1,329 @@
|
||||
/*! firebase-admin v8.9.2 */
|
||||
"use strict";
|
||||
/*!
|
||||
* Copyright 2018 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
var deep_copy_1 = require("../utils/deep-copy");
|
||||
var utils = require("../utils");
|
||||
var validator = require("../utils/validator");
|
||||
var error_1 = require("../utils/error");
|
||||
/**
|
||||
* @param {any} obj The object to check for number field within.
|
||||
* @param {string} key The entry key.
|
||||
* @return {number} The corresponding number if available. Otherwise, NaN.
|
||||
*/
|
||||
function getNumberField(obj, key) {
|
||||
if (typeof obj[key] !== 'undefined' && obj[key] !== null) {
|
||||
return parseInt(obj[key].toString(), 10);
|
||||
}
|
||||
return NaN;
|
||||
}
|
||||
/**
|
||||
* Converts a UserImportRecord to a UploadAccountUser object. Throws an error when invalid
|
||||
* fields are provided.
|
||||
* @param {UserImportRecord} user The UserImportRecord to conver to UploadAccountUser.
|
||||
* @param {ValidatorFunction=} userValidator The user validator function.
|
||||
* @return {UploadAccountUser} The corresponding UploadAccountUser to return.
|
||||
*/
|
||||
function populateUploadAccountUser(user, userValidator) {
|
||||
var result = {
|
||||
localId: user.uid,
|
||||
email: user.email,
|
||||
emailVerified: user.emailVerified,
|
||||
displayName: user.displayName,
|
||||
disabled: user.disabled,
|
||||
photoUrl: user.photoURL,
|
||||
phoneNumber: user.phoneNumber,
|
||||
providerUserInfo: [],
|
||||
tenantId: user.tenantId,
|
||||
customAttributes: user.customClaims && JSON.stringify(user.customClaims),
|
||||
};
|
||||
if (typeof user.passwordHash !== 'undefined') {
|
||||
if (!validator.isBuffer(user.passwordHash)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PASSWORD_HASH);
|
||||
}
|
||||
result.passwordHash = utils.toWebSafeBase64(user.passwordHash);
|
||||
}
|
||||
if (typeof user.passwordSalt !== 'undefined') {
|
||||
if (!validator.isBuffer(user.passwordSalt)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_PASSWORD_SALT);
|
||||
}
|
||||
result.salt = utils.toWebSafeBase64(user.passwordSalt);
|
||||
}
|
||||
if (validator.isNonNullObject(user.metadata)) {
|
||||
if (validator.isNonEmptyString(user.metadata.creationTime)) {
|
||||
result.createdAt = new Date(user.metadata.creationTime).getTime();
|
||||
}
|
||||
if (validator.isNonEmptyString(user.metadata.lastSignInTime)) {
|
||||
result.lastLoginAt = new Date(user.metadata.lastSignInTime).getTime();
|
||||
}
|
||||
}
|
||||
if (validator.isArray(user.providerData)) {
|
||||
user.providerData.forEach(function (providerData) {
|
||||
result.providerUserInfo.push({
|
||||
providerId: providerData.providerId,
|
||||
rawId: providerData.uid,
|
||||
email: providerData.email,
|
||||
displayName: providerData.displayName,
|
||||
photoUrl: providerData.photoURL,
|
||||
});
|
||||
});
|
||||
}
|
||||
// Remove blank fields.
|
||||
var key;
|
||||
for (key in result) {
|
||||
if (typeof result[key] === 'undefined') {
|
||||
delete result[key];
|
||||
}
|
||||
}
|
||||
if (result.providerUserInfo.length === 0) {
|
||||
delete result.providerUserInfo;
|
||||
}
|
||||
// Validate the constructured user individual request. This will throw if an error
|
||||
// is detected.
|
||||
if (typeof userValidator === 'function') {
|
||||
userValidator(result);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
/**
|
||||
* Class that provides a helper for building/validating uploadAccount requests and
|
||||
* UserImportResult responses.
|
||||
*/
|
||||
var UserImportBuilder = /** @class */ (function () {
|
||||
/**
|
||||
* @param {UserImportRecord[]} users The list of user records to import.
|
||||
* @param {UserImportOptions=} options The import options which includes hashing
|
||||
* algorithm details.
|
||||
* @param {ValidatorFunction=} userRequestValidator The user request validator function.
|
||||
* @constructor
|
||||
*/
|
||||
function UserImportBuilder(users, options, userRequestValidator) {
|
||||
this.requiresHashOptions = false;
|
||||
this.validatedUsers = [];
|
||||
this.userImportResultErrors = [];
|
||||
this.indexMap = {};
|
||||
this.validatedUsers = this.populateUsers(users, userRequestValidator);
|
||||
this.validatedOptions = this.populateOptions(options, this.requiresHashOptions);
|
||||
}
|
||||
/**
|
||||
* Returns the corresponding constructed uploadAccount request.
|
||||
* @return {UploadAccountRequest} The constructed uploadAccount request.
|
||||
*/
|
||||
UserImportBuilder.prototype.buildRequest = function () {
|
||||
var users = this.validatedUsers.map(function (user) {
|
||||
return deep_copy_1.deepCopy(user);
|
||||
});
|
||||
return deep_copy_1.deepExtend({ users: users }, deep_copy_1.deepCopy(this.validatedOptions));
|
||||
};
|
||||
/**
|
||||
* Populates the UserImportResult using the client side detected errors and the server
|
||||
* side returned errors.
|
||||
* @return {UserImportResult} The user import result based on the returned failed
|
||||
* uploadAccount response.
|
||||
*/
|
||||
UserImportBuilder.prototype.buildResponse = function (failedUploads) {
|
||||
var _this = this;
|
||||
// Initialize user import result.
|
||||
var importResult = {
|
||||
successCount: this.validatedUsers.length,
|
||||
failureCount: this.userImportResultErrors.length,
|
||||
errors: deep_copy_1.deepCopy(this.userImportResultErrors),
|
||||
};
|
||||
importResult.failureCount += failedUploads.length;
|
||||
importResult.successCount -= failedUploads.length;
|
||||
failedUploads.forEach(function (failedUpload) {
|
||||
importResult.errors.push({
|
||||
// Map backend request index to original developer provided array index.
|
||||
index: _this.indexMap[failedUpload.index],
|
||||
error: new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_USER_IMPORT, failedUpload.message),
|
||||
});
|
||||
});
|
||||
// Sort errors by index.
|
||||
importResult.errors.sort(function (a, b) {
|
||||
return a.index - b.index;
|
||||
});
|
||||
// Return sorted result.
|
||||
return importResult;
|
||||
};
|
||||
/**
|
||||
* Validates and returns the hashing options of the uploadAccount request.
|
||||
* Throws an error whenever an invalid or missing options is detected.
|
||||
* @param {UserImportOptions} options The UserImportOptions.
|
||||
* @param {boolean} requiresHashOptions Whether to require hash options.
|
||||
* @return {UploadAccountOptions} The populated UploadAccount options.
|
||||
*/
|
||||
UserImportBuilder.prototype.populateOptions = function (options, requiresHashOptions) {
|
||||
var populatedOptions;
|
||||
if (!requiresHashOptions) {
|
||||
return {};
|
||||
}
|
||||
if (!validator.isNonNullObject(options)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, '"UserImportOptions" are required when importing users with passwords.');
|
||||
}
|
||||
if (!validator.isNonNullObject(options.hash)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.MISSING_HASH_ALGORITHM, "\"hash.algorithm\" is missing from the provided \"UserImportOptions\".");
|
||||
}
|
||||
if (typeof options.hash.algorithm === 'undefined' ||
|
||||
!validator.isNonEmptyString(options.hash.algorithm)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_ALGORITHM, "\"hash.algorithm\" must be a string matching the list of supported algorithms.");
|
||||
}
|
||||
var rounds;
|
||||
switch (options.hash.algorithm) {
|
||||
case 'HMAC_SHA512':
|
||||
case 'HMAC_SHA256':
|
||||
case 'HMAC_SHA1':
|
||||
case 'HMAC_MD5':
|
||||
if (!validator.isBuffer(options.hash.key)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_KEY, "A non-empty \"hash.key\" byte buffer must be provided for " +
|
||||
("hash algorithm " + options.hash.algorithm + "."));
|
||||
}
|
||||
populatedOptions = {
|
||||
hashAlgorithm: options.hash.algorithm,
|
||||
signerKey: utils.toWebSafeBase64(options.hash.key),
|
||||
};
|
||||
break;
|
||||
case 'MD5':
|
||||
case 'SHA1':
|
||||
case 'SHA256':
|
||||
case 'SHA512':
|
||||
// MD5 is [0,8192] but SHA1, SHA256, and SHA512 are [1,8192]
|
||||
rounds = getNumberField(options.hash, 'rounds');
|
||||
var minRounds = options.hash.algorithm === 'MD5' ? 0 : 1;
|
||||
if (isNaN(rounds) || rounds < minRounds || rounds > 8192) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_ROUNDS, "A valid \"hash.rounds\" number between " + minRounds + " and 8192 must be provided for " +
|
||||
("hash algorithm " + options.hash.algorithm + "."));
|
||||
}
|
||||
populatedOptions = {
|
||||
hashAlgorithm: options.hash.algorithm,
|
||||
rounds: rounds,
|
||||
};
|
||||
break;
|
||||
case 'PBKDF_SHA1':
|
||||
case 'PBKDF2_SHA256':
|
||||
rounds = getNumberField(options.hash, 'rounds');
|
||||
if (isNaN(rounds) || rounds < 0 || rounds > 120000) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_ROUNDS, "A valid \"hash.rounds\" number between 0 and 120000 must be provided for " +
|
||||
("hash algorithm " + options.hash.algorithm + "."));
|
||||
}
|
||||
populatedOptions = {
|
||||
hashAlgorithm: options.hash.algorithm,
|
||||
rounds: rounds,
|
||||
};
|
||||
break;
|
||||
case 'SCRYPT':
|
||||
if (!validator.isBuffer(options.hash.key)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_KEY, "A \"hash.key\" byte buffer must be provided for " +
|
||||
("hash algorithm " + options.hash.algorithm + "."));
|
||||
}
|
||||
rounds = getNumberField(options.hash, 'rounds');
|
||||
if (isNaN(rounds) || rounds <= 0 || rounds > 8) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_ROUNDS, "A valid \"hash.rounds\" number between 1 and 8 must be provided for " +
|
||||
("hash algorithm " + options.hash.algorithm + "."));
|
||||
}
|
||||
var memoryCost = getNumberField(options.hash, 'memoryCost');
|
||||
if (isNaN(memoryCost) || memoryCost <= 0 || memoryCost > 14) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_MEMORY_COST, "A valid \"hash.memoryCost\" number between 1 and 14 must be provided for " +
|
||||
("hash algorithm " + options.hash.algorithm + "."));
|
||||
}
|
||||
if (typeof options.hash.saltSeparator !== 'undefined' &&
|
||||
!validator.isBuffer(options.hash.saltSeparator)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_SALT_SEPARATOR, "\"hash.saltSeparator\" must be a byte buffer.");
|
||||
}
|
||||
populatedOptions = {
|
||||
hashAlgorithm: options.hash.algorithm,
|
||||
signerKey: utils.toWebSafeBase64(options.hash.key),
|
||||
rounds: rounds,
|
||||
memoryCost: memoryCost,
|
||||
saltSeparator: utils.toWebSafeBase64(options.hash.saltSeparator || Buffer.from('')),
|
||||
};
|
||||
break;
|
||||
case 'BCRYPT':
|
||||
populatedOptions = {
|
||||
hashAlgorithm: options.hash.algorithm,
|
||||
};
|
||||
break;
|
||||
case 'STANDARD_SCRYPT':
|
||||
var cpuMemCost = getNumberField(options.hash, 'memoryCost');
|
||||
if (isNaN(cpuMemCost)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_MEMORY_COST, "A valid \"hash.memoryCost\" number must be provided for " +
|
||||
("hash algorithm " + options.hash.algorithm + "."));
|
||||
}
|
||||
var parallelization = getNumberField(options.hash, 'parallelization');
|
||||
if (isNaN(parallelization)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_PARALLELIZATION, "A valid \"hash.parallelization\" number must be provided for " +
|
||||
("hash algorithm " + options.hash.algorithm + "."));
|
||||
}
|
||||
var blockSize = getNumberField(options.hash, 'blockSize');
|
||||
if (isNaN(blockSize)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_BLOCK_SIZE, "A valid \"hash.blockSize\" number must be provided for " +
|
||||
("hash algorithm " + options.hash.algorithm + "."));
|
||||
}
|
||||
var dkLen = getNumberField(options.hash, 'derivedKeyLength');
|
||||
if (isNaN(dkLen)) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_DERIVED_KEY_LENGTH, "A valid \"hash.derivedKeyLength\" number must be provided for " +
|
||||
("hash algorithm " + options.hash.algorithm + "."));
|
||||
}
|
||||
populatedOptions = {
|
||||
hashAlgorithm: options.hash.algorithm,
|
||||
cpuMemCost: cpuMemCost,
|
||||
parallelization: parallelization,
|
||||
blockSize: blockSize,
|
||||
dkLen: dkLen,
|
||||
};
|
||||
break;
|
||||
default:
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_HASH_ALGORITHM, "Unsupported hash algorithm provider \"" + options.hash.algorithm + "\".");
|
||||
}
|
||||
return populatedOptions;
|
||||
};
|
||||
/**
|
||||
* Validates and returns the users list of the uploadAccount request.
|
||||
* Whenever a user with an error is detected, the error is cached and will later be
|
||||
* merged into the user import result. This allows the processing of valid users without
|
||||
* failing early on the first error detected.
|
||||
* @param {UserImportRecord[]} users The UserImportRecords to convert to UnploadAccountUser
|
||||
* objects.
|
||||
* @param {ValidatorFunction=} userValidator The user validator function.
|
||||
* @return {UploadAccountUser[]} The populated uploadAccount users.
|
||||
*/
|
||||
UserImportBuilder.prototype.populateUsers = function (users, userValidator) {
|
||||
var _this = this;
|
||||
var populatedUsers = [];
|
||||
users.forEach(function (user, index) {
|
||||
try {
|
||||
var result = populateUploadAccountUser(user, userValidator);
|
||||
if (typeof result.passwordHash !== 'undefined') {
|
||||
_this.requiresHashOptions = true;
|
||||
}
|
||||
// Only users that pass client screening will be passed to backend for processing.
|
||||
populatedUsers.push(result);
|
||||
// Map user's index (the one to be sent to backend) to original developer provided array.
|
||||
_this.indexMap[populatedUsers.length - 1] = index;
|
||||
}
|
||||
catch (error) {
|
||||
// Save the client side error with respect to the developer provided array.
|
||||
_this.userImportResultErrors.push({
|
||||
index: index,
|
||||
error: error,
|
||||
});
|
||||
}
|
||||
});
|
||||
return populatedUsers;
|
||||
};
|
||||
return UserImportBuilder;
|
||||
}());
|
||||
exports.UserImportBuilder = UserImportBuilder;
|
188
node_modules/firebase-admin/lib/auth/user-record.js
generated
vendored
Normal file
188
node_modules/firebase-admin/lib/auth/user-record.js
generated
vendored
Normal file
@ -0,0 +1,188 @@
|
||||
/*! firebase-admin v8.9.2 */
|
||||
"use strict";
|
||||
/*!
|
||||
* Copyright 2017 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
var deep_copy_1 = require("../utils/deep-copy");
|
||||
var utils = require("../utils");
|
||||
var error_1 = require("../utils/error");
|
||||
/**
|
||||
* 'REDACTED', encoded as a base64 string.
|
||||
*/
|
||||
var B64_REDACTED = Buffer.from('REDACTED').toString('base64');
|
||||
/**
|
||||
* Parses a time stamp string or number and returns the corresponding date if valid.
|
||||
*
|
||||
* @param {any} time The unix timestamp string or number in milliseconds.
|
||||
* @return {string} The corresponding date as a UTC string, if valid. Otherwise, null.
|
||||
*/
|
||||
function parseDate(time) {
|
||||
try {
|
||||
var date = new Date(parseInt(time, 10));
|
||||
if (!isNaN(date.getTime())) {
|
||||
return date.toUTCString();
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
// Do nothing. null will be returned.
|
||||
}
|
||||
return null;
|
||||
}
|
||||
/**
|
||||
* User metadata class that provides metadata information like user account creation
|
||||
* and last sign in time.
|
||||
*
|
||||
* @param {object} response The server side response returned from the getAccountInfo
|
||||
* endpoint.
|
||||
* @constructor
|
||||
*/
|
||||
var UserMetadata = /** @class */ (function () {
|
||||
function UserMetadata(response) {
|
||||
// Creation date should always be available but due to some backend bugs there
|
||||
// were cases in the past where users did not have creation date properly set.
|
||||
// This included legacy Firebase migrating project users and some anonymous users.
|
||||
// These bugs have already been addressed since then.
|
||||
utils.addReadonlyGetter(this, 'creationTime', parseDate(response.createdAt));
|
||||
utils.addReadonlyGetter(this, 'lastSignInTime', parseDate(response.lastLoginAt));
|
||||
}
|
||||
/** @return {object} The plain object representation of the user's metadata. */
|
||||
UserMetadata.prototype.toJSON = function () {
|
||||
return {
|
||||
lastSignInTime: this.lastSignInTime,
|
||||
creationTime: this.creationTime,
|
||||
};
|
||||
};
|
||||
return UserMetadata;
|
||||
}());
|
||||
exports.UserMetadata = UserMetadata;
|
||||
/**
|
||||
* User info class that provides provider user information for different
|
||||
* Firebase providers like google.com, facebook.com, password, etc.
|
||||
*
|
||||
* @param {object} response The server side response returned from the getAccountInfo
|
||||
* endpoint.
|
||||
* @constructor
|
||||
*/
|
||||
var UserInfo = /** @class */ (function () {
|
||||
function UserInfo(response) {
|
||||
// Provider user id and provider id are required.
|
||||
if (!response.rawId || !response.providerId) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid user info response');
|
||||
}
|
||||
utils.addReadonlyGetter(this, 'uid', response.rawId);
|
||||
utils.addReadonlyGetter(this, 'displayName', response.displayName);
|
||||
utils.addReadonlyGetter(this, 'email', response.email);
|
||||
utils.addReadonlyGetter(this, 'photoURL', response.photoUrl);
|
||||
utils.addReadonlyGetter(this, 'providerId', response.providerId);
|
||||
utils.addReadonlyGetter(this, 'phoneNumber', response.phoneNumber);
|
||||
}
|
||||
/** @return {object} The plain object representation of the current provider data. */
|
||||
UserInfo.prototype.toJSON = function () {
|
||||
return {
|
||||
uid: this.uid,
|
||||
displayName: this.displayName,
|
||||
email: this.email,
|
||||
photoURL: this.photoURL,
|
||||
providerId: this.providerId,
|
||||
phoneNumber: this.phoneNumber,
|
||||
};
|
||||
};
|
||||
return UserInfo;
|
||||
}());
|
||||
exports.UserInfo = UserInfo;
|
||||
/**
|
||||
* User record class that defines the Firebase user object populated from
|
||||
* the Firebase Auth getAccountInfo response.
|
||||
*
|
||||
* @param {any} response The server side response returned from the getAccountInfo
|
||||
* endpoint.
|
||||
* @constructor
|
||||
*/
|
||||
var UserRecord = /** @class */ (function () {
|
||||
function UserRecord(response) {
|
||||
// The Firebase user id is required.
|
||||
if (!response.localId) {
|
||||
throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid user response');
|
||||
}
|
||||
utils.addReadonlyGetter(this, 'uid', response.localId);
|
||||
utils.addReadonlyGetter(this, 'email', response.email);
|
||||
utils.addReadonlyGetter(this, 'emailVerified', !!response.emailVerified);
|
||||
utils.addReadonlyGetter(this, 'displayName', response.displayName);
|
||||
utils.addReadonlyGetter(this, 'photoURL', response.photoUrl);
|
||||
utils.addReadonlyGetter(this, 'phoneNumber', response.phoneNumber);
|
||||
// If disabled is not provided, the account is enabled by default.
|
||||
utils.addReadonlyGetter(this, 'disabled', response.disabled || false);
|
||||
utils.addReadonlyGetter(this, 'metadata', new UserMetadata(response));
|
||||
var providerData = [];
|
||||
for (var _i = 0, _a = (response.providerUserInfo || []); _i < _a.length; _i++) {
|
||||
var entry = _a[_i];
|
||||
providerData.push(new UserInfo(entry));
|
||||
}
|
||||
utils.addReadonlyGetter(this, 'providerData', providerData);
|
||||
// If the password hash is redacted (probably due to missing permissions)
|
||||
// then clear it out, similar to how the salt is returned. (Otherwise, it
|
||||
// *looks* like a b64-encoded hash is present, which is confusing.)
|
||||
if (response.passwordHash === B64_REDACTED) {
|
||||
utils.addReadonlyGetter(this, 'passwordHash', undefined);
|
||||
}
|
||||
else {
|
||||
utils.addReadonlyGetter(this, 'passwordHash', response.passwordHash);
|
||||
}
|
||||
utils.addReadonlyGetter(this, 'passwordSalt', response.salt);
|
||||
try {
|
||||
utils.addReadonlyGetter(this, 'customClaims', JSON.parse(response.customAttributes));
|
||||
}
|
||||
catch (e) {
|
||||
// Ignore error.
|
||||
utils.addReadonlyGetter(this, 'customClaims', undefined);
|
||||
}
|
||||
var validAfterTime = null;
|
||||
// Convert validSince first to UTC milliseconds and then to UTC date string.
|
||||
if (typeof response.validSince !== 'undefined') {
|
||||
validAfterTime = parseDate(response.validSince * 1000);
|
||||
}
|
||||
utils.addReadonlyGetter(this, 'tokensValidAfterTime', validAfterTime || undefined);
|
||||
utils.addReadonlyGetter(this, 'tenantId', response.tenantId);
|
||||
}
|
||||
/** @return {object} The plain object representation of the user record. */
|
||||
UserRecord.prototype.toJSON = function () {
|
||||
var json = {
|
||||
uid: this.uid,
|
||||
email: this.email,
|
||||
emailVerified: this.emailVerified,
|
||||
displayName: this.displayName,
|
||||
photoURL: this.photoURL,
|
||||
phoneNumber: this.phoneNumber,
|
||||
disabled: this.disabled,
|
||||
// Convert metadata to json.
|
||||
metadata: this.metadata.toJSON(),
|
||||
passwordHash: this.passwordHash,
|
||||
passwordSalt: this.passwordSalt,
|
||||
customClaims: deep_copy_1.deepCopy(this.customClaims),
|
||||
tokensValidAfterTime: this.tokensValidAfterTime,
|
||||
tenantId: this.tenantId,
|
||||
};
|
||||
json.providerData = [];
|
||||
for (var _i = 0, _a = this.providerData; _i < _a.length; _i++) {
|
||||
var entry = _a[_i];
|
||||
// Convert each provider data to json.
|
||||
json.providerData.push(entry.toJSON());
|
||||
}
|
||||
return json;
|
||||
};
|
||||
return UserRecord;
|
||||
}());
|
||||
exports.UserRecord = UserRecord;
|
Reference in New Issue
Block a user