/*! @azure/msal-common v11.0.0 2023-03-07 */
'use strict';
import { CredentialType, CacheType, Constants, Separators, AuthenticationScheme } from '../../utils/Constants.js';
import { ClientAuthError } from '../../error/ClientAuthError.js';

/*
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License.
 */
/**
 * Base type for credentials to be stored in the cache: eg: ACCESS_TOKEN, ID_TOKEN etc
 *
 * Key:Value Schema:
 *
 * Key: <home_account_id*>-<environment>-<credential_type>-<client_id>-<realm*>-<target*>-<requestedClaims*>-<scheme*>
 *
 * Value Schema:
 * {
 *      homeAccountId: home account identifier for the auth scheme,
 *      environment: entity that issued the token, represented as a full host
 *      credentialType: Type of credential as a string, can be one of the following: RefreshToken, AccessToken, IdToken, Password, Cookie, Certificate, Other
 *      clientId: client ID of the application
 *      secret: Actual credential as a string
 *      familyId: Family ID identifier, usually only used for refresh tokens
 *      realm: Full tenant or organizational identifier that the account belongs to
 *      target: Permissions that are included in the token, or for refresh tokens, the resource identifier.
 *      tokenType: Matches the authentication scheme for which the token was issued (i.e. Bearer or pop)
 *      requestedClaimsHash: Matches the SHA 256 hash of the claims object included in the token request
 *      userAssertionHash: Matches the SHA 256 hash of the obo_assertion for the OBO flow
 * }
 */
