UNPKG

@dreaken/msal-browser-fixed-beta

Version:
1,219 lines (1,193 loc) 237 kB
/*! @dreaken/msal-browser-fixed-beta v2.0.0-beta.13 2020-04-13 */ 'use strict'; /*! ***************************************************************************** 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 }; } } /*! @azure/msal-common v1.0.0-beta.0 2020-03-31 */ /*! ***************************************************************************** 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() { 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) { var _this = _super.call(this, errorMessage) || this; Object.setPrototypeOf(_this, AuthError.prototype); _this.errorCode = errorCode; _this.errorMessage = errorMessage; _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.0.0-beta.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 = "./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/*", lint: "eslint src --ext .ts", 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 lint && 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/mocha": "^5.2.7", "@types/sinon": "^7.5.0", "@typescript-eslint/eslint-plugin": "^2.4.0", "@typescript-eslint/eslint-plugin-tslint": "^2.4.0", "@typescript-eslint/parser": "^2.4.0", "babel-plugin-istanbul": "^5.2.0", chai: "^4.2.0", "chai-as-promised": "^7.1.1", eslint: "^6.5.1", 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.3", shx: "^0.3.2", sinon: "^7.5.0", tslib: "^1.10.0", tslint: "^5.20.0", typescript: "^3.6.4" }; var dependencies = { }; var pkg = { name: name, author: author, license: license, repository: repository, version: version, description: description, keywords: keywords, main: main, module: module, 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." }, tokenRequestCacheError: { code: "token_request_cache_error", desc: "The token request could not be fetched from the cache correctly." }, 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." }, 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, resource, or 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." } }; /** * 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 token request could not be retrieved from the cache * @param errDetail */ ClientAuthError.createTokenRequestCacheError = function (errDetail) { return new ClientAuthError(ClientAuthErrorMessage.tokenRequestCacheError.code, ClientAuthErrorMessage.tokenRequestCacheError.desc + " Error Detail: " + errDetail); }; /** * 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 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 (scopes) { return new ClientAuthError(ClientAuthErrorMessage.noTokensFoundError.code, ClientAuthErrorMessage.noTokensFoundError.desc + " Scopes: " + scopes); }; /** * 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 (scope) { return new ClientAuthError(ClientAuthErrorMessage.multipleMatchingTokens.code, "Cache error for scope " + scope + ": " + ClientAuthErrorMessage.multipleMatchingTokens.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); }; 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); }; /** * 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(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 and converts them to lower case. * * @param arr */ StringUtils.trimAndConvertArrayEntriesToLowerCase = function (arr) { return arr.map(function (entry) { return entry.trim().toLowerCase(); }); }; /** * Removes empty strings from array * @param arr */ StringUtils.removeEmptyStringsFromArray = function (arr) { return arr.filter(function (entry) { return !StringUtils.isEmpty(entry); }); }; return StringUtils; }()); /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ /** * Log message level. */ var LogLevel; (function (LogLevel) { LogLevel[LogLevel["Error"] = 0] = "Error"; LogLevel[LogLevel["Warning"] = 1] = "Warning"; LogLevel[LogLevel["Info"] = 2] = "Info"; LogLevel[LogLevel["Verbose"] = 3] = "Verbose"; })(LogLevel || (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 = 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 + " : " + LogLevel[options.logLevel] + " - " + 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: LogLevel.Error, containsPii: false, correlationId: correlationId || "" }); }; /** * Logs error messages with PII. */ Logger.prototype.errorPii = function (message, correlationId) { this.logMessage(message, { logLevel: LogLevel.Error, containsPii: true, correlationId: correlationId || "" }); }; /** * Logs warning messages. */ Logger.prototype.warning = function (message, correlationId) { this.logMessage(message, { logLevel: LogLevel.Warning, containsPii: false, correlationId: correlationId || "" }); }; /** * Logs warning messages with PII. */ Logger.prototype.warningPii = function (message, correlationId) { this.logMessage(message, { logLevel: LogLevel.Warning, containsPii: true, correlationId: correlationId || "" }); }; /** * Logs info messages. */ Logger.prototype.info = function (message, correlationId) { this.logMessage(message, { logLevel: LogLevel.Info, containsPii: false, correlationId: correlationId || "" }); }; /** * Logs info messages with PII. */ Logger.prototype.infoPii = function (message, correlationId) { this.logMessage(message, { logLevel: LogLevel.Info, containsPii: true, correlationId: correlationId || "" }); }; /** * Logs verbose messages. */ Logger.prototype.verbose = function (message, correlationId) { this.logMessage(message, { logLevel: LogLevel.Verbose, containsPii: false, correlationId: correlationId || "" }); }; /** * Logs verbose messages with PII. */ Logger.prototype.verbosePii = function (message, correlationId) { this.logMessage(message, { logLevel: LogLevel.Verbose, containsPii: true, correlationId: correlationId || "" }); }; /** * Returns whether PII Logging is enabled or not. */ Logger.prototype.isPiiLoggingEnabled = function () { return this.piiLoggingEnabled || false; }; return Logger; }()); // Token renewal offset default in seconds var DEFAULT_TOKEN_RENEWAL_OFFSET_SEC = 300; // Default module system options var DEFAULT_SYSTEM_OPTIONS = { tokenRenewalOffsetSeconds: DEFAULT_TOKEN_RENEWAL_OFFSET_SEC, telemetry: null }; // Default logger implementation var DEFAULT_LOGGER_IMPLEMENTATION = { loggerCallback: function () { var notImplErr = "Logger - loggerCallbackInterface() has not been implemented."; throw AuthError.createUnexpectedError(notImplErr); }, piiLoggingEnabled: false, logLevel: LogLevel.Info }; // Default storage implementation var DEFAULT_STORAGE_IMPLEMENTATION = { clear: function () { var notImplErr = "Storage interface - clear() has not been implemented for the cacheStorage interface."; throw AuthError.createUnexpectedError(notImplErr); }, containsKey: function () { var notImplErr = "Storage interface - containsKey() has not been implemented for the cacheStorage interface."; throw AuthError.createUnexpectedError(notImplErr); }, getItem: function () { var notImplErr = "Storage interface - getItem() has not been implemented for the cacheStorage interface."; throw AuthError.createUnexpectedError(notImplErr); }, getKeys: function () { var notImplErr = "Storage interface - getKeys() has not been implemented for the cacheStorage interface."; throw AuthError.createUnexpectedError(notImplErr); }, removeItem: function () { var notImplErr = "Storage interface - removeItem() has not been implemented for the cacheStorage interface."; throw AuthError.createUnexpectedError(notImplErr); }, setItem: function () { var notImplErr = "Storage interface - setItem() has not been implemented for the cacheStorage interface."; throw AuthError.createUnexpectedError(notImplErr); } }; // Default network implementation var DEFAULT_NETWORK_IMPLEMENTATION = { sendGetRequestAsync: function () { return __awaiter$1(this, void 0, void 0, function () { var notImplErr; return __generator$1(this, function (_a) { notImplErr = "Network interface - sendGetRequestAsync() has not been implemented"; throw AuthError.createUnexpectedError(notImplErr); }); }); }, sendPostRequestAsync: function () { return __awaiter$1(this, void 0, void 0, function () { var notImplErr; return __generator$1(this, function (_a) { notImplErr = "Network interface - sendPostRequestAsync() has not been implemented"; throw AuthError.createUnexpectedError(notImplErr); }); }); } }; // Default crypto implementation var DEFAULT_CRYPTO_IMPLEMENTATION = { createNewGuid: function () { var notImplErr = "Crypto interface - createNewGuid() has not been implemented"; throw AuthError.createUnexpectedError(notImplErr); }, base64Decode: function () { var notImplErr = "Crypto interface - base64Decode() has not been implemented"; throw AuthError.createUnexpectedError(notImplErr); }, base64Encode: function () { var notImplErr = "Crypto interface - base64Encode() has not been implemented"; throw AuthError.createUnexpectedError(notImplErr); }, generatePkceCodes: function () { return __awaiter$1(this, void 0, void 0, function () { var notImplErr; return __generator$1(this, function (_a) { notImplErr = "Crypto interface - generatePkceCodes() has not been implemented"; throw AuthError.createUnexpectedError(notImplErr); }); }); } }; /** * Function that sets the default options when not explicitly configured from app developer * * @param TStorageOptions * @param TSystemOptions * @param TFrameworkOptions * * @returns MsalConfiguration object */ function buildModuleConfiguration(_a) { var userSystemOptions = _a.systemOptions, userLoggerOption = _a.loggerOptions, storageImplementation = _a.storageInterface, networkImplementation = _a.networkInterface, cryptoImplementation = _a.cryptoInterface; var overlayedConfig = { systemOptions: userSystemOptions || DEFAULT_SYSTEM_OPTIONS, loggerOptions: userLoggerOption || DEFAULT_LOGGER_IMPLEMENTATION, storageInterface: storageImplementation || DEFAULT_STORAGE_IMPLEMENTATION, networkInterface: networkImplementation || DEFAULT_NETWORK_IMPLEMENTATION, cryptoInterface: cryptoImplementation || DEFAULT_CRYPTO_IMPLEMENTATION }; return overlayedConfig; } /** * Access token cache item which is used to manage tokens and token renewal. */ var AccessTokenCacheItem = /** @class */ (function () { function AccessTokenCacheItem(key, value) { this.key = key; this.value = value; } return AccessTokenCacheItem; }()); /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ var Constants = { LIBRARY_NAME: "MSAL.JS", // Prefix for all library cache entries CACHE_PREFIX: "msal", // default authority DEFAULT_AUTHORITY: "https://login.microsoftonline.com/common", // Default AAD Instance Discovery Endpoint AAD_INSTANCE_DISCOVERY_ENDPT: "https://login.microsoftonline.com/common/discovery/instance", // 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" }; /** * Request header names */ var HEADER_NAMES; (function (HEADER_NAMES) { HEADER_NAMES["CONTENT_TYPE"] = "Content-Type"; })(HEADER_NAMES || (HEADER_NAMES = {})); /** * Temporary cache keys for MSAL, deleted after any request. */ var TemporaryCacheKeys; (function (TemporaryCacheKeys) { TemporaryCacheKeys["AUTHORITY"] = "authority"; TemporaryCacheKeys["ACQUIRE_TOKEN_ACCOUNT"] = "acquireToken.account"; TemporaryCacheKeys["SESSION_STATE"] = "session.state"; TemporaryCacheKeys["REQUEST_STATE"] = "request.state"; TemporaryCacheKeys["NONCE_IDTOKEN"] = "nonce.idtoken"; TemporaryCacheKeys["ORIGIN_URI"] = "request.origin"; TemporaryCacheKeys["RENEW_STATUS"] = "token.renew.status"; TemporaryCacheKeys["URL_HASH"] = "urlHash"; TemporaryCacheKeys["REQUEST_PARAMS"] = "request.params"; TemporaryCacheKeys["SCOPES"] = "scopes"; })(TemporaryCacheKeys || (TemporaryCacheKeys = {})); /** * 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 = {})); /** * List of pre-established trusted host URLs. */ var AADTrustedHostList = [ "login.windows.net", "login.chinacloudapi.cn", "login.cloudgovapi.us", "login.microsoftonline.com", "login.microsoftonline.de", "login.microsoftonline.us" ]; /** * 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["RESOURCE"] = "resource"; 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["POST_LOGOUT_URI"] = "post_logout_redirect_uri"; })(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 = {})); /** * 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 ]; /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ /** * The CacheHelpers class contains a set of helper functions used by the module to manage cache items. */ var CacheHelpers = /** @class */ (function () { function CacheHelpers(cacheImpl) { this.cacheStorage = cacheImpl; } /** * Create acquireTokenAccountKey to cache account object * @param accountId * @param state */ CacheHelpers.prototype.generateAcquireTokenAccountKey = function (accountId) { return "" + TemporaryCacheKeys.ACQUIRE_TOKEN_ACCOUNT + Constants.RESOURCE_DELIM + accountId; }; /** * Create authorityKey to cache authority * @param state */ CacheHelpers.prototype.generateAuthorityKey = function (state) { return "" + TemporaryCacheKeys.AUTHORITY + Constants.RESOURCE_DELIM + state; }; /** * Create Nonce key to cache nonce * @param state */ CacheHelpers.prototype.generateNonceKey = function (state) { return "" + TemporaryCacheKeys.NONCE_IDTOKEN + Constants.RESOURCE_DELIM + state; }; /** * Sets the cachekeys for and stores the account information in cache * @param account * @param state */ CacheHelpers.prototype.setAccountCache = function (account) { // Cache acquireTokenAccountKey var accountId = account && account.homeAccountIdentifier ? account.homeAccountIdentifier : Constants.NO_ACCOUNT; var acquireTokenAccountKey = this.generateAcquireTokenAccountKey(accountId); this.cacheStorage.setItem(acquireTokenAccountKey, JSON.stringify(account)); }; /** * Sets the cacheKey for and stores the authority information in cache * @param state * @param authority */ CacheHelpers.prototype.setAuthorityCache = function (authority, state) { // Cache authorityKey var authorityKey = this.generateAuthorityKey(state); this.cacheStorage.setItem(authorityKey, authority.canonicalAuthority); }; /** * Updates account, authority, and state in cache * @param serverAuthenticationRequest * @param account */ CacheHelpers.prototype.updateCacheEntries = function (serverAuthenticationRequest, account) { // Cache account and state if (account) { this.setAccountCache(account); } // Cache the request state this.cacheStorage.setItem(TemporaryCacheKeys.REQUEST_STATE, serverAuthenticationRequest.state); // Cache the nonce this.cacheStorage.setItem(this.generateNonceKey(serverAuthenticationRequest.state), serverAuthenticationRequest.nonce); // Cache authorityKey this.setAuthorityCache(serverAuthenticationRequest.authorityInstance, serverAuthenticationRequest.state); }; /** * Reset all temporary cache items * @param state */ CacheHelpers.prototype.resetTempCacheItems = function (state) { var _this = this; // check state and remove associated cache items this.cacheStorage.getKeys().forEach(function (key) { if (!StringUtils.isEmpty(state) && key.indexOf(state) !== -1) { var splitKey = key.split(Constants.RESOURCE_DELIM); var keyState = splitKey.length > 1 ? splitKey[splitKey.length - 1] : null; if (keyState === state) { _this.cacheStorage.removeItem(key); } } }); // delete generic interactive request parameters this.cacheStorage.removeItem(TemporaryCacheKeys.REQUEST_STATE); this.cacheStorage.removeItem(TemporaryCacheKeys.REQUEST_PARAMS); this.cacheStorage.removeItem(TemporaryCacheKeys.ORIGIN_URI); }; /** * Get all access tokens in the cache * @param clientId * @param homeAccountIdentifier */ CacheHelpers.prototype.getAllAccessTokens = function (clientId, authority, resource, homeAccountIdentifier) { var _this = this; var results = this.cacheStorage.getKeys().reduce(function (tokens, key) { var keyMatches = key.match(clientId) && key.match(authority) && key.match(resource) && key.match(homeAccountIdentifier); if (keyMatches) { var value = _this.cacheStorage.getItem(key); if (value) { try { var parseAtKey = JSON.parse(key); if (_this.checkForExactKeyMatch(parseAtKey, clientId, authority, resource, homeAccountIdentifier)) { var newAccessTokenCacheItem = new AccessTokenCacheItem(parseAtKey, JSON.parse(value)); return tokens.concat([newAccessTokenCacheItem]); } } catch (e) { throw ClientAuthError.createCacheParseError(key); } } } return tokens; }, []); return results; }; /** * Remove all access tokens in the cache * @param clientId * @param homeAccountIdentifier */ CacheHelpers.prototype.removeAllAccessTokens = function (clientId, authority, resource, homeAccountIdentifier) { var _this = this; this.cacheStorage.getKeys().forEach(function (key) { var keyMatches = key.match(clientId) && key.match(authority) && key.match(resource) && key.match(homeAccountIdentifier); if (keyMatches) { try { var parseAtKey = JSON.parse(key); if (_this.checkForExactKeyMatch(parseAtKey, clientId, authority, resource, homeAccountIdentifier)) { _this.cacheStorage.removeItem(key); } } catch (e) { throw ClientAuthError.createCacheParseError(key); } } }); }; /** * Checks that any parameters are exact matches for key value, since key.match in the above functions only do contains checks, not exact matches. * @param atKey * @param clientId * @param authority * @param resource * @param homeAccountIdentifier */ CacheHelpers.prototype.checkForExactKeyMatch = function (atKey, clientId, authority, resource, homeAccountIdentifier) { var hasClientId = (atKey.clientId === clientId); // If any inputs are empty, return true so we don't fail the check. var hasAuthorityUri = StringUtils.isEmpty(authority) || (atKey.authority === authority); var hasResourceUri = StringUtils.isEmpty(resource) || (atKey.resource === resource); var hasHomeAccountId = StringUtils.isEmpty(homeAccountIdentifier) || (atKey.homeAccountIdentifier === homeAccountIdentifier); return hasClientId && hasAuthorityUri && hasResourceUri && hasHomeAccountId; }; return CacheHelpers; }()); /** * accountIdentifier combination of id