UNPKG

@azure/msal-browser

Version:
1,220 lines (1,194 loc) 363 kB
/*! @azure/msal-browser v2.2.0 2020-09-18 */ 'use strict'; 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. 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 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /* global Reflect, Promise */ 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); }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function __awaiter(thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } function __spreadArrays() { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; } /*! @azure/msal-common v1.3.0 2020-09-18 */ /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. 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 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics$1 = function(d, b) { extendStatics$1 = 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$1(d, b); }; function __extends$1(d, b) { extendStatics$1(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign$1 = function() { __assign$1 = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign$1.apply(this, arguments); }; function __awaiter$1(thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator$1(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } function __spreadArrays$1() { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; } /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ /** * AuthErrorMessage class containing string constants used by error codes and messages. */ var AuthErrorMessage = { unexpectedError: { code: "unexpected_error", desc: "Unexpected error in authentication." } }; /** * General error class thrown by the MSAL.js library. */ var AuthError = /** @class */ (function (_super) { __extends$1(AuthError, _super); function AuthError(errorCode, errorMessage, suberror) { var _this = this; var errorString = errorMessage ? errorCode + ": " + errorMessage : errorCode; _this = _super.call(this, errorString) || this; Object.setPrototypeOf(_this, AuthError.prototype); _this.errorCode = errorCode; _this.errorMessage = errorMessage; _this.suberror = suberror; _this.name = "AuthError"; return _this; } /** * Creates an error that is thrown when something unexpected happens in the library. * @param errDesc */ AuthError.createUnexpectedError = function (errDesc) { return new AuthError(AuthErrorMessage.unexpectedError.code, AuthErrorMessage.unexpectedError.desc + ": " + errDesc); }; return AuthError; }(Error)); var name = "@azure/msal-common"; var author = { name: "Microsoft", email: "nugetaad@microsoft.com", url: "https://www.microsoft.com" }; var license = "MIT"; var repository = { type: "git", url: "https://github.com/AzureAD/microsoft-authentication-library-for-js.git" }; var version = "1.3.0"; var description = "Microsoft Authentication Library for js"; var keywords = [ "implicit", "authorization code", "PKCE", "js", "AAD", "msal", "oauth" ]; var main = "./dist/index.js"; var module$1 = "./dist/index.es.js"; var types = "./dist/src/index.d.ts"; var browserslist = [ "last 1 version", "> 1%", "maintained node versions", "not dead" ]; var engines = { node: ">=0.8.0" }; var directories = { test: "test" }; var files = [ "dist" ]; var scripts = { clean: "shx rm -rf dist lib", "clean:coverage": "rimraf ../../.nyc_output/*", doc: "npm run doc:generate && npm run doc:deploy", "doc:generate": "typedoc --mode modules --excludePrivate --excludeProtected --excludeNotExported --out ./ref ./src/ --gitRevision dev", "doc:deploy": "gh-pages -d ref -a -e ref/msal-common", lint: "cd ../../ && npm run lint:common", "lint:fix": "npm run lint -- -- --fix", test: "mocha", "test:coverage": "nyc --reporter=text mocha --exit", "test:coverage:only": "npm run clean:coverage && npm run test:coverage", "build:modules": "rollup -c", "build:modules:watch": "rollup -cw", build: "npm run clean && npm run build:modules", prepack: "npm run build" }; var devDependencies = { "@babel/core": "^7.7.2", "@babel/plugin-proposal-class-properties": "^7.7.0", "@babel/plugin-proposal-object-rest-spread": "^7.6.2", "@babel/polyfill": "^7.7.0", "@babel/preset-env": "^7.7.1", "@babel/preset-typescript": "^7.7.2", "@babel/register": "^7.7.0", "@istanbuljs/nyc-config-babel": "^2.1.1", "@rollup/plugin-json": "^4.0.0", "@types/chai": "^4.2.5", "@types/chai-as-promised": "^7.1.2", "@types/debug": "^4.1.5", "@types/mocha": "^5.2.7", "@types/sinon": "^7.5.0", "babel-plugin-istanbul": "^5.2.0", beachball: "^1.32.2", chai: "^4.2.0", "chai-as-promised": "^7.1.1", "gh-pages": "^3.1.0", husky: "^3.0.9", mocha: "^6.2.2", nyc: "^14.1.1", rimraf: "^3.0.2", rollup: "^1.24.0", "rollup-plugin-typescript2": "^0.24.3", "rollup-plugin-uglify": "^6.0.4", shx: "^0.3.2", sinon: "^7.5.0", tslib: "^1.10.0", tslint: "^5.20.0", typedoc: "^0.17.8", typescript: "^3.7.5" }; var dependencies = { debug: "^4.1.1" }; var pkg = { name: name, author: author, license: license, repository: repository, version: version, description: description, keywords: keywords, main: main, module: module$1, types: types, browserslist: browserslist, engines: engines, directories: directories, files: files, scripts: scripts, devDependencies: devDependencies, dependencies: dependencies }; /** * ClientAuthErrorMessage class containing string constants used by error codes and messages. */ var ClientAuthErrorMessage = { clientInfoDecodingError: { code: "client_info_decoding_error", desc: "The client info could not be parsed/decoded correctly. Please review the trace to determine the root cause." }, clientInfoEmptyError: { code: "client_info_empty_error", desc: "The client info was empty. Please review the trace to determine the root cause." }, idTokenParsingError: { code: "id_token_parsing_error", desc: "ID token cannot be parsed. Please review stack trace to determine root cause." }, nullOrEmptyIdToken: { code: "null_or_empty_id_token", desc: "The idToken is null or empty. Please review the trace to determine the root cause." }, endpointResolutionError: { code: "endpoints_resolution_error", desc: "Error: could not resolve endpoints. Please check network and try again." }, invalidAuthorityType: { code: "invalid_authority_type", desc: "The given authority is not a valid type of authority supported by MSAL. Please review the trace to determine the root cause." }, hashNotDeserialized: { code: "hash_not_deserialized", desc: "The hash parameters could not be deserialized. Please review the trace to determine the root cause." }, blankGuidGenerated: { code: "blank_guid_generated", desc: "The guid generated was blank. Please review the trace to determine the root cause." }, invalidStateError: { code: "invalid_state", desc: "State was not the expected format. Please check the logs to determine whether the request was sent using ProtocolUtils.setRequestState()." }, stateMismatchError: { code: "state_mismatch", desc: "State mismatch error. Please check your network. Continued requests may cause cache overflow." }, nonceMismatchError: { code: "nonce_mismatch", desc: "Nonce mismatch error. This may be caused by a race condition in concurrent requests." }, accountMismatchError: { code: "account_mismatch", desc: "The cached account and account which made the token request do not match." }, invalidIdToken: { code: "invalid_id_token", desc: "Invalid ID token format." }, noTokensFoundError: { code: "no_tokens_found", desc: "No tokens were found for the given scopes, and no authorization code was passed to acquireToken. You must retrieve an authorization code before making a call to acquireToken()." }, cacheParseError: { code: "cache_parse_error", desc: "Could not parse cache key." }, userLoginRequiredError: { code: "user_login_error", desc: "User login is required." }, multipleMatchingTokens: { code: "multiple_matching_tokens", desc: "The cache contains multiple tokens satisfying the requirements. " + "Call AcquireToken again providing more requirements such as authority or account." }, multipleMatchingAccounts: { code: "multiple_matching_accounts", desc: "The cache contains multiple accounts satisfying the given parameters. Please pass more info to obtain the correct account" }, tokenRequestCannotBeMade: { code: "request_cannot_be_made", desc: "Token request cannot be made without authorization code or refresh token." }, appendEmptyScopeError: { code: "cannot_append_empty_scope", desc: "Cannot append null or empty scope to ScopeSet. Please check the stack trace for more info." }, removeEmptyScopeError: { code: "cannot_remove_empty_scope", desc: "Cannot remove null or empty scope from ScopeSet. Please check the stack trace for more info." }, appendScopeSetError: { code: "cannot_append_scopeset", desc: "Cannot append ScopeSet due to error." }, emptyInputScopeSetError: { code: "empty_input_scopeset", desc: "Empty input ScopeSet cannot be processed." }, DeviceCodePollingCancelled: { code: "device_code_polling_cancelled", desc: "Caller has cancelled token endpoint polling during device code flow by setting DeviceCodeRequest.cancel = true." }, DeviceCodeExpired: { code: "device_code_expired", desc: "Device code is expired." }, NoAccountInSilentRequest: { code: "no_account_in_silent_request", desc: "Please pass an account object, silent flow is not supported without account information" }, invalidCacheRecord: { code: "invalid_cache_record", desc: "Cache record object was null or undefined." }, invalidCacheEnvironment: { code: "invalid_cache_environment", desc: "Invalid environment when attempting to create cache entry" }, noAccountFound: { code: "no_account_found", desc: "No account found in cache for given key." }, CachePluginError: { code: "no cache plugin set on CacheManager", desc: "ICachePlugin needs to be set before using readFromStorage or writeFromStorage" }, noCryptoObj: { code: "no_crypto_object", desc: "No crypto object detected. This is required for the following operation: " }, invalidCacheType: { code: "invalid_cache_type", desc: "Invalid cache type" }, unexpectedAccountType: { code: "unexpected_account_type", desc: "Unexpected account type." }, unexpectedCredentialType: { code: "unexpected_credential_type", desc: "Unexpected credential type." }, invalidAssertion: { code: "invalid_assertion", desc: "Client assertion must meet requirements described in https://tools.ietf.org/html/rfc7515" }, invalidClientCredential: { code: "invalid_client_credential", desc: "Client credential (secret, certificate, or assertion) must not be empty when creating a confidential client. An application should at most have one credential" }, tokenRefreshRequired: { code: "token_refresh_required", desc: "Cannot return token from cache because it must be refreshed. This may be due to one of the following reasons: forceRefresh parameter is set to true, claims have been requested, there is no cached access token or it is expired." } }; /** * Error thrown when there is an error in the client code running on the browser. */ var ClientAuthError = /** @class */ (function (_super) { __extends$1(ClientAuthError, _super); function ClientAuthError(errorCode, errorMessage) { var _this = _super.call(this, errorCode, errorMessage) || this; _this.name = "ClientAuthError"; Object.setPrototypeOf(_this, ClientAuthError.prototype); return _this; } /** * Creates an error thrown when client info object doesn't decode correctly. * @param caughtError */ ClientAuthError.createClientInfoDecodingError = function (caughtError) { return new ClientAuthError(ClientAuthErrorMessage.clientInfoDecodingError.code, ClientAuthErrorMessage.clientInfoDecodingError.desc + " Failed with error: " + caughtError); }; /** * Creates an error thrown if the client info is empty. * @param rawClientInfo */ ClientAuthError.createClientInfoEmptyError = function (rawClientInfo) { return new ClientAuthError(ClientAuthErrorMessage.clientInfoEmptyError.code, ClientAuthErrorMessage.clientInfoEmptyError.desc + " Given Object: " + rawClientInfo); }; /** * Creates an error thrown when the id token extraction errors out. * @param err */ ClientAuthError.createIdTokenParsingError = function (caughtExtractionError) { return new ClientAuthError(ClientAuthErrorMessage.idTokenParsingError.code, ClientAuthErrorMessage.idTokenParsingError.desc + " Failed with error: " + caughtExtractionError); }; /** * Creates an error thrown when the id token string is null or empty. * @param invalidRawTokenString */ ClientAuthError.createIdTokenNullOrEmptyError = function (invalidRawTokenString) { return new ClientAuthError(ClientAuthErrorMessage.nullOrEmptyIdToken.code, ClientAuthErrorMessage.nullOrEmptyIdToken.desc + " Raw ID Token Value: " + invalidRawTokenString); }; /** * Creates an error thrown when the endpoint discovery doesn't complete correctly. */ ClientAuthError.createEndpointDiscoveryIncompleteError = function (errDetail) { return new ClientAuthError(ClientAuthErrorMessage.endpointResolutionError.code, ClientAuthErrorMessage.endpointResolutionError.desc + " Detail: " + errDetail); }; /** * Creates an error thrown if authority type is not valid. * @param invalidAuthorityError */ ClientAuthError.createInvalidAuthorityTypeError = function (givenUrl) { return new ClientAuthError(ClientAuthErrorMessage.invalidAuthorityType.code, ClientAuthErrorMessage.invalidAuthorityType.desc + " Given Url: " + givenUrl); }; /** * Creates an error thrown when the hash cannot be deserialized. * @param invalidAuthorityError */ ClientAuthError.createHashNotDeserializedError = function (hashParamObj) { return new ClientAuthError(ClientAuthErrorMessage.hashNotDeserialized.code, ClientAuthErrorMessage.hashNotDeserialized.desc + " Given Object: " + hashParamObj); }; /** * Creates an error thrown when the state cannot be parsed. * @param invalidState */ ClientAuthError.createInvalidStateError = function (invalidState, errorString) { return new ClientAuthError(ClientAuthErrorMessage.invalidStateError.code, ClientAuthErrorMessage.invalidStateError.desc + " Invalid State: " + invalidState + ", Root Err: " + errorString); }; /** * Creates an error thrown when two states do not match. */ ClientAuthError.createStateMismatchError = function () { return new ClientAuthError(ClientAuthErrorMessage.stateMismatchError.code, ClientAuthErrorMessage.stateMismatchError.desc); }; /** * Creates an error thrown when the nonce does not match. */ ClientAuthError.createNonceMismatchError = function () { return new ClientAuthError(ClientAuthErrorMessage.nonceMismatchError.code, ClientAuthErrorMessage.nonceMismatchError.desc); }; /** * Creates an error thrown when the cached account and response account do not match. */ ClientAuthError.createAccountMismatchError = function () { return new ClientAuthError(ClientAuthErrorMessage.accountMismatchError.code, ClientAuthErrorMessage.accountMismatchError.desc); }; /** * Throws error if idToken is not correctly formed * @param idToken */ ClientAuthError.createInvalidIdTokenError = function (idToken) { return new ClientAuthError(ClientAuthErrorMessage.invalidIdToken.code, ClientAuthErrorMessage.invalidIdToken.desc + " Given token: " + JSON.stringify(idToken)); }; /** * Creates an error thrown when the authorization code required for a token request is null or empty. */ ClientAuthError.createNoTokensFoundError = function () { return new ClientAuthError(ClientAuthErrorMessage.noTokensFoundError.code, ClientAuthErrorMessage.noTokensFoundError.desc); }; /** * Creates an error in cache parsing. */ ClientAuthError.createCacheParseError = function (cacheKey) { return new ClientAuthError(ClientAuthErrorMessage.cacheParseError.code, ClientAuthErrorMessage.cacheParseError.desc + " Cache key: " + cacheKey); }; /** * Throws error when renewing token without login. */ ClientAuthError.createUserLoginRequiredError = function () { return new ClientAuthError(ClientAuthErrorMessage.userLoginRequiredError.code, ClientAuthErrorMessage.userLoginRequiredError.desc); }; /** * Throws error when multiple tokens are in cache for the given scope. * @param scope */ ClientAuthError.createMultipleMatchingTokensInCacheError = function () { return new ClientAuthError(ClientAuthErrorMessage.multipleMatchingTokens.code, ClientAuthErrorMessage.multipleMatchingTokens.desc + "."); }; /** * Throws error when multiple tokens are in cache for the given scope. * @param scope */ ClientAuthError.createMultipleMatchingAccountsInCacheError = function () { return new ClientAuthError(ClientAuthErrorMessage.multipleMatchingAccounts.code, ClientAuthErrorMessage.multipleMatchingAccounts.desc); }; /** * Throws error when no auth code or refresh token is given to ServerTokenRequestParameters. */ ClientAuthError.createTokenRequestCannotBeMadeError = function () { return new ClientAuthError(ClientAuthErrorMessage.tokenRequestCannotBeMade.code, ClientAuthErrorMessage.tokenRequestCannotBeMade.desc); }; /** * Throws error when attempting to append a null, undefined or empty scope to a set * @param givenScope */ ClientAuthError.createAppendEmptyScopeToSetError = function (givenScope) { return new ClientAuthError(ClientAuthErrorMessage.appendEmptyScopeError.code, ClientAuthErrorMessage.appendEmptyScopeError.desc + " Given Scope: " + givenScope); }; /** * Throws error when attempting to append a null, undefined or empty scope to a set * @param givenScope */ ClientAuthError.createRemoveEmptyScopeFromSetError = function (givenScope) { return new ClientAuthError(ClientAuthErrorMessage.removeEmptyScopeError.code, ClientAuthErrorMessage.removeEmptyScopeError.desc + " Given Scope: " + givenScope); }; /** * Throws error when attempting to append null or empty ScopeSet. * @param appendError */ ClientAuthError.createAppendScopeSetError = function (appendError) { return new ClientAuthError(ClientAuthErrorMessage.appendScopeSetError.code, ClientAuthErrorMessage.appendScopeSetError.desc + " Detail Error: " + appendError); }; /** * Throws error if ScopeSet is null or undefined. * @param givenScopeSet */ ClientAuthError.createEmptyInputScopeSetError = function (givenScopeSet) { return new ClientAuthError(ClientAuthErrorMessage.emptyInputScopeSetError.code, ClientAuthErrorMessage.emptyInputScopeSetError.desc + " Given ScopeSet: " + givenScopeSet); }; /** * Throws error if user sets CancellationToken.cancel = true during polling of token endpoint during device code flow */ ClientAuthError.createDeviceCodeCancelledError = function () { return new ClientAuthError(ClientAuthErrorMessage.DeviceCodePollingCancelled.code, "" + ClientAuthErrorMessage.DeviceCodePollingCancelled.desc); }; /** * Throws error if device code is expired */ ClientAuthError.createDeviceCodeExpiredError = function () { return new ClientAuthError(ClientAuthErrorMessage.DeviceCodeExpired.code, "" + ClientAuthErrorMessage.DeviceCodeExpired.desc); }; /** * Throws error when silent requests are made without an account object */ ClientAuthError.createNoAccountInSilentRequestError = function () { return new ClientAuthError(ClientAuthErrorMessage.NoAccountInSilentRequest.code, "" + ClientAuthErrorMessage.NoAccountInSilentRequest.desc); }; /** * Throws error when cache record is null or undefined. */ ClientAuthError.createNullOrUndefinedCacheRecord = function () { return new ClientAuthError(ClientAuthErrorMessage.invalidCacheRecord.code, ClientAuthErrorMessage.invalidCacheRecord.desc); }; /** * Throws error when provided environment is not part of the CloudDiscoveryMetadata object */ ClientAuthError.createInvalidCacheEnvironmentError = function () { return new ClientAuthError(ClientAuthErrorMessage.invalidCacheEnvironment.code, ClientAuthErrorMessage.invalidCacheEnvironment.desc); }; /** * Throws error when account is not found in cache. */ ClientAuthError.createNoAccountFoundError = function () { return new ClientAuthError(ClientAuthErrorMessage.noAccountFound.code, ClientAuthErrorMessage.noAccountFound.desc); }; /** * Throws error if ICachePlugin not set on CacheManager. */ ClientAuthError.createCachePluginError = function () { return new ClientAuthError(ClientAuthErrorMessage.CachePluginError.code, "" + ClientAuthErrorMessage.CachePluginError.desc); }; /** * Throws error if crypto object not found. * @param operationName */ ClientAuthError.createNoCryptoObjectError = function (operationName) { return new ClientAuthError(ClientAuthErrorMessage.noCryptoObj.code, "" + ClientAuthErrorMessage.noCryptoObj.desc + operationName); }; /** * Throws error if cache type is invalid. */ ClientAuthError.createInvalidCacheTypeError = function () { return new ClientAuthError(ClientAuthErrorMessage.invalidCacheType.code, "" + ClientAuthErrorMessage.invalidCacheType.desc); }; /** * Throws error if unexpected account type. */ ClientAuthError.createUnexpectedAccountTypeError = function () { return new ClientAuthError(ClientAuthErrorMessage.unexpectedAccountType.code, "" + ClientAuthErrorMessage.unexpectedAccountType.desc); }; /** * Throws error if unexpected credential type. */ ClientAuthError.createUnexpectedCredentialTypeError = function () { return new ClientAuthError(ClientAuthErrorMessage.unexpectedCredentialType.code, "" + ClientAuthErrorMessage.unexpectedCredentialType.desc); }; /** * Throws error if client assertion is not valid. */ ClientAuthError.createInvalidAssertionError = function () { return new ClientAuthError(ClientAuthErrorMessage.invalidAssertion.code, "" + ClientAuthErrorMessage.invalidAssertion.desc); }; /** * Throws error if client assertion is not valid. */ ClientAuthError.createInvalidCredentialError = function () { return new ClientAuthError(ClientAuthErrorMessage.invalidClientCredential.code, "" + ClientAuthErrorMessage.invalidClientCredential.desc); }; /** * Throws error if token cannot be retrieved from cache due to refresh being required. */ ClientAuthError.createRefreshRequiredError = function () { return new ClientAuthError(ClientAuthErrorMessage.tokenRefreshRequired.code, ClientAuthErrorMessage.tokenRefreshRequired.desc); }; return ClientAuthError; }(AuthError)); /** * @hidden */ var StringUtils = /** @class */ (function () { function StringUtils() { } /** * decode a JWT * * @param jwtToken */ StringUtils.decodeJwt = function (jwtToken) { if (StringUtils.isEmpty(jwtToken)) { throw ClientAuthError.createIdTokenNullOrEmptyError(jwtToken); } var idTokenPartsRegex = /^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$/; var matches = idTokenPartsRegex.exec(jwtToken); if (!matches || matches.length < 4) { throw ClientAuthError.createIdTokenParsingError("Given token is malformed: " + JSON.stringify(jwtToken)); } var crackedToken = { header: matches[1], JWSPayload: matches[2], JWSSig: matches[3] }; return crackedToken; }; /** * Check if a string is empty. * * @param str */ StringUtils.isEmpty = function (str) { return (typeof str === "undefined" || !str || 0 === str.length); }; StringUtils.startsWith = function (str, search) { return str.indexOf(search) === 0; }; StringUtils.endsWith = function (str, search) { return (str.length >= search.length) && (str.lastIndexOf(search) === (str.length - search.length)); }; /** * Parses string into an object. * * @param query */ StringUtils.queryStringToObject = function (query) { var match; // Regex for replacing addition symbol with a space var pl = /\+/g; var search = /([^&=]+)=([^&]*)/g; var decode = function (s) { return decodeURIComponent(decodeURIComponent(s.replace(pl, " "))); }; var obj = {}; match = search.exec(query); while (match) { obj[decode(match[1])] = decode(match[2]); match = search.exec(query); } return obj; }; /** * Trims entries in an array. * * @param arr */ StringUtils.trimArrayEntries = function (arr) { return arr.map(function (entry) { return entry.trim(); }); }; /** * Removes empty strings from array * @param arr */ StringUtils.removeEmptyStringsFromArray = function (arr) { return arr.filter(function (entry) { return !StringUtils.isEmpty(entry); }); }; /** * Attempts to parse a string into JSON * @param str */ StringUtils.jsonParseHelper = function (str) { try { return JSON.parse(str); } catch (e) { return null; } }; return StringUtils; }()); /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ /** * Log message level. */ (function (LogLevel) { LogLevel[LogLevel["Error"] = 0] = "Error"; LogLevel[LogLevel["Warning"] = 1] = "Warning"; LogLevel[LogLevel["Info"] = 2] = "Info"; LogLevel[LogLevel["Verbose"] = 3] = "Verbose"; })(exports.LogLevel || (exports.LogLevel = {})); /** * Class which facilitates logging of messages to a specific place. */ var Logger = /** @class */ (function () { function Logger(loggerOptions) { // Current log level, defaults to info. this.level = exports.LogLevel.Info; if (loggerOptions) { this.localCallback = loggerOptions.loggerCallback; this.piiLoggingEnabled = loggerOptions.piiLoggingEnabled; this.level = loggerOptions.logLevel; } } /** * Log message with required options. */ Logger.prototype.logMessage = function (logMessage, options) { if ((options.logLevel > this.level) || (!this.piiLoggingEnabled && options.containsPii)) { return; } var timestamp = new Date().toUTCString(); var logHeader = StringUtils.isEmpty(this.correlationId) ? "[" + timestamp + "] : " : "[" + timestamp + "] : [" + this.correlationId + "]"; var log = logHeader + " : " + pkg.version + " : " + exports.LogLevel[options.logLevel] + " - " + logMessage; // debug(`msal:${LogLevel[options.logLevel]}${options.containsPii ? "-Pii": ""}${options.context ? `:${options.context}` : ""}`)(logMessage); this.executeCallback(options.logLevel, log, options.containsPii); }; /** * Execute callback with message. */ Logger.prototype.executeCallback = function (level, message, containsPii) { if (this.localCallback) { this.localCallback(level, message, containsPii); } }; /** * Logs error messages. */ Logger.prototype.error = function (message, correlationId) { this.logMessage(message, { logLevel: exports.LogLevel.Error, containsPii: false, correlationId: correlationId || "" }); }; /** * Logs error messages with PII. */ Logger.prototype.errorPii = function (message, correlationId) { this.logMessage(message, { logLevel: exports.LogLevel.Error, containsPii: true, correlationId: correlationId || "" }); }; /** * Logs warning messages. */ Logger.prototype.warning = function (message, correlationId) { this.logMessage(message, { logLevel: exports.LogLevel.Warning, containsPii: false, correlationId: correlationId || "" }); }; /** * Logs warning messages with PII. */ Logger.prototype.warningPii = function (message, correlationId) { this.logMessage(message, { logLevel: exports.LogLevel.Warning, containsPii: true, correlationId: correlationId || "" }); }; /** * Logs info messages. */ Logger.prototype.info = function (message, correlationId) { this.logMessage(message, { logLevel: exports.LogLevel.Info, containsPii: false, correlationId: correlationId || "" }); }; /** * Logs info messages with PII. */ Logger.prototype.infoPii = function (message, correlationId) { this.logMessage(message, { logLevel: exports.LogLevel.Info, containsPii: true, correlationId: correlationId || "" }); }; /** * Logs verbose messages. */ Logger.prototype.verbose = function (message, correlationId) { this.logMessage(message, { logLevel: exports.LogLevel.Verbose, containsPii: false, correlationId: correlationId || "" }); }; /** * Logs verbose messages with PII. */ Logger.prototype.verbosePii = function (message, correlationId) { this.logMessage(message, { logLevel: exports.LogLevel.Verbose, containsPii: true, correlationId: correlationId || "" }); }; /** * Returns whether PII Logging is enabled or not. */ Logger.prototype.isPiiLoggingEnabled = function () { return this.piiLoggingEnabled || false; }; return Logger; }()); /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ var Constants = { LIBRARY_NAME: "MSAL.JS", SKU: "msal.js.common", // Prefix for all library cache entries CACHE_PREFIX: "msal", // default authority DEFAULT_AUTHORITY: "https://login.microsoftonline.com/common/", DEFAULT_AUTHORITY_HOST: "login.microsoftonline.com", // ADFS String ADFS: "adfs", // Default AAD Instance Discovery Endpoint AAD_INSTANCE_DISCOVERY_ENDPT: "https://login.microsoftonline.com/common/discovery/instance?api-version=1.1&authorization_endpoint=", // Resource delimiter - used for certain cache entries RESOURCE_DELIM: "|", // Placeholder for non-existent account ids/objects NO_ACCOUNT: "NO_ACCOUNT", // Claims CLAIMS: "claims", // Consumer UTID CONSUMER_UTID: "9188040d-6c67-4c5b-b112-36a304b66dad", // Default scopes OPENID_SCOPE: "openid", PROFILE_SCOPE: "profile", OFFLINE_ACCESS_SCOPE: "offline_access", // Default response type for authorization code flow CODE_RESPONSE_TYPE: "code", CODE_GRANT_TYPE: "authorization_code", RT_GRANT_TYPE: "refresh_token", FRAGMENT_RESPONSE_MODE: "fragment", S256_CODE_CHALLENGE_METHOD: "S256", URL_FORM_CONTENT_TYPE: "application/x-www-form-urlencoded;charset=utf-8", AUTHORIZATION_PENDING: "authorization_pending", NOT_DEFINED: "not_defined" }; /** * Request header names */ var HeaderNames; (function (HeaderNames) { HeaderNames["CONTENT_TYPE"] = "Content-Type"; HeaderNames["X_CLIENT_CURR_TELEM"] = "x-client-current-telemetry"; HeaderNames["X_CLIENT_LAST_TELEM"] = "x-client-last-telemetry"; HeaderNames["RETRY_AFTER"] = "Retry-After"; HeaderNames["X_MS_LIB_CAPABILITY"] = "x-ms-lib-capability"; HeaderNames["X_MS_LIB_CAPABILITY_VALUE"] = "retry-after, h429"; })(HeaderNames || (HeaderNames = {})); /** * Persistent cache keys MSAL which stay while user is logged in. */ var PersistentCacheKeys; (function (PersistentCacheKeys) { PersistentCacheKeys["ID_TOKEN"] = "idtoken"; PersistentCacheKeys["CLIENT_INFO"] = "client.info"; PersistentCacheKeys["ADAL_ID_TOKEN"] = "adal.idtoken"; PersistentCacheKeys["ERROR"] = "error"; PersistentCacheKeys["ERROR_DESC"] = "error.description"; })(PersistentCacheKeys || (PersistentCacheKeys = {})); /** * String constants related to AAD Authority */ var AADAuthorityConstants; (function (AADAuthorityConstants) { AADAuthorityConstants["COMMON"] = "common"; AADAuthorityConstants["ORGANIZATIONS"] = "organizations"; AADAuthorityConstants["CONSUMERS"] = "consumers"; })(AADAuthorityConstants || (AADAuthorityConstants = {})); /** * Keys in the hashParams sent by AAD Server */ var AADServerParamKeys; (function (AADServerParamKeys) { AADServerParamKeys["CLIENT_ID"] = "client_id"; AADServerParamKeys["REDIRECT_URI"] = "redirect_uri"; AADServerParamKeys["RESPONSE_TYPE"] = "response_type"; AADServerParamKeys["RESPONSE_MODE"] = "response_mode"; AADServerParamKeys["GRANT_TYPE"] = "grant_type"; AADServerParamKeys["CLAIMS"] = "claims"; AADServerParamKeys["SCOPE"] = "scope"; AADServerParamKeys["ERROR"] = "error"; AADServerParamKeys["ERROR_DESCRIPTION"] = "error_description"; AADServerParamKeys["ACCESS_TOKEN"] = "access_token"; AADServerParamKeys["ID_TOKEN"] = "id_token"; AADServerParamKeys["REFRESH_TOKEN"] = "refresh_token"; AADServerParamKeys["EXPIRES_IN"] = "expires_in"; AADServerParamKeys["STATE"] = "state"; AADServerParamKeys["NONCE"] = "nonce"; AADServerParamKeys["PROMPT"] = "prompt"; AADServerParamKeys["SESSION_STATE"] = "session_state"; AADServerParamKeys["CLIENT_INFO"] = "client_info"; AADServerParamKeys["CODE"] = "code"; AADServerParamKeys["CODE_CHALLENGE"] = "code_challenge"; AADServerParamKeys["CODE_CHALLENGE_METHOD"] = "code_challenge_method"; AADServerParamKeys["CODE_VERIFIER"] = "code_verifier"; AADServerParamKeys["CLIENT_REQUEST_ID"] = "client-request-id"; AADServerParamKeys["X_CLIENT_SKU"] = "x-client-SKU"; AADServerParamKeys["X_CLIENT_VER"] = "x-client-VER"; AADServerParamKeys["X_CLIENT_OS"] = "x-client-OS"; AADServerParamKeys["X_CLIENT_CPU"] = "x-client-CPU"; AADServerParamKeys["POST_LOGOUT_URI"] = "post_logout_redirect_uri"; AADServerParamKeys["DEVICE_CODE"] = "device_code"; AADServerParamKeys["CLIENT_SECRET"] = "client_secret"; AADServerParamKeys["CLIENT_ASSERTION"] = "client_assertion"; AADServerParamKeys["CLIENT_ASSERTION_TYPE"] = "client_assertion_type"; AADServerParamKeys["OBO_ASSERTION"] = "assertion"; AADServerParamKeys["REQUESTED_TOKEN_USE"] = "requested_token_use"; AADServerParamKeys["ON_BEHALF_OF"] = "on_behalf_of"; })(AADServerParamKeys || (AADServerParamKeys = {})); /** * IdToken claim string constants */ var IdTokenClaimName; (function (IdTokenClaimName) { IdTokenClaimName["ISSUER"] = "iss"; IdTokenClaimName["OBJID"] = "oid"; IdTokenClaimName["SUBJECT"] = "sub"; IdTokenClaimName["TENANTID"] = "tid"; IdTokenClaimName["VERSION"] = "ver"; IdTokenClaimName["PREF_USERNAME"] = "preferred_username"; IdTokenClaimName["NAME"] = "name"; IdTokenClaimName["NONCE"] = "nonce"; IdTokenClaimName["EXPIRATION"] = "exp"; IdTokenClaimName["HOME_OBJID"] = "home_oid"; IdTokenClaimName["SESSIONID"] = "sid"; IdTokenClaimName["CLOUD_INSTANCE_HOSTNAME"] = "cloud_instance_host_name"; })(IdTokenClaimName || (IdTokenClaimName = {})); var ClaimsRequestKeys; (function (ClaimsRequestKeys) { ClaimsRequestKeys["ACCESS_TOKEN"] = "access_token"; ClaimsRequestKeys["XMS_CC"] = "xms_cc"; })(ClaimsRequestKeys || (ClaimsRequestKeys = {})); /** * we considered making this "enum" in the request instead of string, however it looks like the allowed list of * prompt values kept changing over past couple of years. There are some undocumented prompt values for some * internal partners too, hence the choice of generic "string" type instead of the "enum" */ var PromptValue = { LOGIN: "login", SELECT_ACCOUNT: "select_account", CONSENT: "consent", NONE: "none", }; /** * SSO Types - generated to populate hints */ var SSOTypes; (function (SSOTypes) { SSOTypes["ACCOUNT"] = "account"; SSOTypes["SID"] = "sid"; SSOTypes["LOGIN_HINT"] = "login_hint"; SSOTypes["ID_TOKEN"] = "id_token"; SSOTypes["DOMAIN_HINT"] = "domain_hint"; SSOTypes["ORGANIZATIONS"] = "organizations"; SSOTypes["CONSUMERS"] = "consumers"; SSOTypes["ACCOUNT_ID"] = "accountIdentifier"; SSOTypes["HOMEACCOUNT_ID"] = "homeAccountIdentifier"; })(SSOTypes || (SSOTypes = {})); /** * Disallowed extra query parameters. */ var BlacklistedEQParams = [ SSOTypes.SID, SSOTypes.LOGIN_HINT ]; /** * allowed values for codeVerifier */ var CodeChallengeMethodValues = { PLAIN: "plain", S256: "S256" }; /** * allowed values for response_mode */ var ResponseMode; (function (ResponseMode) { ResponseMode["QUERY"] = "query"; ResponseMode["FRAGMENT"] = "fragment"; ResponseMode["FORM_POST"] = "form_post"; })(ResponseMode || (ResponseMode = {})); /** * allowed grant_type */ var GrantType; (function (GrantType) { GrantType["IMPLICIT_GRANT"] = "implicit"; GrantType["AUTHORIZATION_CODE_GRANT"] = "authorization_code"; GrantType["CLIENT_CREDENTIALS_GRANT"] = "client_credentials"; GrantType["RESOURCE_OWNER_PASSWORD_GRANT"] = "password"; GrantType["REFRESH_TOKEN_GRANT"] = "refresh_token"; GrantType["DEVICE_CODE_GRANT"] = "device_code"; GrantType["JWT_BEARER"] = "urn:ietf:params:oauth:grant-type:jwt-bearer"; })(GrantType || (GrantType = {})); /** * Account types in Cache */ var CacheAccountType; (function (CacheAccountType) { CacheAccountType["MSSTS_ACCOUNT_TYPE"] = "MSSTS"; CacheAccountType["ADFS_ACCOUNT_TYPE"] = "ADFS"; CacheAccountType["MSAV1_ACCOUNT_TYPE"] = "MSA"; CacheAccountType["GENERIC_ACCOUNT_TYPE"] = "Generic"; // NTLM, Kerberos, FBA, Basic etc })(CacheAccountType || (CacheAccountType = {})); /** * Separators used in cache */ var Separators; (function (Separators) { Separators["CACHE_KEY_SEPARATOR"] = "-"; Separators["CLIENT_INFO_SEPARATOR"] = "."; })(Separators || (Separators = {})); /** * Credential Type stored in the cache */ var CredentialType; (function (CredentialType) { CredentialType["ID_TOKEN"] = "IdToken"; CredentialType["ACCESS_TOKEN"] = "AccessToken"; CredentialType["REFRESH_TOKEN"] = "RefreshToken"; })(CredentialType || (CredentialType = {})); /** * Credential Type stored in the cache */ var CacheSchemaType; (function (CacheSchemaType) { CacheSchemaType["ACCOUNT"] = "Account"; CacheSchemaType["CREDENTIAL"] = "Credential"; CacheSchemaType["ID_TOKEN"] = "IdToken"; CacheSchemaType["ACCESS_TOKEN"] = "AccessToken"; CacheSchemaType["REFRESH_TOKEN"] = "RefreshToken"; CacheSchemaType["APP_METADATA"] = "AppMetadata"; CacheSchemaType["TEMPORARY"] = "TempCache"; CacheSchemaType["TELEMETRY"] = "Telemetry"; CacheSchemaType["UNDEFINED"] = "Undefined"; CacheSchemaType["THROTTLING"] = "Throttling"; })(CacheSchemaType || (CacheSchemaType = {})); /** * Combine all cache types */ var CacheType; (function (CacheType) { CacheType[CacheType["ADFS"] = 1001] = "ADFS"; CacheType[CacheType["MSA"] = 1002] = "MSA"; CacheType[CacheType["MSSTS"] = 1003] = "MSSTS"; CacheType[CacheType["GENERIC"] = 1004] = "GENERIC"; CacheType[CacheType["ACCESS_TOKEN"] = 2001] = "ACCESS_TOKEN"; CacheType[CacheType["REFRESH_TOKEN"] = 2002] = "REFRESH_TOKEN"; CacheType[CacheType["ID_TOKEN"] = 2003] = "ID_TOKEN"; CacheType[CacheType["APP_METADATA"] = 3001] = "APP_METADATA"; CacheType[CacheType["UNDEFINED"] = 9999] = "UNDEFINED"; })(CacheType || (CacheType = {})); /** * More Cache related constants */ var APP_METADATA = "appmetadata"; var ClientInfo = "client_info"; var SERVER_TELEM_CONSTANTS = { SCHEMA_VERSION: 2, FAILURE_LIMIT: 3, CACHE_KEY: "server-telemetry", CATEGORY_SEP