var CredentialEntity = /** @class */ (function () {
    function CredentialEntity() {
    }
    /**
     * Initializes a map with credential {CredentialType} regular expressions.
     */
    CredentialEntity._initRegex = function () {
        var separator = Separators.CACHE_KEY_SEPARATOR;
        CredentialEntity.credentialRegexMap = new Map();
        for (var _i = 0, _a = Object.keys(CredentialType); _i < _a.length; _i++) {
            var credKey = _a[_i];
            var credVal = CredentialType[credKey].toLowerCase();
            try {
                // Verify credential type is preceded by a valid host name (environment) using lookbehind
                CredentialEntity.credentialRegexMap.set(CredentialType[credKey], new RegExp("(?<=" + separator + CredentialEntity.credentialDomainRegex + ")" + separator + credVal + separator));
            }
            catch (err) {
                // Lookbehind is not supported (Safari or older versions of IE) - removing it
                CredentialEntity.credentialRegexMap.set(CredentialType[credKey], new RegExp("" + separator + CredentialEntity.credentialDomainRegex + separator + credVal + separator));
            }
        }
    };
    /**
     * Generate Account Id key component as per the schema: <home_account_id>-<environment>
     */
    CredentialEntity.prototype.generateAccountId = function () {
        return CredentialEntity.generateAccountIdForCacheKey(this.homeAccountId, this.environment);
    };
    /**
     * Generate Credential Id key component as per the schema: <credential_type>-<client_id>-<realm>
     */
    CredentialEntity.prototype.generateCredentialId = function () {
        return CredentialEntity.generateCredentialIdForCacheKey(this.credentialType, this.clientId, this.realm, this.familyId);
    };
    /**
     * Generate target key component as per schema: <target>
     */
    CredentialEntity.prototype.generateTarget = function () {
        return CredentialEntity.generateTargetForCacheKey(this.target);
    };
    /**
     * generates credential key
     */
    CredentialEntity.prototype.generateCredentialKey = function () {
        return CredentialEntity.generateCredentialCacheKey(this.homeAccountId, this.environment, this.credentialType, this.clientId, this.realm, this.target, this.familyId, this.tokenType, this.requestedClaimsHash);
    };
    /**
     * returns the type of the cache (in this case credential)
     */
    CredentialEntity.prototype.generateType = function () {
        switch (this.credentialType) {
            case CredentialType.ID_TOKEN:
                return CacheType.ID_TOKEN;
            case CredentialType.ACCESS_TOKEN:
            case CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME:
                return CacheType.ACCESS_TOKEN;
            case CredentialType.REFRESH_TOKEN:
                return CacheType.REFRESH_TOKEN;
            default: {
                throw ClientAuthError.createUnexpectedCredentialTypeError();
            }
        }
    };
    /**
     * helper function to return `CredentialType`
     * @param key
     */
    CredentialEntity.getCredentialType = function (key) {
        var _a;
        for (var _i = 0, _b = Object.keys(CredentialType); _i < _b.length; _i++) {
            var credKey = _b[_i];
            if ((_a = this.credentialRegexMap.get(CredentialType[credKey])) === null || _a === void 0 ? void 0 : _a.test(key.toLowerCase())) {
                return CredentialType[credKey];
            }
        }
        return Constants.NOT_DEFINED;
    };
    /**
     * generates credential key
     * <home_account_id*>-\<environment>-<credential_type>-<client_id>-<realm\*>-<target\*>-<scheme\*>
     */
    CredentialEntity.generateCredentialCacheKey = function (homeAccountId, environment, credentialType, clientId, realm, target, familyId, tokenType, requestedClaimsHash) {
        var credentialKey = [
            this.generateAccountIdForCacheKey(homeAccountId, environment),
            this.generateCredentialIdForCacheKey(credentialType, clientId, realm, familyId),
            this.generateTargetForCacheKey(target),
            this.generateClaimsHashForCacheKey(requestedClaimsHash),
            this.generateSchemeForCacheKey(tokenType)
        ];
        return credentialKey.join(Separators.CACHE_KEY_SEPARATOR).toLowerCase();
    };
    /**
     * generates Account Id for keys
     * @param homeAccountId
     * @param environment
     */
    CredentialEntity.generateAccountIdForCacheKey = function (homeAccountId, environment) {
        var accountId = [homeAccountId, environment];
        return accountId.join(Separators.CACHE_KEY_SEPARATOR).toLowerCase();
    };
    /**
     * Generates Credential Id for keys
     * @param credentialType
     * @param realm
     * @param clientId
     * @param familyId
     */
    CredentialEntity.generateCredentialIdForCacheKey = function (credentialType, clientId, realm, familyId) {
        var clientOrFamilyId = credentialType === CredentialType.REFRESH_TOKEN
            ? familyId || clientId
            : clientId;
        var credentialId = [
            credentialType,
            clientOrFamilyId,
            realm || Constants.EMPTY_STRING,
        ];
        return credentialId.join(Separators.CACHE_KEY_SEPARATOR).toLowerCase();
    };
    /**
     * Generate target key component as per schema: <target>
     */
    CredentialEntity.generateTargetForCacheKey = function (scopes) {
        return (scopes || Constants.EMPTY_STRING).toLowerCase();
    };
    /**
     * Generate requested claims key component as per schema: <requestedClaims>
     */
    CredentialEntity.generateClaimsHashForCacheKey = function (requestedClaimsHash) {
        return (requestedClaimsHash || Constants.EMPTY_STRING).toLowerCase();
    };
    /**
     * Generate scheme key componenet as per schema: <scheme>
     */
    CredentialEntity.generateSchemeForCacheKey = function (tokenType) {
        /*
         * PoP Tokens and SSH certs include scheme in cache key
         * Cast to lowercase to handle "bearer" from ADFS
         */
        return (tokenType && tokenType.toLowerCase() !== AuthenticationScheme.BEARER.toLowerCase()) ? tokenType.toLowerCase() : Constants.EMPTY_STRING;
    };
    /*
     * Match host names like "login.microsoftonline.com", "https://accounts.google.com:4000", https://localhost:5000,
     * "login.microsoftonline.com/common", "login.microsoftonline.com:4000/common", etc
     */
    CredentialEntity.credentialDomainRegex = "(https?:\\/\\/)?((([\\w-]+\\.)*([\\w-]{1,63})(\\.(\\w{2,63})))|(localhost))(\\:[0-9]{4,5})?(\\/[\\w-]+)?";
    return CredentialEntity;
}());
CredentialEntity._initRegex();

export { CredentialEntity };
//# sourceMappingURL=CredentialEntity.js.map
