From 9b840bb79c415a3c17df3473a9a2a8af734b7063 Mon Sep 17 00:00:00 2001 From: derisen Date: Wed, 7 Jul 2021 06:30:14 -0700 Subject: [PATCH] fix redirect route handler invalid route path issue --- demo/App/routes/router.js | 4 ++-- dist/UrlUtils.d.ts | 6 ++++++ dist/msal-express-wrapper.cjs.development.js | 13 ++++++++++++- dist/msal-express-wrapper.cjs.development.js.map | 2 +- dist/msal-express-wrapper.cjs.production.min.js | 2 +- dist/msal-express-wrapper.cjs.production.min.js.map | 2 +- dist/msal-express-wrapper.esm.js | 13 ++++++++++++- dist/msal-express-wrapper.esm.js.map | 2 +- src/AuthProvider.ts | 2 +- src/UrlUtils.ts | 10 ++++++++++ 10 files changed, 47 insertions(+), 9 deletions(-) diff --git a/demo/App/routes/router.js b/demo/App/routes/router.js index ba0d6cd..5198f11 100644 --- a/demo/App/routes/router.js +++ b/demo/App/routes/router.js @@ -45,10 +45,10 @@ module.exports = (authProvider) => { mainController.getTenantPage ); // get token for this route to call web API - // unauthorized + // error router.get('/error', (req, res) => res.redirect('/401.html')); - // error + // unauthorized router.get('/unauthorized', (req, res) => res.redirect('/500.html')); // 404 diff --git a/dist/UrlUtils.d.ts b/dist/UrlUtils.d.ts index 3fbe371..030d5ee 100644 --- a/dist/UrlUtils.d.ts +++ b/dist/UrlUtils.d.ts @@ -7,4 +7,10 @@ export declare class UrlUtils { * @returns {string} */ static ensureAbsoluteUrl: (req: Request, url: string) => string; + /** + * Gets the path segment from a given URL + * @param {string} url: a given URL + * @returns {string} + */ + static getPathFromUrl: (url: string) => string; } diff --git a/dist/msal-express-wrapper.cjs.development.js b/dist/msal-express-wrapper.cjs.development.js index b90ac5a..9cd96a9 100644 --- a/dist/msal-express-wrapper.cjs.development.js +++ b/dist/msal-express-wrapper.cjs.development.js @@ -1745,6 +1745,17 @@ UrlUtils.ensureAbsoluteUrl = function (req, url) { return url; } }; +/** + * Gets the path segment from a given URL + * @param {string} url: a given URL + * @returns {string} + */ + + +UrlUtils.getPathFromUrl = function (url) { + var urlComponents = new msalCommon.UrlString(url).getUrlComponents(); + return "/" + urlComponents.PathSegments.join("/"); +}; var _excluded = ["_claim_names", "_claim_sources"]; /** @@ -1772,7 +1783,7 @@ var AuthProvider = /*#__PURE__*/function () { // TODO: initialize app defaults var appRouter = express.Router(); // handle redirect - appRouter.get(_this.appSettings.authRoutes.redirect, _this.handleRedirect()); + appRouter.get(UrlUtils.getPathFromUrl(_this.appSettings.authRoutes.redirect), _this.handleRedirect()); if (_this.appSettings.authRoutes.frontChannelLogout) { /** diff --git a/dist/msal-express-wrapper.cjs.development.js.map b/dist/msal-express-wrapper.cjs.development.js.map index f0a872c..62383c5 100644 --- a/dist/msal-express-wrapper.cjs.development.js.map +++ b/dist/msal-express-wrapper.cjs.development.js.map @@ -1 +1 @@ -{"version":3,"file":"msal-express-wrapper.cjs.development.js","sources":["../node_modules/regenerator-runtime/runtime.js","../src/Constants.ts","../src/ConfigurationUtils.ts","../src/Logger.ts","../src/TokenValidator.ts","../src/KeyVaultManager.ts","../src/FetchManager.ts","../src/UrlUtils.ts","../src/AuthProvider.ts"],"sourcesContent":["/**\n * Copyright (c) 2014-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nvar runtime = (function (exports) {\n \"use strict\";\n\n var Op = Object.prototype;\n var hasOwn = Op.hasOwnProperty;\n var undefined; // More compressible than void 0.\n var $Symbol = typeof Symbol === \"function\" ? Symbol : {};\n var iteratorSymbol = $Symbol.iterator || \"@@iterator\";\n var asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\";\n var toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n\n function define(obj, key, value) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n return obj[key];\n }\n try {\n // IE 8 has a broken Object.defineProperty that only works on DOM objects.\n define({}, \"\");\n } catch (err) {\n define = function(obj, key, value) {\n return obj[key] = value;\n };\n }\n\n function wrap(innerFn, outerFn, self, tryLocsList) {\n // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.\n var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;\n var generator = Object.create(protoGenerator.prototype);\n var context = new Context(tryLocsList || []);\n\n // The ._invoke method unifies the implementations of the .next,\n // .throw, and .return methods.\n generator._invoke = makeInvokeMethod(innerFn, self, context);\n\n return generator;\n }\n exports.wrap = wrap;\n\n // Try/catch helper to minimize deoptimizations. Returns a completion\n // record like context.tryEntries[i].completion. This interface could\n // have been (and was previously) designed to take a closure to be\n // invoked without arguments, but in all the cases we care about we\n // already have an existing method we want to call, so there's no need\n // to create a new function object. We can even get away with assuming\n // the method takes exactly one argument, since that happens to be true\n // in every case, so we don't have to touch the arguments object. The\n // only additional allocation required is the completion record, which\n // has a stable shape and so hopefully should be cheap to allocate.\n function tryCatch(fn, obj, arg) {\n try {\n return { type: \"normal\", arg: fn.call(obj, arg) };\n } catch (err) {\n return { type: \"throw\", arg: err };\n }\n }\n\n var GenStateSuspendedStart = \"suspendedStart\";\n var GenStateSuspendedYield = \"suspendedYield\";\n var GenStateExecuting = \"executing\";\n var GenStateCompleted = \"completed\";\n\n // Returning this object from the innerFn has the same effect as\n // breaking out of the dispatch switch statement.\n var ContinueSentinel = {};\n\n // Dummy constructor functions that we use as the .constructor and\n // .constructor.prototype properties for functions that return Generator\n // objects. For full spec compliance, you may wish to configure your\n // minifier not to mangle the names of these two functions.\n function Generator() {}\n function GeneratorFunction() {}\n function GeneratorFunctionPrototype() {}\n\n // This is a polyfill for %IteratorPrototype% for environments that\n // don't natively support it.\n var IteratorPrototype = {};\n IteratorPrototype[iteratorSymbol] = function () {\n return this;\n };\n\n var getProto = Object.getPrototypeOf;\n var NativeIteratorPrototype = getProto && getProto(getProto(values([])));\n if (NativeIteratorPrototype &&\n NativeIteratorPrototype !== Op &&\n hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {\n // This environment has a native %IteratorPrototype%; use it instead\n // of the polyfill.\n IteratorPrototype = NativeIteratorPrototype;\n }\n\n var Gp = GeneratorFunctionPrototype.prototype =\n Generator.prototype = Object.create(IteratorPrototype);\n GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;\n GeneratorFunctionPrototype.constructor = GeneratorFunction;\n GeneratorFunction.displayName = define(\n GeneratorFunctionPrototype,\n toStringTagSymbol,\n \"GeneratorFunction\"\n );\n\n // Helper for defining the .next, .throw, and .return methods of the\n // Iterator interface in terms of a single ._invoke method.\n function defineIteratorMethods(prototype) {\n [\"next\", \"throw\", \"return\"].forEach(function(method) {\n define(prototype, method, function(arg) {\n return this._invoke(method, arg);\n });\n });\n }\n\n exports.isGeneratorFunction = function(genFun) {\n var ctor = typeof genFun === \"function\" && genFun.constructor;\n return ctor\n ? ctor === GeneratorFunction ||\n // For the native GeneratorFunction constructor, the best we can\n // do is to check its .name property.\n (ctor.displayName || ctor.name) === \"GeneratorFunction\"\n : false;\n };\n\n exports.mark = function(genFun) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);\n } else {\n genFun.__proto__ = GeneratorFunctionPrototype;\n define(genFun, toStringTagSymbol, \"GeneratorFunction\");\n }\n genFun.prototype = Object.create(Gp);\n return genFun;\n };\n\n // Within the body of any async function, `await x` is transformed to\n // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test\n // `hasOwn.call(value, \"__await\")` to determine if the yielded value is\n // meant to be awaited.\n exports.awrap = function(arg) {\n return { __await: arg };\n };\n\n function AsyncIterator(generator, PromiseImpl) {\n function invoke(method, arg, resolve, reject) {\n var record = tryCatch(generator[method], generator, arg);\n if (record.type === \"throw\") {\n reject(record.arg);\n } else {\n var result = record.arg;\n var value = result.value;\n if (value &&\n typeof value === \"object\" &&\n hasOwn.call(value, \"__await\")) {\n return PromiseImpl.resolve(value.__await).then(function(value) {\n invoke(\"next\", value, resolve, reject);\n }, function(err) {\n invoke(\"throw\", err, resolve, reject);\n });\n }\n\n return PromiseImpl.resolve(value).then(function(unwrapped) {\n // When a yielded Promise is resolved, its final value becomes\n // the .value of the Promise<{value,done}> result for the\n // current iteration.\n result.value = unwrapped;\n resolve(result);\n }, function(error) {\n // If a rejected Promise was yielded, throw the rejection back\n // into the async generator function so it can be handled there.\n return invoke(\"throw\", error, resolve, reject);\n });\n }\n }\n\n var previousPromise;\n\n function enqueue(method, arg) {\n function callInvokeWithMethodAndArg() {\n return new PromiseImpl(function(resolve, reject) {\n invoke(method, arg, resolve, reject);\n });\n }\n\n return previousPromise =\n // If enqueue has been called before, then we want to wait until\n // all previous Promises have been resolved before calling invoke,\n // so that results are always delivered in the correct order. If\n // enqueue has not been called before, then it is important to\n // call invoke immediately, without waiting on a callback to fire,\n // so that the async generator function has the opportunity to do\n // any necessary setup in a predictable way. This predictability\n // is why the Promise constructor synchronously invokes its\n // executor callback, and why async functions synchronously\n // execute code before the first await. Since we implement simple\n // async functions in terms of async generators, it is especially\n // important to get this right, even though it requires care.\n previousPromise ? previousPromise.then(\n callInvokeWithMethodAndArg,\n // Avoid propagating failures to Promises returned by later\n // invocations of the iterator.\n callInvokeWithMethodAndArg\n ) : callInvokeWithMethodAndArg();\n }\n\n // Define the unified helper method that is used to implement .next,\n // .throw, and .return (see defineIteratorMethods).\n this._invoke = enqueue;\n }\n\n defineIteratorMethods(AsyncIterator.prototype);\n AsyncIterator.prototype[asyncIteratorSymbol] = function () {\n return this;\n };\n exports.AsyncIterator = AsyncIterator;\n\n // Note that simple async functions are implemented on top of\n // AsyncIterator objects; they just return a Promise for the value of\n // the final result produced by the iterator.\n exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {\n if (PromiseImpl === void 0) PromiseImpl = Promise;\n\n var iter = new AsyncIterator(\n wrap(innerFn, outerFn, self, tryLocsList),\n PromiseImpl\n );\n\n return exports.isGeneratorFunction(outerFn)\n ? iter // If outerFn is a generator, return the full iterator.\n : iter.next().then(function(result) {\n return result.done ? result.value : iter.next();\n });\n };\n\n function makeInvokeMethod(innerFn, self, context) {\n var state = GenStateSuspendedStart;\n\n return function invoke(method, arg) {\n if (state === GenStateExecuting) {\n throw new Error(\"Generator is already running\");\n }\n\n if (state === GenStateCompleted) {\n if (method === \"throw\") {\n throw arg;\n }\n\n // Be forgiving, per 25.3.3.3.3 of the spec:\n // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume\n return doneResult();\n }\n\n context.method = method;\n context.arg = arg;\n\n while (true) {\n var delegate = context.delegate;\n if (delegate) {\n var delegateResult = maybeInvokeDelegate(delegate, context);\n if (delegateResult) {\n if (delegateResult === ContinueSentinel) continue;\n return delegateResult;\n }\n }\n\n if (context.method === \"next\") {\n // Setting context._sent for legacy support of Babel's\n // function.sent implementation.\n context.sent = context._sent = context.arg;\n\n } else if (context.method === \"throw\") {\n if (state === GenStateSuspendedStart) {\n state = GenStateCompleted;\n throw context.arg;\n }\n\n context.dispatchException(context.arg);\n\n } else if (context.method === \"return\") {\n context.abrupt(\"return\", context.arg);\n }\n\n state = GenStateExecuting;\n\n var record = tryCatch(innerFn, self, context);\n if (record.type === \"normal\") {\n // If an exception is thrown from innerFn, we leave state ===\n // GenStateExecuting and loop back for another invocation.\n state = context.done\n ? GenStateCompleted\n : GenStateSuspendedYield;\n\n if (record.arg === ContinueSentinel) {\n continue;\n }\n\n return {\n value: record.arg,\n done: context.done\n };\n\n } else if (record.type === \"throw\") {\n state = GenStateCompleted;\n // Dispatch the exception by looping back around to the\n // context.dispatchException(context.arg) call above.\n context.method = \"throw\";\n context.arg = record.arg;\n }\n }\n };\n }\n\n // Call delegate.iterator[context.method](context.arg) and handle the\n // result, either by returning a { value, done } result from the\n // delegate iterator, or by modifying context.method and context.arg,\n // setting context.delegate to null, and returning the ContinueSentinel.\n function maybeInvokeDelegate(delegate, context) {\n var method = delegate.iterator[context.method];\n if (method === undefined) {\n // A .throw or .return when the delegate iterator has no .throw\n // method always terminates the yield* loop.\n context.delegate = null;\n\n if (context.method === \"throw\") {\n // Note: [\"return\"] must be used for ES3 parsing compatibility.\n if (delegate.iterator[\"return\"]) {\n // If the delegate iterator has a return method, give it a\n // chance to clean up.\n context.method = \"return\";\n context.arg = undefined;\n maybeInvokeDelegate(delegate, context);\n\n if (context.method === \"throw\") {\n // If maybeInvokeDelegate(context) changed context.method from\n // \"return\" to \"throw\", let that override the TypeError below.\n return ContinueSentinel;\n }\n }\n\n context.method = \"throw\";\n context.arg = new TypeError(\n \"The iterator does not provide a 'throw' method\");\n }\n\n return ContinueSentinel;\n }\n\n var record = tryCatch(method, delegate.iterator, context.arg);\n\n if (record.type === \"throw\") {\n context.method = \"throw\";\n context.arg = record.arg;\n context.delegate = null;\n return ContinueSentinel;\n }\n\n var info = record.arg;\n\n if (! info) {\n context.method = \"throw\";\n context.arg = new TypeError(\"iterator result is not an object\");\n context.delegate = null;\n return ContinueSentinel;\n }\n\n if (info.done) {\n // Assign the result of the finished delegate to the temporary\n // variable specified by delegate.resultName (see delegateYield).\n context[delegate.resultName] = info.value;\n\n // Resume execution at the desired location (see delegateYield).\n context.next = delegate.nextLoc;\n\n // If context.method was \"throw\" but the delegate handled the\n // exception, let the outer generator proceed normally. If\n // context.method was \"next\", forget context.arg since it has been\n // \"consumed\" by the delegate iterator. If context.method was\n // \"return\", allow the original .return call to continue in the\n // outer generator.\n if (context.method !== \"return\") {\n context.method = \"next\";\n context.arg = undefined;\n }\n\n } else {\n // Re-yield the result returned by the delegate method.\n return info;\n }\n\n // The delegate iterator is finished, so forget it and continue with\n // the outer generator.\n context.delegate = null;\n return ContinueSentinel;\n }\n\n // Define Generator.prototype.{next,throw,return} in terms of the\n // unified ._invoke helper method.\n defineIteratorMethods(Gp);\n\n define(Gp, toStringTagSymbol, \"Generator\");\n\n // A Generator should always return itself as the iterator object when the\n // @@iterator function is called on it. Some browsers' implementations of the\n // iterator prototype chain incorrectly implement this, causing the Generator\n // object to not be returned from this call. This ensures that doesn't happen.\n // See https://github.com/facebook/regenerator/issues/274 for more details.\n Gp[iteratorSymbol] = function() {\n return this;\n };\n\n Gp.toString = function() {\n return \"[object Generator]\";\n };\n\n function pushTryEntry(locs) {\n var entry = { tryLoc: locs[0] };\n\n if (1 in locs) {\n entry.catchLoc = locs[1];\n }\n\n if (2 in locs) {\n entry.finallyLoc = locs[2];\n entry.afterLoc = locs[3];\n }\n\n this.tryEntries.push(entry);\n }\n\n function resetTryEntry(entry) {\n var record = entry.completion || {};\n record.type = \"normal\";\n delete record.arg;\n entry.completion = record;\n }\n\n function Context(tryLocsList) {\n // The root entry object (effectively a try statement without a catch\n // or a finally block) gives us a place to store values thrown from\n // locations where there is no enclosing try statement.\n this.tryEntries = [{ tryLoc: \"root\" }];\n tryLocsList.forEach(pushTryEntry, this);\n this.reset(true);\n }\n\n exports.keys = function(object) {\n var keys = [];\n for (var key in object) {\n keys.push(key);\n }\n keys.reverse();\n\n // Rather than returning an object with a next method, we keep\n // things simple and return the next function itself.\n return function next() {\n while (keys.length) {\n var key = keys.pop();\n if (key in object) {\n next.value = key;\n next.done = false;\n return next;\n }\n }\n\n // To avoid creating an additional object, we just hang the .value\n // and .done properties off the next function object itself. This\n // also ensures that the minifier will not anonymize the function.\n next.done = true;\n return next;\n };\n };\n\n function values(iterable) {\n if (iterable) {\n var iteratorMethod = iterable[iteratorSymbol];\n if (iteratorMethod) {\n return iteratorMethod.call(iterable);\n }\n\n if (typeof iterable.next === \"function\") {\n return iterable;\n }\n\n if (!isNaN(iterable.length)) {\n var i = -1, next = function next() {\n while (++i < iterable.length) {\n if (hasOwn.call(iterable, i)) {\n next.value = iterable[i];\n next.done = false;\n return next;\n }\n }\n\n next.value = undefined;\n next.done = true;\n\n return next;\n };\n\n return next.next = next;\n }\n }\n\n // Return an iterator with no values.\n return { next: doneResult };\n }\n exports.values = values;\n\n function doneResult() {\n return { value: undefined, done: true };\n }\n\n Context.prototype = {\n constructor: Context,\n\n reset: function(skipTempReset) {\n this.prev = 0;\n this.next = 0;\n // Resetting context._sent for legacy support of Babel's\n // function.sent implementation.\n this.sent = this._sent = undefined;\n this.done = false;\n this.delegate = null;\n\n this.method = \"next\";\n this.arg = undefined;\n\n this.tryEntries.forEach(resetTryEntry);\n\n if (!skipTempReset) {\n for (var name in this) {\n // Not sure about the optimal order of these conditions:\n if (name.charAt(0) === \"t\" &&\n hasOwn.call(this, name) &&\n !isNaN(+name.slice(1))) {\n this[name] = undefined;\n }\n }\n }\n },\n\n stop: function() {\n this.done = true;\n\n var rootEntry = this.tryEntries[0];\n var rootRecord = rootEntry.completion;\n if (rootRecord.type === \"throw\") {\n throw rootRecord.arg;\n }\n\n return this.rval;\n },\n\n dispatchException: function(exception) {\n if (this.done) {\n throw exception;\n }\n\n var context = this;\n function handle(loc, caught) {\n record.type = \"throw\";\n record.arg = exception;\n context.next = loc;\n\n if (caught) {\n // If the dispatched exception was caught by a catch block,\n // then let that catch block handle the exception normally.\n context.method = \"next\";\n context.arg = undefined;\n }\n\n return !! caught;\n }\n\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n var record = entry.completion;\n\n if (entry.tryLoc === \"root\") {\n // Exception thrown outside of any try block that could handle\n // it, so set the completion value of the entire function to\n // throw the exception.\n return handle(\"end\");\n }\n\n if (entry.tryLoc <= this.prev) {\n var hasCatch = hasOwn.call(entry, \"catchLoc\");\n var hasFinally = hasOwn.call(entry, \"finallyLoc\");\n\n if (hasCatch && hasFinally) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n } else if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else if (hasCatch) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n }\n\n } else if (hasFinally) {\n if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else {\n throw new Error(\"try statement without catch or finally\");\n }\n }\n }\n },\n\n abrupt: function(type, arg) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc <= this.prev &&\n hasOwn.call(entry, \"finallyLoc\") &&\n this.prev < entry.finallyLoc) {\n var finallyEntry = entry;\n break;\n }\n }\n\n if (finallyEntry &&\n (type === \"break\" ||\n type === \"continue\") &&\n finallyEntry.tryLoc <= arg &&\n arg <= finallyEntry.finallyLoc) {\n // Ignore the finally entry if control is not jumping to a\n // location outside the try/catch block.\n finallyEntry = null;\n }\n\n var record = finallyEntry ? finallyEntry.completion : {};\n record.type = type;\n record.arg = arg;\n\n if (finallyEntry) {\n this.method = \"next\";\n this.next = finallyEntry.finallyLoc;\n return ContinueSentinel;\n }\n\n return this.complete(record);\n },\n\n complete: function(record, afterLoc) {\n if (record.type === \"throw\") {\n throw record.arg;\n }\n\n if (record.type === \"break\" ||\n record.type === \"continue\") {\n this.next = record.arg;\n } else if (record.type === \"return\") {\n this.rval = this.arg = record.arg;\n this.method = \"return\";\n this.next = \"end\";\n } else if (record.type === \"normal\" && afterLoc) {\n this.next = afterLoc;\n }\n\n return ContinueSentinel;\n },\n\n finish: function(finallyLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.finallyLoc === finallyLoc) {\n this.complete(entry.completion, entry.afterLoc);\n resetTryEntry(entry);\n return ContinueSentinel;\n }\n }\n },\n\n \"catch\": function(tryLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc === tryLoc) {\n var record = entry.completion;\n if (record.type === \"throw\") {\n var thrown = record.arg;\n resetTryEntry(entry);\n }\n return thrown;\n }\n }\n\n // The context.catch method must only be called with a location\n // argument that corresponds to a known catch block.\n throw new Error(\"illegal catch attempt\");\n },\n\n delegateYield: function(iterable, resultName, nextLoc) {\n this.delegate = {\n iterator: values(iterable),\n resultName: resultName,\n nextLoc: nextLoc\n };\n\n if (this.method === \"next\") {\n // Deliberately forget the last sent value so that we don't\n // accidentally pass it on to the delegate.\n this.arg = undefined;\n }\n\n return ContinueSentinel;\n }\n };\n\n // Regardless of whether this script is executing as a CommonJS module\n // or not, return the runtime object so that we can declare the variable\n // regeneratorRuntime in the outer scope, which allows this module to be\n // injected easily by `bin/regenerator --include-runtime script.js`.\n return exports;\n\n}(\n // If this script is executing as a CommonJS module, use module.exports\n // as the regeneratorRuntime namespace. Otherwise create a new empty\n // object. Either way, the resulting object will be used to initialize\n // the regeneratorRuntime variable at the top of this file.\n typeof module === \"object\" ? module.exports : {}\n));\n\ntry {\n regeneratorRuntime = runtime;\n} catch (accidentalStrictMode) {\n // This module should not be running in strict mode, so the above\n // assignment should always work unless something is misconfigured. Just\n // in case runtime.js accidentally runs in strict mode, we can escape\n // strict mode using a global Function call. This could conceivably fail\n // if a Content Security Policy forbids using Function, but in that case\n // the proper solution is to fix the accidental strict mode problem. If\n // you've misconfigured your bundler to force strict mode and applied a\n // CSP to forbid Function, and you're not willing to fix either of those\n // problems, please detail your unique predicament in a GitHub issue.\n Function(\"r\", \"regeneratorRuntime = r\")(runtime);\n}\n","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\n/**\r\n * Basic authentication stages used to determine\r\n * appropriate action after redirect occurs\r\n */\r\nexport const AppStages = {\r\n SIGN_IN: \"sign_in\",\r\n SIGN_OUT: \"sign_out\",\r\n ACQUIRE_TOKEN: \"acquire_token\",\r\n};\r\n\r\n/**\r\n * String constants related to AAD Authority\r\n */\r\nexport const AADAuthorityConstants = {\r\n COMMON: \"common\",\r\n ORGANIZATIONS: \"organizations\",\r\n CONSUMERS: \"consumers\"\r\n}\r\n\r\n/**\r\n * String constants related to AAD Authority\r\n */\r\nexport const KeyVaultCredentialTypes = {\r\n SECRET: \"secret\",\r\n CERTIFICATE: \"certificate\",\r\n}\r\n\r\n/**\r\n * Constants used in access control scenarios\r\n */\r\nexport const AccessConstants = {\r\n GROUPS: \"groups\",\r\n ROLES: \"roles\",\r\n CLAIM_NAMES: \"_claim_name\",\r\n CLAIM_SOURCES: \"_claim_sources\",\r\n PAGINATION_LINK: \"@odata.nextLink\",\r\n GRAPH_MEMBERS_ENDPOINT: \"https://graph.microsoft.com/v1.0/me/memberOf\",\r\n GRAPH_MEMBER_SCOPES: \"User.Read GroupMember.Read.All\"\r\n};\r\n\r\nexport const InfoMessages = {\r\n REQUEST_FOR_RESOURCE: \"Request made to web API\",\r\n OVERAGE_OCCURRED: \"User has too many groups. Groups overage claim occurred\"\r\n}\r\n\r\n/**\r\n * Various error constants\r\n */\r\nexport const ErrorMessages = {\r\n NOT_PERMITTED: \"Not permitted\",\r\n INVALID_TOKEN: \"Invalid token\",\r\n CANNOT_DETERMINE_APP_STAGE: \"Cannot determine application stage\",\r\n CANNOT_VALIDATE_TOKEN: \"Cannot validate token\",\r\n NONCE_MISMATCH: \"Nonce does not match\",\r\n INTERACTION_REQUIRED: \"interaction_required\",\r\n TOKEN_ACQUISITION_FAILED: \"Token acquisition failed\",\r\n AUTH_CODE_NOT_OBTAINED: \"Authorization code cannot be obtained\",\r\n TOKEN_NOT_FOUND: \"No token found\",\r\n TOKEN_NOT_DECODED: \"Token cannot be decoded\",\r\n TOKEN_NOT_VERIFIED: \"Token cannot be verified\",\r\n KEYS_NOT_OBTAINED: \"Signing keys cannot be obtained\",\r\n STATE_NOT_FOUND: \"State not found\",\r\n USER_HAS_NO_ROLE: \"User does not have any roles\",\r\n USER_NOT_IN_ROLE: \"User does not have this role\",\r\n USER_HAS_NO_GROUP: \"User does not have any groups\",\r\n USER_NOT_IN_GROUP: \"User does not have this group\",\r\n METHOD_NOT_ALLOWED: \"Method not allowed for this route\",\r\n RULE_NOT_FOUND: \"No rule found for this route\",\r\n SESSION_NOT_FOUND: \"No session found for this request\",\r\n KEY_VAULT_CONFIG_NOT_FOUND: \"No coordinates found for Key Vault\"\r\n};\r\n\r\nexport const ConfigurationErrorMessages = {\r\n NO_CLIENT_ID: \"No clientId provided!\",\r\n INVALID_CLIENT_ID: \"Invalid clientId!\",\r\n NO_TENANT_INFO: \"No tenant info provided!\",\r\n INVALID_TENANT_INFO: \"Invalid tenant info!\",\r\n NO_CLIENT_CREDENTIAL: \"No client credential provided!\",\r\n NO_REDIRECT_URI: \"No redirect URI provided!\",\r\n NO_ERROR_ROUTE: \"No error route provided!\",\r\n NO_UNAUTHORIZED_ROUTE: \"No unauthorized route provided!\"\r\n}\r\n\r\n/**\r\n * For more information, visit: https://login.microsoftonline.com/error\r\n */\r\nexport const ErrorCodes = {\r\n 65001: \"AADSTS65001\", // consent required\r\n};","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { \r\n UrlString, \r\n StringUtils,\r\n Constants, \r\n} from \"@azure/msal-common\";\r\n\r\nimport { \r\n ICachePlugin,\r\n Configuration,\r\n LogLevel \r\n} from \"@azure/msal-node\";\r\n\r\nimport { AppSettings } from \"./Types\";\r\n\r\nimport { \r\n AADAuthorityConstants, \r\n ConfigurationErrorMessages \r\n} from \"./Constants\";\r\n\r\nexport class ConfigurationUtils {\r\n\r\n /**\r\n * Validates the fields in the configuration file\r\n * @param {AppSettings} config: configuration object\r\n * @returns {void}\r\n */\r\n static validateAppSettings(config: AppSettings): void {\r\n if (StringUtils.isEmpty(config.appCredentials.clientId)) {\r\n throw new Error(ConfigurationErrorMessages.NO_CLIENT_ID);\r\n } else if (!ConfigurationUtils.isGuid(config.appCredentials.clientId)) {\r\n throw new Error(ConfigurationErrorMessages.INVALID_CLIENT_ID);\r\n }\r\n\r\n if (StringUtils.isEmpty(config.appCredentials.tenantId)) {\r\n throw new Error(ConfigurationErrorMessages.NO_TENANT_INFO);\r\n } else if (!ConfigurationUtils.isGuid(config.appCredentials.tenantId) && !Object.values(AADAuthorityConstants).includes(config.appCredentials.tenantId)) {\r\n throw new Error(ConfigurationErrorMessages.INVALID_TENANT_INFO);\r\n }\r\n\r\n if (StringUtils.isEmpty(config.appCredentials.clientSecret) && !config.appCredentials.clientCertificate) {\r\n throw new Error(ConfigurationErrorMessages.NO_CLIENT_CREDENTIAL);\r\n }\r\n\r\n if (StringUtils.isEmpty(config.authRoutes.redirect)) {\r\n throw new Error(ConfigurationErrorMessages.NO_REDIRECT_URI);\r\n }\r\n\r\n if (StringUtils.isEmpty(config.authRoutes.error)) {\r\n throw new Error(ConfigurationErrorMessages.NO_ERROR_ROUTE);\r\n }\r\n\r\n if (StringUtils.isEmpty(config.authRoutes.unauthorized)) {\r\n throw new Error(ConfigurationErrorMessages.NO_UNAUTHORIZED_ROUTE);\r\n }\r\n };\r\n\r\n\r\n /**\r\n * Maps the custom configuration object to configuration\r\n * object expected by MSAL Node ConfidentialClientApplication class\r\n * @param {AppSettings} config: configuration object\r\n * @param {ICachePlugin} cachePlugin: persistent cache implementation\r\n * @returns {Configuration}\r\n */\r\n static getMsalConfiguration(config: AppSettings, cachePlugin: ICachePlugin = null): Configuration {\r\n return {\r\n auth: {\r\n clientId: config.appCredentials.clientId,\r\n authority: config.b2cPolicies ?\r\n Object.entries(config.b2cPolicies)[0][1][\"authority\"]\r\n :\r\n `https://${Constants.DEFAULT_AUTHORITY_HOST}/${config.appCredentials.tenantId}`,\r\n ...(config.appCredentials.hasOwnProperty(\"clientSecret\")) && { clientSecret: config.appCredentials.clientSecret },\r\n ...(config.appCredentials.hasOwnProperty(\"clientCertificate\")) && { clientCertificate: config.appCredentials.clientCertificate },\r\n knownAuthorities: config.b2cPolicies ?\r\n [UrlString.getDomainFromUrl(Object.entries(config.b2cPolicies)[0][1][\"authority\"])] // in B2C scenarios\r\n :\r\n [],\r\n },\r\n cache: {\r\n cachePlugin,\r\n },\r\n system: {\r\n loggerOptions: {\r\n loggerCallback: (logLevel, message, containsPii) => {\r\n if (containsPii) {\r\n return;\r\n }\r\n switch (logLevel) {\r\n case LogLevel.Error:\r\n console.error(message);\r\n return;\r\n case LogLevel.Info:\r\n console.info(message);\r\n return;\r\n case LogLevel.Verbose:\r\n console.debug(message);\r\n return;\r\n case LogLevel.Warning:\r\n console.warn(message);\r\n return;\r\n }\r\n },\r\n piiLoggingEnabled: false,\r\n logLevel: LogLevel.Verbose,\r\n },\r\n },\r\n };\r\n };\r\n\r\n /**\r\n * verifies if a string is GUID\r\n * @param guid\r\n */\r\n static isGuid(guid: string): boolean {\r\n const regexGuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\r\n return regexGuid.test(guid);\r\n }\r\n}\r\n","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { LogLevel } from \"@azure/msal-common\"\r\n\r\nexport class Logger {\r\n\r\n /**\r\n * Log an error\r\n * @param {string} log\r\n * @returns {void}\r\n */\r\n static logError(log: string): void {\r\n console.error(this.logMessage(log));\r\n }\r\n\r\n /**\r\n * Log a warning\r\n * @param {string} log\r\n * @returns {void}\r\n */\r\n static logWarning(log: string): void {\r\n console.warn(this.logMessage(log));\r\n }\r\n\r\n /**\r\n * Log anything\r\n * @param {string} log\r\n * @returns {void}\r\n */\r\n static logInfo(log: string): void {\r\n console.info(this.logMessage(log));\r\n }\r\n\r\n /**\r\n * Log message with required options.\r\n * @param {string} logMessage \r\n * @returns {string}\r\n */\r\n private static logMessage(logMessage: string): string {\r\n const timestamp = new Date().toUTCString();\r\n\r\n let logHeader: string = `[${timestamp}]`;\r\n\r\n const log = `${logHeader} : @azure-samples/msal-express-wrapper@0.1.0 : ${LogLevel[LogLevel.Verbose]} - ${logMessage}`;\r\n return log;\r\n }\r\n\r\n}","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport jwt from \"jsonwebtoken\";\r\nimport jwksClient from \"jwks-rsa\";\r\n\r\nimport { \r\n StringUtils, \r\n Constants, \r\n TokenClaims \r\n} from \"@azure/msal-common\";\r\n\r\nimport { Configuration } from \"@azure/msal-node\";\r\n\r\nimport { Logger } from \"./Logger\";\r\n\r\nimport { \r\n AppSettings,\r\n Resource, \r\n IdTokenClaims, \r\n AccessTokenClaims \r\n} from \"./Types\";\r\n\r\nimport { \r\n ErrorMessages, \r\n AADAuthorityConstants \r\n} from \"./Constants\";\r\n\r\nexport class TokenValidator {\r\n private appSettings: AppSettings;\r\n private msalConfig: Configuration;\r\n\r\n /**\r\n * @param {AppSettings} appSettings \r\n * @param {Configuration} msalConfig\r\n * @constructor\r\n */\r\n constructor(appSettings: AppSettings, msalConfig: Configuration) {\r\n this.appSettings = appSettings;\r\n this.msalConfig = msalConfig;\r\n }\r\n\r\n /**\r\n * Verifies a given token's signature using jwks-rsa\r\n * @param {string} authToken \r\n * @returns {Promise}\r\n */\r\n async verifyTokenSignature(authToken: string): Promise {\r\n if (StringUtils.isEmpty(authToken)) {\r\n Logger.logError(ErrorMessages.TOKEN_NOT_FOUND);\r\n return false;\r\n }\r\n\r\n // we will first decode to get kid parameter in header\r\n let decodedToken;\r\n\r\n try {\r\n decodedToken = jwt.decode(authToken, { complete: true });\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.TOKEN_NOT_DECODED);\r\n console.log(error);\r\n return false;\r\n }\r\n\r\n // obtains signing keys from discovery endpoint\r\n let keys;\r\n\r\n try {\r\n keys = await this.getSigningKeys(decodedToken.header, decodedToken.payload.tid);\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.KEYS_NOT_OBTAINED);\r\n console.log(error);\r\n return false;\r\n }\r\n\r\n // verify the signature at header section using keys\r\n let verifiedToken: TokenClaims;\r\n\r\n try {\r\n verifiedToken = jwt.verify(authToken, keys);\r\n\r\n /**\r\n * if a multiplexer was used in place of tenantId i.e. if the app\r\n * is multi-tenant, the tenantId should be obtained from the user\"s\r\n * token\"s tid claim for verification purposes\r\n */\r\n if (\r\n this.appSettings.appCredentials.tenantId === AADAuthorityConstants.COMMON ||\r\n this.appSettings.appCredentials.tenantId === AADAuthorityConstants.ORGANIZATIONS ||\r\n this.appSettings.appCredentials.tenantId === AADAuthorityConstants.CONSUMERS\r\n ) {\r\n this.appSettings.appCredentials.tenantId = decodedToken.payload.tid;\r\n }\r\n\r\n return verifiedToken;\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.TOKEN_NOT_VERIFIED);\r\n console.log(error);\r\n return false;\r\n }\r\n };\r\n\r\n /**\r\n * Verifies the access token for signature\r\n * @param {string} idToken: raw Id token\r\n * @returns {Promise}\r\n */\r\n async validateIdToken(idToken: string): Promise {\r\n try {\r\n const verifiedToken = await this.verifyTokenSignature(idToken);\r\n\r\n if (verifiedToken) {\r\n return this.validateIdTokenClaims(verifiedToken as IdTokenClaims);\r\n } else {\r\n return false;\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n return false;\r\n }\r\n };\r\n\r\n /**\r\n * Validates the id token for a set of claims\r\n * @param {IdTokenClaims} idTokenClaims: decoded id token claims\r\n * @returns {boolean}\r\n */\r\n validateIdTokenClaims(idTokenClaims: IdTokenClaims): boolean {\r\n const now = Math.round(new Date().getTime() / 1000); // in UNIX format\r\n\r\n /**\r\n * At the very least, check for issuer, audience, issue and expiry dates.\r\n * For more information on validating id tokens, visit:\r\n * https://docs.microsoft.com/azure/active-directory/develop/id-tokens#validating-an-id_token\r\n */\r\n const checkIssuer = idTokenClaims.iss.includes(this.appSettings.appCredentials.tenantId) ? true : false;\r\n const checkAudience = idTokenClaims.aud === this.msalConfig.auth.clientId ? true : false;\r\n const checkTimestamp = idTokenClaims.iat <= now && idTokenClaims.exp >= now ? true : false;\r\n\r\n return checkIssuer && checkAudience && checkTimestamp;\r\n };\r\n\r\n /**\r\n * Verifies the access token for signature\r\n * @param {string} accessToken: raw JWT token\r\n * @param {string} protectedRoute: used for checking scope\r\n * @returns {Promise}\r\n */\r\n async verifyAccessTokenSignature(accessToken: string, protectedRoute: string): Promise {\r\n try {\r\n const verifiedToken = await this.verifyTokenSignature(accessToken);\r\n\r\n if (verifiedToken) {\r\n return this.validateAccessTokenClaims(verifiedToken as AccessTokenClaims, protectedRoute);\r\n } else {\r\n return false;\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n return false;\r\n }\r\n };\r\n\r\n /**\r\n * Validates the access token for a set of claims\r\n * @param {TokenClaims} verifiedToken: token with a verified signature\r\n * @param {string} protectedRoute: route where this token is required to access\r\n * @returns {boolean}\r\n */\r\n validateAccessTokenClaims(verifiedToken: AccessTokenClaims, protectedRoute: string): boolean {\r\n const now = Math.round(new Date().getTime() / 1000); // in UNIX format\r\n\r\n /**\r\n * At the very least, validate the token with respect to issuer, audience, scope\r\n * and timestamp, though implementation and extent vary. For more information, visit:\r\n * https://docs.microsoft.com/azure/active-directory/develop/access-tokens#validating-tokens\r\n */\r\n const checkIssuer = verifiedToken.iss.includes(this.appSettings.appCredentials.tenantId) ? true : false;\r\n const checkTimestamp = verifiedToken.iat <= now && verifiedToken.iat >= now ? true : false;\r\n\r\n const checkAudience = verifiedToken.aud === this.appSettings.appCredentials.clientId ||\r\n verifiedToken.aud === \"api://\" + this.appSettings.appCredentials.clientId ? true : false;\r\n\r\n const checkScopes = Object.values(this.appSettings.ownedResources).find((resource: Resource) => resource.endpoint === protectedRoute)\r\n .scopes.every(scp => verifiedToken.scp.includes(scp));\r\n\r\n return checkAudience && checkIssuer && checkTimestamp && checkScopes;\r\n };\r\n\r\n /**\r\n * Fetches signing keys of an access token\r\n * from the authority discovery endpoint\r\n * @param {Object} header: token header\r\n * @param {string} tid: tenant id\r\n * @returns {Promise}\r\n */\r\n private async getSigningKeys(header, tid: string): Promise {\r\n let jwksUri;\r\n\r\n // Check if a B2C application i.e. app has b2cPolicies\r\n if (this.appSettings.b2cPolicies) {\r\n jwksUri = `${this.msalConfig.auth.authority}/discovery/v2.0/keys`;\r\n } else {\r\n jwksUri = `https://${Constants.DEFAULT_AUTHORITY_HOST}/${tid}/discovery/v2.0/keys`;\r\n }\r\n\r\n const client = jwksClient({\r\n jwksUri: jwksUri,\r\n });\r\n\r\n return (await client.getSigningKeyAsync(header.kid)).getPublicKey();\r\n };\r\n}\r\n","import { CertificateClient, KeyVaultCertificate } from \"@azure/keyvault-certificates\";\r\nimport { DefaultAzureCredential } from \"@azure/identity\";\r\nimport { KeyVaultSecret, SecretClient } from \"@azure/keyvault-secrets\";\r\n\r\nimport { AppSettings } from \"./Types\";\r\nimport { KeyVaultCredentialTypes } from \"./Constants\";\r\n\r\nexport class KeyVaultManager {\r\n\r\n /**\r\n * Fetches credentials from Key Vault and updates appSettings\r\n * @param {AppSettings} config \r\n * @returns {Promise}\r\n */\r\n async getCredentialFromKeyVault(config: AppSettings): Promise {\r\n\r\n const credential = new DefaultAzureCredential();\r\n\r\n if (!config.appCredentials.keyVaultCredential) {\r\n return config\r\n }\r\n\r\n switch (config.appCredentials.keyVaultCredential.credentialType) {\r\n case KeyVaultCredentialTypes.SECRET: {\r\n try {\r\n const secretResponse = await this.getSecretCredential(config, credential);\r\n config.appCredentials.clientSecret = secretResponse.value;\r\n return config;\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n break;\r\n }\r\n\r\n case KeyVaultCredentialTypes.CERTIFICATE: {\r\n try {\r\n const certificateResponse = await this.getCertificateCredential(config, credential);\r\n const secretResponse = await this.getSecretCredential(config, credential);\r\n\r\n config.appCredentials.clientCertificate = {\r\n thumbprint: certificateResponse.properties.x509Thumbprint.toString(),\r\n privateKey: secretResponse.value.split('-----BEGIN CERTIFICATE-----\\n')[0]\r\n }\r\n return config;\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n break;\r\n }\r\n\r\n default:\r\n break;\r\n }\r\n };\r\n\r\n /**\r\n * Gets a certificate credential from Key Vault\r\n * @param {AppSettings} config \r\n * @param {DefaultAzureCredential} credential \r\n * @returns {Promise}\r\n */\r\n async getCertificateCredential(config: AppSettings, credential: DefaultAzureCredential): Promise {\r\n\r\n // Initialize secretClient with credentials\r\n const secretClient = new CertificateClient(config.appCredentials.keyVaultCredential.keyVaultUrl, credential);\r\n\r\n try {\r\n const keyVaultCertificate = await secretClient.getCertificate(config.appCredentials.keyVaultCredential.credentialName);\r\n return keyVaultCertificate;\r\n } catch (error) {\r\n console.log(error);\r\n return error;\r\n }\r\n }\r\n\r\n /**\r\n * Gets a secret credential from Key Vault\r\n * @param {AppSettings} config \r\n * @param {DefaultAzureCredential} credential \r\n * @returns {Promise}\r\n */\r\n async getSecretCredential(config: AppSettings, credential: DefaultAzureCredential): Promise {\r\n\r\n // Initialize secretClient with credentials\r\n const secretClient = new SecretClient(config.appCredentials.keyVaultCredential.keyVaultUrl, credential);\r\n\r\n try {\r\n const keyVaultSecret = await secretClient.getSecret(config.appCredentials.keyVaultCredential.credentialName);\r\n return keyVaultSecret;\r\n } catch (error) {\r\n console.log(error);\r\n return error;\r\n }\r\n }\r\n}","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport axios, { AxiosResponse, AxiosRequestConfig } from \"axios\";\r\nimport { StringUtils } from \"@azure/msal-common\";\r\n\r\nimport { \r\n AccessConstants, \r\n InfoMessages, \r\n ErrorMessages \r\n} from \"./Constants\";\r\n\r\nimport { Logger } from \"./Logger\";\r\n\r\nexport class FetchManager {\r\n\r\n /**\r\n * Calls a resource endpoint with a raw access token\r\n * using the authorization bearer token scheme\r\n * @param {string} endpoint \r\n * @param {string} accessToken \r\n * @returns {Promise}\r\n */\r\n static callApiEndpoint = async (endpoint: string, accessToken: string): Promise => {\r\n\r\n if (StringUtils.isEmpty(accessToken)) {\r\n throw new Error(ErrorMessages.TOKEN_NOT_FOUND)\r\n }\r\n\r\n const options: AxiosRequestConfig = {\r\n headers: {\r\n Authorization: `Bearer ${accessToken}`\r\n }\r\n };\r\n\r\n try {\r\n Logger.logInfo(InfoMessages.REQUEST_FOR_RESOURCE);\r\n const response: AxiosResponse = await axios.get(endpoint, options);\r\n return response.data;\r\n } catch (error) {\r\n console.log(error)\r\n return error;\r\n }\r\n }\r\n\r\n /**\r\n * Handles queries against Microsoft Graph that return multiple pages of data \r\n * @param {string} accessToken: access token required by endpoint \r\n * @param {string} nextPage: next page link\r\n * @param {Array} data: stores data from each page\r\n * @returns {Promise}\r\n */\r\n static handlePagination = async (accessToken: string, nextPage: string, data: string[] = []): Promise => {\r\n\r\n try {\r\n const graphResponse = await FetchManager.callApiEndpoint(nextPage, accessToken);\r\n graphResponse[\"value\"].map((v) => data.push(v.id));\r\n \r\n if (graphResponse[AccessConstants.PAGINATION_LINK]) {\r\n return await FetchManager.handlePagination(accessToken, graphResponse[AccessConstants.PAGINATION_LINK], data)\r\n } else {\r\n return data;\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n return error;\r\n }\r\n \r\n }\r\n\r\n}\r\n","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { Request } from \"express\";\r\nimport { IUri, UrlString } from \"@azure/msal-common\";\r\n\r\nexport class UrlUtils {\r\n /**\r\n * Gets the absolute URL from a given request and path string\r\n * @param {Request} req: express request object \r\n * @param {string} url: a given URL\r\n * @returns {string}\r\n */\r\n static ensureAbsoluteUrl = (req: Request, url: string): string => {\r\n const urlComponents: IUri = new UrlString(url).getUrlComponents();\r\n\r\n if (!urlComponents.Protocol) {\r\n if (!urlComponents.HostNameAndPort) {\r\n return req.protocol + \"://\" + req.get(\"host\") + url;\r\n }\r\n return req.protocol + \"://\" + url;\r\n } else {\r\n return url;\r\n }\r\n };\r\n}\r\n","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\nimport express from \"express\";\r\n\r\nimport {\r\n RequestHandler,\r\n Request,\r\n Response,\r\n NextFunction,\r\n Router\r\n} from \"express\";\r\n\r\nimport {\r\n InteractionRequiredAuthError,\r\n OIDC_DEFAULT_SCOPES,\r\n PromptValue,\r\n StringUtils,\r\n} from \"@azure/msal-common\";\r\n\r\nimport {\r\n ConfidentialClientApplication,\r\n Configuration,\r\n AccountInfo,\r\n ICachePlugin,\r\n CryptoProvider,\r\n AuthorizationUrlRequest,\r\n AuthorizationCodeRequest,\r\n SilentFlowRequest,\r\n OnBehalfOfRequest,\r\n} from \"@azure/msal-node\";\r\n\r\nimport { ConfigurationUtils } from \"./ConfigurationUtils\";\r\nimport { TokenValidator } from \"./TokenValidator\";\r\nimport { KeyVaultManager } from \"./KeyVaultManager\";\r\nimport { FetchManager } from \"./FetchManager\";\r\nimport { UrlUtils } from \"./UrlUtils\";\r\nimport { Logger } from \"./Logger\";\r\n\r\nimport {\r\n Resource,\r\n AppSettings,\r\n AuthCodeParams,\r\n InitializationOptions,\r\n TokenRequestOptions,\r\n GuardOptions,\r\n AccessRule,\r\n SignInOptions,\r\n SignOutOptions,\r\n HandleRedirectOptions\r\n} from \"./Types\";\r\n\r\nimport {\r\n AppStages,\r\n ErrorMessages,\r\n AccessConstants,\r\n InfoMessages\r\n} from \"./Constants\";\r\n\r\n/**\r\n * A simple wrapper around MSAL Node ConfidentialClientApplication object.\r\n * It offers a collection of middleware and utility methods that automate\r\n * basic authentication and authorization tasks in Express MVC web apps and\r\n * RESTful APIs (coming soon).\r\n */\r\nexport class AuthProvider {\r\n appSettings: AppSettings;\r\n private msalConfig: Configuration;\r\n private cryptoProvider: CryptoProvider;\r\n private tokenValidator: TokenValidator;\r\n private msalClient: ConfidentialClientApplication;\r\n\r\n /**\r\n * @param {AppSettings} appSettings\r\n * @param {ICachePlugin} cache: cachePlugin\r\n * @constructor\r\n */\r\n constructor(appSettings: AppSettings, cache?: ICachePlugin) {\r\n ConfigurationUtils.validateAppSettings(appSettings);\r\n this.appSettings = appSettings;\r\n\r\n this.msalConfig = ConfigurationUtils.getMsalConfiguration(appSettings, cache);\r\n this.msalClient = new ConfidentialClientApplication(this.msalConfig);\r\n\r\n this.tokenValidator = new TokenValidator(this.appSettings, this.msalConfig);\r\n this.cryptoProvider = new CryptoProvider();\r\n }\r\n\r\n /**\r\n * Asynchronously builds authProvider object with credentials fetched from Key Vault\r\n * @param {AppSettings} appSettings\r\n * @param {ICachePlugin} cache: cachePlugin\r\n * @returns \r\n */\r\n static async buildAsync(appSettings: AppSettings, cache?: ICachePlugin): Promise {\r\n try {\r\n const keyVault = new KeyVaultManager();\r\n const appSettingsWithKeyVaultCredentials = await keyVault.getCredentialFromKeyVault(appSettings);\r\n const authProvider = new AuthProvider(appSettingsWithKeyVaultCredentials, cache);\r\n return authProvider;\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n }\r\n\r\n /**\r\n * Initialize AuthProvider and set default routes and handlers\r\n * @param {InitializationOptions} options\r\n * @returns {Router}\r\n */\r\n initialize = (options?: InitializationOptions): Router => {\r\n\r\n // TODO: initialize app defaults\r\n\r\n const appRouter = express.Router();\r\n\r\n // handle redirect\r\n appRouter.get(this.appSettings.authRoutes.redirect, this.handleRedirect());\r\n\r\n if (this.appSettings.authRoutes.frontChannelLogout) {\r\n /**\r\n * Expose front-channel logout route. For more information, visit: \r\n * https://docs.microsoft.com/azure/active-directory/develop/v2-protocols-oidc#single-sign-out\r\n */\r\n appRouter.get(this.appSettings.authRoutes.frontChannelLogout, (req, res, next) => {\r\n req.session.destroy(() => {\r\n res.sendStatus(200);\r\n });\r\n });\r\n }\r\n\r\n return appRouter;\r\n }\r\n\r\n // ========== ROUTE HANDLERS ===========\r\n\r\n /**\r\n * Initiates sign in flow\r\n * @param {SignInOptions} options: options to modify login request\r\n * @returns {RequestHandler}\r\n */\r\n signIn = (options?: SignInOptions): RequestHandler => {\r\n return (req: Request, res: Response, next: NextFunction): Promise => {\r\n /**\r\n * Request Configuration\r\n * We manipulate these three request objects below\r\n * to acquire a token with the appropriate claims\r\n */\r\n if (!req.session[\"authCodeRequest\"]) {\r\n req.session.authCodeRequest = {\r\n authority: \"\",\r\n scopes: [],\r\n state: {},\r\n redirectUri: \"\",\r\n } as AuthorizationUrlRequest;\r\n }\r\n\r\n if (!req.session[\"tokenRequest\"]) {\r\n req.session.tokenRequest = {\r\n authority: \"\",\r\n scopes: [],\r\n redirectUri: \"\",\r\n code: \"\",\r\n } as AuthorizationCodeRequest;\r\n }\r\n\r\n // signed-in user's account\r\n if (!req.session[\"account\"]) {\r\n req.session.account = {\r\n homeAccountId: \"\",\r\n environment: \"\",\r\n tenantId: \"\",\r\n username: \"\",\r\n idTokenClaims: {},\r\n } as AccountInfo;\r\n }\r\n\r\n // random GUID for csrf protection\r\n req.session.nonce = this.cryptoProvider.createNewGuid();\r\n \r\n // TODO: encrypt state parameter \r\n const state = this.cryptoProvider.base64Encode(\r\n JSON.stringify({\r\n stage: AppStages.SIGN_IN,\r\n path: options.successRedirect,\r\n nonce: req.session.nonce,\r\n })\r\n );\r\n\r\n const params: AuthCodeParams = {\r\n authority: this.msalConfig.auth.authority,\r\n scopes: OIDC_DEFAULT_SCOPES,\r\n state: state,\r\n redirect: UrlUtils.ensureAbsoluteUrl(req, this.appSettings.authRoutes.redirect),\r\n prompt: PromptValue.SELECT_ACCOUNT,\r\n };\r\n\r\n // get url to sign user in\r\n return this.getAuthCode(req, res, next, params);\r\n }\r\n };\r\n\r\n /**\r\n * Initiate sign out and destroy the session\r\n * @param options: options to modify logout request \r\n * @returns {RequestHandler}\r\n */\r\n signOut = (options?: SignOutOptions): RequestHandler => {\r\n return (req: Request, res: Response, next: NextFunction): void => {\r\n const postLogoutRedirectUri = UrlUtils.ensureAbsoluteUrl(req, options.successRedirect);\r\n\r\n /**\r\n * Construct a logout URI and redirect the user to end the\r\n * session with Azure AD/B2C. For more information, visit:\r\n * (AAD) https://docs.microsoft.com/azure/active-directory/develop/v2-protocols-oidc#send-a-sign-out-request\r\n * (B2C) https://docs.microsoft.com/azure/active-directory-b2c/openid-connect#send-a-sign-out-request\r\n */\r\n const logoutURI = `${this.msalConfig.auth.authority}/oauth2/v2.0/logout?post_logout_redirect_uri=${postLogoutRedirectUri}`;\r\n\r\n req.session.isAuthenticated = false;\r\n\r\n req.session.destroy(() => {\r\n res.redirect(logoutURI);\r\n });\r\n }\r\n };\r\n\r\n /**\r\n * Middleware that handles redirect depending on request state\r\n * There are basically 2 stages: sign-in and acquire token\r\n * @param {HandleRedirectOptions} options: options to modify this middleware\r\n * @returns {RequestHandler}\r\n */\r\n private handleRedirect = (options?: HandleRedirectOptions): RequestHandler => {\r\n return async (req: Request, res: Response, next: NextFunction): Promise => {\r\n if (req.query.state) {\r\n const state = JSON.parse(this.cryptoProvider.base64Decode(req.query.state as string));\r\n\r\n // check if nonce matches\r\n if (state.nonce === req.session.nonce) {\r\n switch (state.stage) {\r\n case AppStages.SIGN_IN: {\r\n // token request should have auth code\r\n req.session.tokenRequest.code = req.query.code as string;\r\n\r\n try {\r\n // exchange auth code for tokens\r\n const tokenResponse = await this.msalClient.acquireTokenByCode(req.session.tokenRequest);\r\n\r\n try {\r\n const isIdTokenValid = await this.tokenValidator.validateIdToken(tokenResponse.idToken);\r\n\r\n if (isIdTokenValid) {\r\n // assign session variables\r\n req.session.account = tokenResponse.account;\r\n req.session.isAuthenticated = true;\r\n\r\n res.redirect(state.path);\r\n } else {\r\n Logger.logError(ErrorMessages.INVALID_TOKEN);\r\n res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.CANNOT_VALIDATE_TOKEN);\r\n next(error)\r\n }\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.TOKEN_ACQUISITION_FAILED);\r\n next(error)\r\n }\r\n break;\r\n }\r\n\r\n case AppStages.ACQUIRE_TOKEN: {\r\n // get the name of the resource associated with scope\r\n const resourceName = this.getResourceNameFromScopes(req.session.tokenRequest.scopes);\r\n\r\n req.session.tokenRequest.code = req.query.code as string\r\n\r\n try {\r\n const tokenResponse = await this.msalClient.acquireTokenByCode(req.session.tokenRequest);\r\n req.session.remoteResources[resourceName].accessToken = tokenResponse.accessToken;\r\n res.redirect(state.path);\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.TOKEN_ACQUISITION_FAILED);\r\n next(error);\r\n }\r\n break;\r\n }\r\n\r\n default:\r\n Logger.logError(ErrorMessages.CANNOT_DETERMINE_APP_STAGE);\r\n res.redirect(this.appSettings.authRoutes.error);\r\n break;\r\n }\r\n } else {\r\n Logger.logError(ErrorMessages.NONCE_MISMATCH);\r\n res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n } else {\r\n Logger.logError(ErrorMessages.STATE_NOT_FOUND)\r\n res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n }\r\n };\r\n\r\n // ========== MIDDLEWARE ===========\r\n\r\n /**\r\n * Middleware that gets tokens via acquireToken*\r\n * @param {TokenRequestOptions} options: options to modify this middleware\r\n * @returns {RequestHandler}\r\n */\r\n getToken = (options: TokenRequestOptions): RequestHandler => {\r\n return async (req: Request, res: Response, next: NextFunction): Promise => {\r\n // get scopes for token request\r\n const scopes = options.resource.scopes;\r\n\r\n const resourceName = this.getResourceNameFromScopes(scopes)\r\n\r\n if (!req.session.remoteResources) {\r\n req.session.remoteResources = {};\r\n }\r\n\r\n req.session.remoteResources = {\r\n [resourceName]: {\r\n ...this.appSettings.remoteResources[resourceName],\r\n accessToken: null,\r\n } as Resource\r\n };\r\n\r\n try {\r\n const silentRequest: SilentFlowRequest = {\r\n account: req.session.account,\r\n scopes: scopes,\r\n };\r\n\r\n // acquire token silently to be used in resource call\r\n const tokenResponse = await this.msalClient.acquireTokenSilent(silentRequest);\r\n\r\n // In B2C scenarios, sometimes an access token is returned empty.\r\n // In that case, we will acquire token interactively instead.\r\n if (StringUtils.isEmpty(tokenResponse.accessToken)) {\r\n Logger.logError(ErrorMessages.TOKEN_NOT_FOUND);\r\n throw new InteractionRequiredAuthError(ErrorMessages.INTERACTION_REQUIRED);\r\n }\r\n\r\n req.session.remoteResources[resourceName].accessToken = tokenResponse.accessToken;\r\n next();\r\n } catch (error) {\r\n // in case there are no cached tokens, initiate an interactive call\r\n if (error instanceof InteractionRequiredAuthError) {\r\n const state = this.cryptoProvider.base64Encode(\r\n JSON.stringify({\r\n stage: AppStages.ACQUIRE_TOKEN,\r\n path: req.originalUrl,\r\n nonce: req.session.nonce,\r\n })\r\n );\r\n\r\n const params: AuthCodeParams = {\r\n authority: this.msalConfig.auth.authority,\r\n scopes: scopes,\r\n state: state,\r\n redirect: UrlUtils.ensureAbsoluteUrl(req, this.appSettings.authRoutes.redirect),\r\n account: req.session.account,\r\n };\r\n\r\n // initiate the first leg of auth code grant to get token\r\n return this.getAuthCode(req, res, next, params);\r\n } else {\r\n next(error);\r\n }\r\n }\r\n }\r\n };\r\n\r\n /**\r\n * Middleware that gets tokens via OBO flow. Used in web API scenarios\r\n * @param {TokenRequestOptions} options: options to modify this middleware\r\n * @returns {RequestHandler}\r\n */\r\n getTokenOnBehalf = (options: TokenRequestOptions): RequestHandler => {\r\n return async (req: Request, res: Response, next: NextFunction): Promise => {\r\n const authHeader = req.headers.authorization;\r\n\r\n // get scopes for token request\r\n const scopes = options.resource.scopes;\r\n const resourceName = this.getResourceNameFromScopes(scopes);\r\n\r\n const oboRequest: OnBehalfOfRequest = {\r\n oboAssertion: authHeader.split(\" \")[1],\r\n scopes: scopes,\r\n }\r\n\r\n try {\r\n const tokenResponse = await this.msalClient.acquireTokenOnBehalfOf(oboRequest);\r\n\r\n // as OBO is commonly used in middle-tier web APIs without sessions, attach AT to req\r\n req[\"locals\"] = {\r\n [resourceName]: {\r\n accessToken: tokenResponse.accessToken\r\n }\r\n }\r\n\r\n next();\r\n } catch (error) {\r\n next(error);\r\n }\r\n }\r\n }\r\n\r\n // ============== GUARDS ===============\r\n\r\n /**\r\n * Check if authenticated in session\r\n * @param {GuardOptions} options: options to modify this middleware\r\n * @returns {RequestHandler}\r\n */\r\n isAuthenticated = (options?: GuardOptions): RequestHandler => {\r\n return (req: Request, res: Response, next: NextFunction): void => {\r\n if (req.session) {\r\n if (!req.session.isAuthenticated) {\r\n Logger.logError(ErrorMessages.NOT_PERMITTED);\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n\r\n next();\r\n } else {\r\n Logger.logError(ErrorMessages.SESSION_NOT_FOUND);\r\n res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n }\r\n };\r\n\r\n /**\r\n * Receives access token in req authorization header\r\n * and validates it using the jwt.verify\r\n * @param {GuardOptions} options: options to modify this middleware\r\n * @returns {RequestHandler}\r\n */\r\n isAuthorized = (options?: GuardOptions): RequestHandler => {\r\n return async (req: Request, res: Response, next: NextFunction): Promise => {\r\n const accessToken = req.headers.authorization.split(\" \")[1];\r\n\r\n if (req.headers.authorization) {\r\n if (!(await this.tokenValidator.verifyAccessTokenSignature(accessToken, `${req.baseUrl}${req.path}`))) {\r\n Logger.logError(ErrorMessages.INVALID_TOKEN);\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n\r\n next();\r\n } else {\r\n Logger.logError(ErrorMessages.TOKEN_NOT_FOUND);\r\n res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n }\r\n };\r\n\r\n /**\r\n * Checks if the user has access for this route, defined in access matrix\r\n * @param {GuardOptions} options: options to modify this middleware\r\n * @returns {RequestHandler}\r\n */\r\n hasAccess = (options?: GuardOptions): RequestHandler => {\r\n return async (req: Request, res: Response, next: NextFunction): Promise => {\r\n if (req.session && this.appSettings.accessMatrix) {\r\n\r\n const checkFor = options.accessRule.hasOwnProperty(AccessConstants.GROUPS) ? AccessConstants.GROUPS : AccessConstants.ROLES;\r\n\r\n switch (checkFor) {\r\n case AccessConstants.GROUPS:\r\n\r\n if (req.session.account.idTokenClaims[AccessConstants.GROUPS] === undefined) {\r\n if (req.session.account.idTokenClaims[AccessConstants.CLAIM_NAMES] || req.session.account.idTokenClaims[AccessConstants.CLAIM_SOURCES]) {\r\n Logger.logWarning(InfoMessages.OVERAGE_OCCURRED)\r\n return await this.handleOverage(req, res, next, options.accessRule);\r\n } else {\r\n Logger.logError(ErrorMessages.USER_HAS_NO_GROUP);\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n } else {\r\n const groups = req.session.account.idTokenClaims[AccessConstants.GROUPS];\r\n\r\n if (!this.checkAccessRule(req.method, options.accessRule, groups, AccessConstants.GROUPS)) {\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n }\r\n\r\n next();\r\n break;\r\n\r\n case AccessConstants.ROLES:\r\n if (req.session.account.idTokenClaims[AccessConstants.ROLES] === undefined) {\r\n Logger.logError(ErrorMessages.USER_HAS_NO_ROLE);\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n } else {\r\n const roles = req.session.account.idTokenClaims[AccessConstants.ROLES];\r\n\r\n if (!this.checkAccessRule(req.method, options.accessRule, roles, AccessConstants.ROLES)) {\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n }\r\n\r\n next();\r\n break;\r\n\r\n default:\r\n break;\r\n }\r\n } else {\r\n res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n }\r\n }\r\n\r\n // ============== UTILS ===============\r\n\r\n /**\r\n * This method is used to generate an auth code url request\r\n * @param {Request} req: express request object\r\n * @param {Response} res: express response object\r\n * @param {NextFunction} next: express next function\r\n * @param {AuthCodeParams} params: modifies auth code url request\r\n * @returns {Promise}\r\n */\r\n private async getAuthCode(req: Request, res: Response, next: NextFunction, params: AuthCodeParams): Promise {\r\n // prepare the request\r\n req.session.authCodeRequest.authority = params.authority;\r\n req.session.authCodeRequest.scopes = params.scopes;\r\n req.session.authCodeRequest.state = params.state;\r\n req.session.authCodeRequest.redirectUri = params.redirect;\r\n req.session.authCodeRequest.prompt = params.prompt;\r\n req.session.authCodeRequest.account = params.account;\r\n\r\n req.session.tokenRequest.authority = params.authority;\r\n req.session.tokenRequest.scopes = params.scopes;\r\n req.session.tokenRequest.redirectUri = params.redirect;\r\n\r\n // request an authorization code to exchange for tokens\r\n try {\r\n const response = await this.msalClient.getAuthCodeUrl(req.session.authCodeRequest);\r\n res.redirect(response);\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.AUTH_CODE_NOT_OBTAINED);\r\n next(error);\r\n }\r\n };\r\n\r\n /**\r\n * Handles group overage claims by querying MS Graph /memberOf endpoint\r\n * @param {Request} req: express request object\r\n * @param {Response} res: express response object\r\n * @param {NextFunction} next: express next function\r\n * @param {AccessRule} rule: a given access rule\r\n * @returns {Promise}\r\n */\r\n private async handleOverage(req: Request, res: Response, next: NextFunction, rule: AccessRule): Promise {\r\n const { _claim_names, _claim_sources, ...newIdTokenClaims } = req.session.account.idTokenClaims;\r\n\r\n const silentRequest: SilentFlowRequest = {\r\n account: req.session.account,\r\n scopes: AccessConstants.GRAPH_MEMBER_SCOPES.split(\" \"),\r\n };\r\n\r\n try {\r\n // acquire token silently to be used in resource call\r\n const tokenResponse = await this.msalClient.acquireTokenSilent(silentRequest);\r\n try {\r\n const graphResponse = await FetchManager.callApiEndpoint(AccessConstants.GRAPH_MEMBERS_ENDPOINT, tokenResponse.accessToken);\r\n\r\n /**\r\n * Some queries against Microsoft Graph return multiple pages of data either due to server-side paging \r\n * or due to the use of the $top query parameter to specifically limit the page size in a request. \r\n * When a result set spans multiple pages, Microsoft Graph returns an @odata.nextLink property in \r\n * the response that contains a URL to the next page of results. Learn more at https://docs.microsoft.com/graph/paging\r\n */\r\n if (graphResponse[AccessConstants.PAGINATION_LINK]) {\r\n try {\r\n const userGroups = await FetchManager.handlePagination(tokenResponse.accessToken, graphResponse[AccessConstants.PAGINATION_LINK]);\r\n\r\n req.session.account.idTokenClaims = {\r\n ...newIdTokenClaims,\r\n groups: userGroups\r\n }\r\n\r\n if (!this.checkAccessRule(req.method, rule, req.session.account.idTokenClaims[AccessConstants.GROUPS], AccessConstants.GROUPS)) {\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n } else {\r\n return next();\r\n }\r\n } catch (error) {\r\n next(error);\r\n }\r\n } else {\r\n req.session.account.idTokenClaims = {\r\n ...newIdTokenClaims,\r\n groups: graphResponse[\"value\"].map((v) => v.id)\r\n }\r\n\r\n if (!this.checkAccessRule(req.method, rule, req.session.account.idTokenClaims[AccessConstants.GROUPS], AccessConstants.GROUPS)) {\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n } else {\r\n return next();\r\n }\r\n }\r\n } catch (error) {\r\n next(error);\r\n }\r\n } catch (error) {\r\n next(error);\r\n }\r\n }\r\n\r\n /**\r\n * Checks if the request passes a given access rule\r\n * @param {string} method: HTTP method for this route\r\n * @param {AccessRule} rule: access rule for this route\r\n * @param {Array} creds: user's credentials i.e. roles or groups\r\n * @param {string} credType: roles or groups\r\n * @returns {boolean}\r\n */\r\n private checkAccessRule(method: string, rule: AccessRule, creds: string[], credType: string): boolean {\r\n if (rule.methods.includes(method)) {\r\n switch (credType) {\r\n case AccessConstants.GROUPS:\r\n if (rule.groups.filter(elem => creds.includes(elem)).length < 1) {\r\n Logger.logError(ErrorMessages.USER_NOT_IN_GROUP);\r\n return false;\r\n }\r\n break;\r\n\r\n case AccessConstants.ROLES:\r\n if (rule.roles.filter(elem => creds.includes(elem)).length < 1) {\r\n Logger.logError(ErrorMessages.USER_NOT_IN_ROLE);\r\n return false;\r\n }\r\n break;\r\n\r\n default:\r\n break;\r\n }\r\n } else {\r\n Logger.logError(ErrorMessages.METHOD_NOT_ALLOWED);\r\n return false;\r\n }\r\n\r\n return true;\r\n }\r\n\r\n /**\r\n * Util method to get the resource name for a given scope(s)\r\n * @param {Array} scopes: an array of scopes that the resource is associated with\r\n * @returns {string}\r\n */\r\n private getResourceNameFromScopes(scopes: string[]): string {\r\n // TODO: deep check equality here \r\n\r\n const index = Object.values({ ...this.appSettings.remoteResources, ...this.appSettings.ownedResources })\r\n .findIndex((resource: Resource) => JSON.stringify(resource.scopes) === JSON.stringify(scopes));\r\n\r\n const resourceName = Object.keys({ ...this.appSettings.remoteResources, ...this.appSettings.ownedResources })[index];\r\n return resourceName;\r\n };\r\n}\r\n"],"names":["undefined","AppStages","SIGN_IN","SIGN_OUT","ACQUIRE_TOKEN","AADAuthorityConstants","COMMON","ORGANIZATIONS","CONSUMERS","KeyVaultCredentialTypes","SECRET","CERTIFICATE","AccessConstants","GROUPS","ROLES","CLAIM_NAMES","CLAIM_SOURCES","PAGINATION_LINK","GRAPH_MEMBERS_ENDPOINT","GRAPH_MEMBER_SCOPES","InfoMessages","REQUEST_FOR_RESOURCE","OVERAGE_OCCURRED","ErrorMessages","NOT_PERMITTED","INVALID_TOKEN","CANNOT_DETERMINE_APP_STAGE","CANNOT_VALIDATE_TOKEN","NONCE_MISMATCH","INTERACTION_REQUIRED","TOKEN_ACQUISITION_FAILED","AUTH_CODE_NOT_OBTAINED","TOKEN_NOT_FOUND","TOKEN_NOT_DECODED","TOKEN_NOT_VERIFIED","KEYS_NOT_OBTAINED","STATE_NOT_FOUND","USER_HAS_NO_ROLE","USER_NOT_IN_ROLE","USER_HAS_NO_GROUP","USER_NOT_IN_GROUP","METHOD_NOT_ALLOWED","RULE_NOT_FOUND","SESSION_NOT_FOUND","KEY_VAULT_CONFIG_NOT_FOUND","ConfigurationErrorMessages","NO_CLIENT_ID","INVALID_CLIENT_ID","NO_TENANT_INFO","INVALID_TENANT_INFO","NO_CLIENT_CREDENTIAL","NO_REDIRECT_URI","NO_ERROR_ROUTE","NO_UNAUTHORIZED_ROUTE","ErrorCodes","ConfigurationUtils","validateAppSettings","config","StringUtils","isEmpty","appCredentials","clientId","Error","isGuid","tenantId","Object","values","includes","clientSecret","clientCertificate","authRoutes","redirect","error","unauthorized","getMsalConfiguration","cachePlugin","auth","authority","b2cPolicies","entries","Constants","DEFAULT_AUTHORITY_HOST","hasOwnProperty","knownAuthorities","UrlString","getDomainFromUrl","cache","system","loggerOptions","loggerCallback","logLevel","message","containsPii","LogLevel","console","Info","info","Verbose","debug","Warning","warn","piiLoggingEnabled","guid","regexGuid","test","Logger","logError","log","logMessage","logWarning","logInfo","timestamp","Date","toUTCString","logHeader","TokenValidator","appSettings","msalConfig","verifyTokenSignature","authToken","decodedToken","jwt","decode","complete","getSigningKeys","header","payload","tid","keys","verifiedToken","verify","validateIdToken","idToken","validateIdTokenClaims","idTokenClaims","now","Math","round","getTime","checkIssuer","iss","checkAudience","aud","checkTimestamp","iat","exp","verifyAccessTokenSignature","accessToken","protectedRoute","validateAccessTokenClaims","checkScopes","ownedResources","find","resource","endpoint","scopes","every","scp","jwksUri","client","jwksClient","getSigningKeyAsync","kid","getPublicKey","KeyVaultManager","getCredentialFromKeyVault","credential","DefaultAzureCredential","keyVaultCredential","credentialType","getSecretCredential","secretResponse","value","getCertificateCredential","certificateResponse","thumbprint","properties","x509Thumbprint","toString","privateKey","split","secretClient","CertificateClient","keyVaultUrl","getCertificate","credentialName","keyVaultCertificate","SecretClient","getSecret","keyVaultSecret","FetchManager","options","headers","Authorization","axios","get","response","data","nextPage","callApiEndpoint","graphResponse","map","v","push","id","handlePagination","UrlUtils","req","url","urlComponents","getUrlComponents","Protocol","HostNameAndPort","protocol","AuthProvider","appRouter","express","Router","handleRedirect","frontChannelLogout","res","next","session","destroy","sendStatus","authCodeRequest","state","redirectUri","tokenRequest","code","account","homeAccountId","environment","username","nonce","cryptoProvider","createNewGuid","base64Encode","JSON","stringify","stage","path","successRedirect","params","OIDC_DEFAULT_SCOPES","ensureAbsoluteUrl","prompt","PromptValue","SELECT_ACCOUNT","getAuthCode","postLogoutRedirectUri","logoutURI","isAuthenticated","query","parse","base64Decode","msalClient","acquireTokenByCode","tokenResponse","tokenValidator","isIdTokenValid","resourceName","getResourceNameFromScopes","remoteResources","silentRequest","acquireTokenSilent","InteractionRequiredAuthError","originalUrl","authHeader","authorization","oboRequest","oboAssertion","acquireTokenOnBehalfOf","baseUrl","accessMatrix","checkFor","accessRule","handleOverage","groups","checkAccessRule","method","roles","ConfidentialClientApplication","CryptoProvider","buildAsync","keyVault","appSettingsWithKeyVaultCredentials","authProvider","getAuthCodeUrl","rule","_claim_names","newIdTokenClaims","userGroups","creds","credType","methods","filter","elem","length","index","findIndex"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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8kBY6N,yBA9kBZ,GA8kBY,mCAA0B3G,MAA1B;AACJ;AAEA,QAAMgJ,KAAK,GAAG1O,MAAM,CAACC,MAAP,cAAmB,KAAKkD,WAAL,CAAiBmJ,eAApC,EAAwD,KAAKnJ,WAAL,CAAiBmC,cAAzE,GACTqJ,SADS,CACC,UAACnJ,QAAD;AAAA,aAAwBqF,IAAI,CAACC,SAAL,CAAetF,QAAQ,CAACE,MAAxB,MAAoCmF,IAAI,CAACC,SAAL,CAAepF,MAAf,CAA5D;AAAA,KADD,CAAd;AAGA,QAAM0G,YAAY,GAAGpM,MAAM,CAAC+D,IAAP,cAAiB,KAAKZ,WAAL,CAAiBmJ,eAAlC,EAAsD,KAAKnJ,WAAL,CAAiBmC,cAAvE,GAAyFoJ,KAAzF,CAArB;AACA,WAAOtC,YAAP;AACH,GAtlBL;;AAAA;AAAA;;;;;;;;;;;;;;;;;;"} \ No newline at end of file +{"version":3,"file":"msal-express-wrapper.cjs.development.js","sources":["../node_modules/regenerator-runtime/runtime.js","../src/Constants.ts","../src/ConfigurationUtils.ts","../src/Logger.ts","../src/TokenValidator.ts","../src/KeyVaultManager.ts","../src/FetchManager.ts","../src/UrlUtils.ts","../src/AuthProvider.ts"],"sourcesContent":["/**\n * Copyright (c) 2014-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nvar runtime = (function (exports) {\n \"use strict\";\n\n var Op = Object.prototype;\n var hasOwn = Op.hasOwnProperty;\n var undefined; // More compressible than void 0.\n var $Symbol = typeof Symbol === \"function\" ? Symbol : {};\n var iteratorSymbol = $Symbol.iterator || \"@@iterator\";\n var asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\";\n var toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n\n function define(obj, key, value) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n return obj[key];\n }\n try {\n // IE 8 has a broken Object.defineProperty that only works on DOM objects.\n define({}, \"\");\n } catch (err) {\n define = function(obj, key, value) {\n return obj[key] = value;\n };\n }\n\n function wrap(innerFn, outerFn, self, tryLocsList) {\n // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.\n var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;\n var generator = Object.create(protoGenerator.prototype);\n var context = new Context(tryLocsList || []);\n\n // The ._invoke method unifies the implementations of the .next,\n // .throw, and .return methods.\n generator._invoke = makeInvokeMethod(innerFn, self, context);\n\n return generator;\n }\n exports.wrap = wrap;\n\n // Try/catch helper to minimize deoptimizations. Returns a completion\n // record like context.tryEntries[i].completion. This interface could\n // have been (and was previously) designed to take a closure to be\n // invoked without arguments, but in all the cases we care about we\n // already have an existing method we want to call, so there's no need\n // to create a new function object. We can even get away with assuming\n // the method takes exactly one argument, since that happens to be true\n // in every case, so we don't have to touch the arguments object. The\n // only additional allocation required is the completion record, which\n // has a stable shape and so hopefully should be cheap to allocate.\n function tryCatch(fn, obj, arg) {\n try {\n return { type: \"normal\", arg: fn.call(obj, arg) };\n } catch (err) {\n return { type: \"throw\", arg: err };\n }\n }\n\n var GenStateSuspendedStart = \"suspendedStart\";\n var GenStateSuspendedYield = \"suspendedYield\";\n var GenStateExecuting = \"executing\";\n var GenStateCompleted = \"completed\";\n\n // Returning this object from the innerFn has the same effect as\n // breaking out of the dispatch switch statement.\n var ContinueSentinel = {};\n\n // Dummy constructor functions that we use as the .constructor and\n // .constructor.prototype properties for functions that return Generator\n // objects. For full spec compliance, you may wish to configure your\n // minifier not to mangle the names of these two functions.\n function Generator() {}\n function GeneratorFunction() {}\n function GeneratorFunctionPrototype() {}\n\n // This is a polyfill for %IteratorPrototype% for environments that\n // don't natively support it.\n var IteratorPrototype = {};\n IteratorPrototype[iteratorSymbol] = function () {\n return this;\n };\n\n var getProto = Object.getPrototypeOf;\n var NativeIteratorPrototype = getProto && getProto(getProto(values([])));\n if (NativeIteratorPrototype &&\n NativeIteratorPrototype !== Op &&\n hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {\n // This environment has a native %IteratorPrototype%; use it instead\n // of the polyfill.\n IteratorPrototype = NativeIteratorPrototype;\n }\n\n var Gp = GeneratorFunctionPrototype.prototype =\n Generator.prototype = Object.create(IteratorPrototype);\n GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;\n GeneratorFunctionPrototype.constructor = GeneratorFunction;\n GeneratorFunction.displayName = define(\n GeneratorFunctionPrototype,\n toStringTagSymbol,\n \"GeneratorFunction\"\n );\n\n // Helper for defining the .next, .throw, and .return methods of the\n // Iterator interface in terms of a single ._invoke method.\n function defineIteratorMethods(prototype) {\n [\"next\", \"throw\", \"return\"].forEach(function(method) {\n define(prototype, method, function(arg) {\n return this._invoke(method, arg);\n });\n });\n }\n\n exports.isGeneratorFunction = function(genFun) {\n var ctor = typeof genFun === \"function\" && genFun.constructor;\n return ctor\n ? ctor === GeneratorFunction ||\n // For the native GeneratorFunction constructor, the best we can\n // do is to check its .name property.\n (ctor.displayName || ctor.name) === \"GeneratorFunction\"\n : false;\n };\n\n exports.mark = function(genFun) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);\n } else {\n genFun.__proto__ = GeneratorFunctionPrototype;\n define(genFun, toStringTagSymbol, \"GeneratorFunction\");\n }\n genFun.prototype = Object.create(Gp);\n return genFun;\n };\n\n // Within the body of any async function, `await x` is transformed to\n // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test\n // `hasOwn.call(value, \"__await\")` to determine if the yielded value is\n // meant to be awaited.\n exports.awrap = function(arg) {\n return { __await: arg };\n };\n\n function AsyncIterator(generator, PromiseImpl) {\n function invoke(method, arg, resolve, reject) {\n var record = tryCatch(generator[method], generator, arg);\n if (record.type === \"throw\") {\n reject(record.arg);\n } else {\n var result = record.arg;\n var value = result.value;\n if (value &&\n typeof value === \"object\" &&\n hasOwn.call(value, \"__await\")) {\n return PromiseImpl.resolve(value.__await).then(function(value) {\n invoke(\"next\", value, resolve, reject);\n }, function(err) {\n invoke(\"throw\", err, resolve, reject);\n });\n }\n\n return PromiseImpl.resolve(value).then(function(unwrapped) {\n // When a yielded Promise is resolved, its final value becomes\n // the .value of the Promise<{value,done}> result for the\n // current iteration.\n result.value = unwrapped;\n resolve(result);\n }, function(error) {\n // If a rejected Promise was yielded, throw the rejection back\n // into the async generator function so it can be handled there.\n return invoke(\"throw\", error, resolve, reject);\n });\n }\n }\n\n var previousPromise;\n\n function enqueue(method, arg) {\n function callInvokeWithMethodAndArg() {\n return new PromiseImpl(function(resolve, reject) {\n invoke(method, arg, resolve, reject);\n });\n }\n\n return previousPromise =\n // If enqueue has been called before, then we want to wait until\n // all previous Promises have been resolved before calling invoke,\n // so that results are always delivered in the correct order. If\n // enqueue has not been called before, then it is important to\n // call invoke immediately, without waiting on a callback to fire,\n // so that the async generator function has the opportunity to do\n // any necessary setup in a predictable way. This predictability\n // is why the Promise constructor synchronously invokes its\n // executor callback, and why async functions synchronously\n // execute code before the first await. Since we implement simple\n // async functions in terms of async generators, it is especially\n // important to get this right, even though it requires care.\n previousPromise ? previousPromise.then(\n callInvokeWithMethodAndArg,\n // Avoid propagating failures to Promises returned by later\n // invocations of the iterator.\n callInvokeWithMethodAndArg\n ) : callInvokeWithMethodAndArg();\n }\n\n // Define the unified helper method that is used to implement .next,\n // .throw, and .return (see defineIteratorMethods).\n this._invoke = enqueue;\n }\n\n defineIteratorMethods(AsyncIterator.prototype);\n AsyncIterator.prototype[asyncIteratorSymbol] = function () {\n return this;\n };\n exports.AsyncIterator = AsyncIterator;\n\n // Note that simple async functions are implemented on top of\n // AsyncIterator objects; they just return a Promise for the value of\n // the final result produced by the iterator.\n exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {\n if (PromiseImpl === void 0) PromiseImpl = Promise;\n\n var iter = new AsyncIterator(\n wrap(innerFn, outerFn, self, tryLocsList),\n PromiseImpl\n );\n\n return exports.isGeneratorFunction(outerFn)\n ? iter // If outerFn is a generator, return the full iterator.\n : iter.next().then(function(result) {\n return result.done ? result.value : iter.next();\n });\n };\n\n function makeInvokeMethod(innerFn, self, context) {\n var state = GenStateSuspendedStart;\n\n return function invoke(method, arg) {\n if (state === GenStateExecuting) {\n throw new Error(\"Generator is already running\");\n }\n\n if (state === GenStateCompleted) {\n if (method === \"throw\") {\n throw arg;\n }\n\n // Be forgiving, per 25.3.3.3.3 of the spec:\n // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume\n return doneResult();\n }\n\n context.method = method;\n context.arg = arg;\n\n while (true) {\n var delegate = context.delegate;\n if (delegate) {\n var delegateResult = maybeInvokeDelegate(delegate, context);\n if (delegateResult) {\n if (delegateResult === ContinueSentinel) continue;\n return delegateResult;\n }\n }\n\n if (context.method === \"next\") {\n // Setting context._sent for legacy support of Babel's\n // function.sent implementation.\n context.sent = context._sent = context.arg;\n\n } else if (context.method === \"throw\") {\n if (state === GenStateSuspendedStart) {\n state = GenStateCompleted;\n throw context.arg;\n }\n\n context.dispatchException(context.arg);\n\n } else if (context.method === \"return\") {\n context.abrupt(\"return\", context.arg);\n }\n\n state = GenStateExecuting;\n\n var record = tryCatch(innerFn, self, context);\n if (record.type === \"normal\") {\n // If an exception is thrown from innerFn, we leave state ===\n // GenStateExecuting and loop back for another invocation.\n state = context.done\n ? GenStateCompleted\n : GenStateSuspendedYield;\n\n if (record.arg === ContinueSentinel) {\n continue;\n }\n\n return {\n value: record.arg,\n done: context.done\n };\n\n } else if (record.type === \"throw\") {\n state = GenStateCompleted;\n // Dispatch the exception by looping back around to the\n // context.dispatchException(context.arg) call above.\n context.method = \"throw\";\n context.arg = record.arg;\n }\n }\n };\n }\n\n // Call delegate.iterator[context.method](context.arg) and handle the\n // result, either by returning a { value, done } result from the\n // delegate iterator, or by modifying context.method and context.arg,\n // setting context.delegate to null, and returning the ContinueSentinel.\n function maybeInvokeDelegate(delegate, context) {\n var method = delegate.iterator[context.method];\n if (method === undefined) {\n // A .throw or .return when the delegate iterator has no .throw\n // method always terminates the yield* loop.\n context.delegate = null;\n\n if (context.method === \"throw\") {\n // Note: [\"return\"] must be used for ES3 parsing compatibility.\n if (delegate.iterator[\"return\"]) {\n // If the delegate iterator has a return method, give it a\n // chance to clean up.\n context.method = \"return\";\n context.arg = undefined;\n maybeInvokeDelegate(delegate, context);\n\n if (context.method === \"throw\") {\n // If maybeInvokeDelegate(context) changed context.method from\n // \"return\" to \"throw\", let that override the TypeError below.\n return ContinueSentinel;\n }\n }\n\n context.method = \"throw\";\n context.arg = new TypeError(\n \"The iterator does not provide a 'throw' method\");\n }\n\n return ContinueSentinel;\n }\n\n var record = tryCatch(method, delegate.iterator, context.arg);\n\n if (record.type === \"throw\") {\n context.method = \"throw\";\n context.arg = record.arg;\n context.delegate = null;\n return ContinueSentinel;\n }\n\n var info = record.arg;\n\n if (! info) {\n context.method = \"throw\";\n context.arg = new TypeError(\"iterator result is not an object\");\n context.delegate = null;\n return ContinueSentinel;\n }\n\n if (info.done) {\n // Assign the result of the finished delegate to the temporary\n // variable specified by delegate.resultName (see delegateYield).\n context[delegate.resultName] = info.value;\n\n // Resume execution at the desired location (see delegateYield).\n context.next = delegate.nextLoc;\n\n // If context.method was \"throw\" but the delegate handled the\n // exception, let the outer generator proceed normally. If\n // context.method was \"next\", forget context.arg since it has been\n // \"consumed\" by the delegate iterator. If context.method was\n // \"return\", allow the original .return call to continue in the\n // outer generator.\n if (context.method !== \"return\") {\n context.method = \"next\";\n context.arg = undefined;\n }\n\n } else {\n // Re-yield the result returned by the delegate method.\n return info;\n }\n\n // The delegate iterator is finished, so forget it and continue with\n // the outer generator.\n context.delegate = null;\n return ContinueSentinel;\n }\n\n // Define Generator.prototype.{next,throw,return} in terms of the\n // unified ._invoke helper method.\n defineIteratorMethods(Gp);\n\n define(Gp, toStringTagSymbol, \"Generator\");\n\n // A Generator should always return itself as the iterator object when the\n // @@iterator function is called on it. Some browsers' implementations of the\n // iterator prototype chain incorrectly implement this, causing the Generator\n // object to not be returned from this call. This ensures that doesn't happen.\n // See https://github.com/facebook/regenerator/issues/274 for more details.\n Gp[iteratorSymbol] = function() {\n return this;\n };\n\n Gp.toString = function() {\n return \"[object Generator]\";\n };\n\n function pushTryEntry(locs) {\n var entry = { tryLoc: locs[0] };\n\n if (1 in locs) {\n entry.catchLoc = locs[1];\n }\n\n if (2 in locs) {\n entry.finallyLoc = locs[2];\n entry.afterLoc = locs[3];\n }\n\n this.tryEntries.push(entry);\n }\n\n function resetTryEntry(entry) {\n var record = entry.completion || {};\n record.type = \"normal\";\n delete record.arg;\n entry.completion = record;\n }\n\n function Context(tryLocsList) {\n // The root entry object (effectively a try statement without a catch\n // or a finally block) gives us a place to store values thrown from\n // locations where there is no enclosing try statement.\n this.tryEntries = [{ tryLoc: \"root\" }];\n tryLocsList.forEach(pushTryEntry, this);\n this.reset(true);\n }\n\n exports.keys = function(object) {\n var keys = [];\n for (var key in object) {\n keys.push(key);\n }\n keys.reverse();\n\n // Rather than returning an object with a next method, we keep\n // things simple and return the next function itself.\n return function next() {\n while (keys.length) {\n var key = keys.pop();\n if (key in object) {\n next.value = key;\n next.done = false;\n return next;\n }\n }\n\n // To avoid creating an additional object, we just hang the .value\n // and .done properties off the next function object itself. This\n // also ensures that the minifier will not anonymize the function.\n next.done = true;\n return next;\n };\n };\n\n function values(iterable) {\n if (iterable) {\n var iteratorMethod = iterable[iteratorSymbol];\n if (iteratorMethod) {\n return iteratorMethod.call(iterable);\n }\n\n if (typeof iterable.next === \"function\") {\n return iterable;\n }\n\n if (!isNaN(iterable.length)) {\n var i = -1, next = function next() {\n while (++i < iterable.length) {\n if (hasOwn.call(iterable, i)) {\n next.value = iterable[i];\n next.done = false;\n return next;\n }\n }\n\n next.value = undefined;\n next.done = true;\n\n return next;\n };\n\n return next.next = next;\n }\n }\n\n // Return an iterator with no values.\n return { next: doneResult };\n }\n exports.values = values;\n\n function doneResult() {\n return { value: undefined, done: true };\n }\n\n Context.prototype = {\n constructor: Context,\n\n reset: function(skipTempReset) {\n this.prev = 0;\n this.next = 0;\n // Resetting context._sent for legacy support of Babel's\n // function.sent implementation.\n this.sent = this._sent = undefined;\n this.done = false;\n this.delegate = null;\n\n this.method = \"next\";\n this.arg = undefined;\n\n this.tryEntries.forEach(resetTryEntry);\n\n if (!skipTempReset) {\n for (var name in this) {\n // Not sure about the optimal order of these conditions:\n if (name.charAt(0) === \"t\" &&\n hasOwn.call(this, name) &&\n !isNaN(+name.slice(1))) {\n this[name] = undefined;\n }\n }\n }\n },\n\n stop: function() {\n this.done = true;\n\n var rootEntry = this.tryEntries[0];\n var rootRecord = rootEntry.completion;\n if (rootRecord.type === \"throw\") {\n throw rootRecord.arg;\n }\n\n return this.rval;\n },\n\n dispatchException: function(exception) {\n if (this.done) {\n throw exception;\n }\n\n var context = this;\n function handle(loc, caught) {\n record.type = \"throw\";\n record.arg = exception;\n context.next = loc;\n\n if (caught) {\n // If the dispatched exception was caught by a catch block,\n // then let that catch block handle the exception normally.\n context.method = \"next\";\n context.arg = undefined;\n }\n\n return !! caught;\n }\n\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n var record = entry.completion;\n\n if (entry.tryLoc === \"root\") {\n // Exception thrown outside of any try block that could handle\n // it, so set the completion value of the entire function to\n // throw the exception.\n return handle(\"end\");\n }\n\n if (entry.tryLoc <= this.prev) {\n var hasCatch = hasOwn.call(entry, \"catchLoc\");\n var hasFinally = hasOwn.call(entry, \"finallyLoc\");\n\n if (hasCatch && hasFinally) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n } else if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else if (hasCatch) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n }\n\n } else if (hasFinally) {\n if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else {\n throw new Error(\"try statement without catch or finally\");\n }\n }\n }\n },\n\n abrupt: function(type, arg) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc <= this.prev &&\n hasOwn.call(entry, \"finallyLoc\") &&\n this.prev < entry.finallyLoc) {\n var finallyEntry = entry;\n break;\n }\n }\n\n if (finallyEntry &&\n (type === \"break\" ||\n type === \"continue\") &&\n finallyEntry.tryLoc <= arg &&\n arg <= finallyEntry.finallyLoc) {\n // Ignore the finally entry if control is not jumping to a\n // location outside the try/catch block.\n finallyEntry = null;\n }\n\n var record = finallyEntry ? finallyEntry.completion : {};\n record.type = type;\n record.arg = arg;\n\n if (finallyEntry) {\n this.method = \"next\";\n this.next = finallyEntry.finallyLoc;\n return ContinueSentinel;\n }\n\n return this.complete(record);\n },\n\n complete: function(record, afterLoc) {\n if (record.type === \"throw\") {\n throw record.arg;\n }\n\n if (record.type === \"break\" ||\n record.type === \"continue\") {\n this.next = record.arg;\n } else if (record.type === \"return\") {\n this.rval = this.arg = record.arg;\n this.method = \"return\";\n this.next = \"end\";\n } else if (record.type === \"normal\" && afterLoc) {\n this.next = afterLoc;\n }\n\n return ContinueSentinel;\n },\n\n finish: function(finallyLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.finallyLoc === finallyLoc) {\n this.complete(entry.completion, entry.afterLoc);\n resetTryEntry(entry);\n return ContinueSentinel;\n }\n }\n },\n\n \"catch\": function(tryLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc === tryLoc) {\n var record = entry.completion;\n if (record.type === \"throw\") {\n var thrown = record.arg;\n resetTryEntry(entry);\n }\n return thrown;\n }\n }\n\n // The context.catch method must only be called with a location\n // argument that corresponds to a known catch block.\n throw new Error(\"illegal catch attempt\");\n },\n\n delegateYield: function(iterable, resultName, nextLoc) {\n this.delegate = {\n iterator: values(iterable),\n resultName: resultName,\n nextLoc: nextLoc\n };\n\n if (this.method === \"next\") {\n // Deliberately forget the last sent value so that we don't\n // accidentally pass it on to the delegate.\n this.arg = undefined;\n }\n\n return ContinueSentinel;\n }\n };\n\n // Regardless of whether this script is executing as a CommonJS module\n // or not, return the runtime object so that we can declare the variable\n // regeneratorRuntime in the outer scope, which allows this module to be\n // injected easily by `bin/regenerator --include-runtime script.js`.\n return exports;\n\n}(\n // If this script is executing as a CommonJS module, use module.exports\n // as the regeneratorRuntime namespace. Otherwise create a new empty\n // object. Either way, the resulting object will be used to initialize\n // the regeneratorRuntime variable at the top of this file.\n typeof module === \"object\" ? module.exports : {}\n));\n\ntry {\n regeneratorRuntime = runtime;\n} catch (accidentalStrictMode) {\n // This module should not be running in strict mode, so the above\n // assignment should always work unless something is misconfigured. Just\n // in case runtime.js accidentally runs in strict mode, we can escape\n // strict mode using a global Function call. This could conceivably fail\n // if a Content Security Policy forbids using Function, but in that case\n // the proper solution is to fix the accidental strict mode problem. If\n // you've misconfigured your bundler to force strict mode and applied a\n // CSP to forbid Function, and you're not willing to fix either of those\n // problems, please detail your unique predicament in a GitHub issue.\n Function(\"r\", \"regeneratorRuntime = r\")(runtime);\n}\n","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\n/**\r\n * Basic authentication stages used to determine\r\n * appropriate action after redirect occurs\r\n */\r\nexport const AppStages = {\r\n SIGN_IN: \"sign_in\",\r\n SIGN_OUT: \"sign_out\",\r\n ACQUIRE_TOKEN: \"acquire_token\",\r\n};\r\n\r\n/**\r\n * String constants related to AAD Authority\r\n */\r\nexport const AADAuthorityConstants = {\r\n COMMON: \"common\",\r\n ORGANIZATIONS: \"organizations\",\r\n CONSUMERS: \"consumers\"\r\n}\r\n\r\n/**\r\n * String constants related to AAD Authority\r\n */\r\nexport const KeyVaultCredentialTypes = {\r\n SECRET: \"secret\",\r\n CERTIFICATE: \"certificate\",\r\n}\r\n\r\n/**\r\n * Constants used in access control scenarios\r\n */\r\nexport const AccessConstants = {\r\n GROUPS: \"groups\",\r\n ROLES: \"roles\",\r\n CLAIM_NAMES: \"_claim_name\",\r\n CLAIM_SOURCES: \"_claim_sources\",\r\n PAGINATION_LINK: \"@odata.nextLink\",\r\n GRAPH_MEMBERS_ENDPOINT: \"https://graph.microsoft.com/v1.0/me/memberOf\",\r\n GRAPH_MEMBER_SCOPES: \"User.Read GroupMember.Read.All\"\r\n};\r\n\r\nexport const InfoMessages = {\r\n REQUEST_FOR_RESOURCE: \"Request made to web API\",\r\n OVERAGE_OCCURRED: \"User has too many groups. Groups overage claim occurred\"\r\n}\r\n\r\n/**\r\n * Various error constants\r\n */\r\nexport const ErrorMessages = {\r\n NOT_PERMITTED: \"Not permitted\",\r\n INVALID_TOKEN: \"Invalid token\",\r\n CANNOT_DETERMINE_APP_STAGE: \"Cannot determine application stage\",\r\n CANNOT_VALIDATE_TOKEN: \"Cannot validate token\",\r\n NONCE_MISMATCH: \"Nonce does not match\",\r\n INTERACTION_REQUIRED: \"interaction_required\",\r\n TOKEN_ACQUISITION_FAILED: \"Token acquisition failed\",\r\n AUTH_CODE_NOT_OBTAINED: \"Authorization code cannot be obtained\",\r\n TOKEN_NOT_FOUND: \"No token found\",\r\n TOKEN_NOT_DECODED: \"Token cannot be decoded\",\r\n TOKEN_NOT_VERIFIED: \"Token cannot be verified\",\r\n KEYS_NOT_OBTAINED: \"Signing keys cannot be obtained\",\r\n STATE_NOT_FOUND: \"State not found\",\r\n USER_HAS_NO_ROLE: \"User does not have any roles\",\r\n USER_NOT_IN_ROLE: \"User does not have this role\",\r\n USER_HAS_NO_GROUP: \"User does not have any groups\",\r\n USER_NOT_IN_GROUP: \"User does not have this group\",\r\n METHOD_NOT_ALLOWED: \"Method not allowed for this route\",\r\n RULE_NOT_FOUND: \"No rule found for this route\",\r\n SESSION_NOT_FOUND: \"No session found for this request\",\r\n KEY_VAULT_CONFIG_NOT_FOUND: \"No coordinates found for Key Vault\"\r\n};\r\n\r\nexport const ConfigurationErrorMessages = {\r\n NO_CLIENT_ID: \"No clientId provided!\",\r\n INVALID_CLIENT_ID: \"Invalid clientId!\",\r\n NO_TENANT_INFO: \"No tenant info provided!\",\r\n INVALID_TENANT_INFO: \"Invalid tenant info!\",\r\n NO_CLIENT_CREDENTIAL: \"No client credential provided!\",\r\n NO_REDIRECT_URI: \"No redirect URI provided!\",\r\n NO_ERROR_ROUTE: \"No error route provided!\",\r\n NO_UNAUTHORIZED_ROUTE: \"No unauthorized route provided!\"\r\n}\r\n\r\n/**\r\n * For more information, visit: https://login.microsoftonline.com/error\r\n */\r\nexport const ErrorCodes = {\r\n 65001: \"AADSTS65001\", // consent required\r\n};","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { \r\n UrlString, \r\n StringUtils,\r\n Constants, \r\n} from \"@azure/msal-common\";\r\n\r\nimport { \r\n ICachePlugin,\r\n Configuration,\r\n LogLevel \r\n} from \"@azure/msal-node\";\r\n\r\nimport { AppSettings } from \"./Types\";\r\n\r\nimport { \r\n AADAuthorityConstants, \r\n ConfigurationErrorMessages \r\n} from \"./Constants\";\r\n\r\nexport class ConfigurationUtils {\r\n\r\n /**\r\n * Validates the fields in the configuration file\r\n * @param {AppSettings} config: configuration object\r\n * @returns {void}\r\n */\r\n static validateAppSettings(config: AppSettings): void {\r\n if (StringUtils.isEmpty(config.appCredentials.clientId)) {\r\n throw new Error(ConfigurationErrorMessages.NO_CLIENT_ID);\r\n } else if (!ConfigurationUtils.isGuid(config.appCredentials.clientId)) {\r\n throw new Error(ConfigurationErrorMessages.INVALID_CLIENT_ID);\r\n }\r\n\r\n if (StringUtils.isEmpty(config.appCredentials.tenantId)) {\r\n throw new Error(ConfigurationErrorMessages.NO_TENANT_INFO);\r\n } else if (!ConfigurationUtils.isGuid(config.appCredentials.tenantId) && !Object.values(AADAuthorityConstants).includes(config.appCredentials.tenantId)) {\r\n throw new Error(ConfigurationErrorMessages.INVALID_TENANT_INFO);\r\n }\r\n\r\n if (StringUtils.isEmpty(config.appCredentials.clientSecret) && !config.appCredentials.clientCertificate) {\r\n throw new Error(ConfigurationErrorMessages.NO_CLIENT_CREDENTIAL);\r\n }\r\n\r\n if (StringUtils.isEmpty(config.authRoutes.redirect)) {\r\n throw new Error(ConfigurationErrorMessages.NO_REDIRECT_URI);\r\n }\r\n\r\n if (StringUtils.isEmpty(config.authRoutes.error)) {\r\n throw new Error(ConfigurationErrorMessages.NO_ERROR_ROUTE);\r\n }\r\n\r\n if (StringUtils.isEmpty(config.authRoutes.unauthorized)) {\r\n throw new Error(ConfigurationErrorMessages.NO_UNAUTHORIZED_ROUTE);\r\n }\r\n };\r\n\r\n\r\n /**\r\n * Maps the custom configuration object to configuration\r\n * object expected by MSAL Node ConfidentialClientApplication class\r\n * @param {AppSettings} config: configuration object\r\n * @param {ICachePlugin} cachePlugin: persistent cache implementation\r\n * @returns {Configuration}\r\n */\r\n static getMsalConfiguration(config: AppSettings, cachePlugin: ICachePlugin = null): Configuration {\r\n return {\r\n auth: {\r\n clientId: config.appCredentials.clientId,\r\n authority: config.b2cPolicies ?\r\n Object.entries(config.b2cPolicies)[0][1][\"authority\"]\r\n :\r\n `https://${Constants.DEFAULT_AUTHORITY_HOST}/${config.appCredentials.tenantId}`,\r\n ...(config.appCredentials.hasOwnProperty(\"clientSecret\")) && { clientSecret: config.appCredentials.clientSecret },\r\n ...(config.appCredentials.hasOwnProperty(\"clientCertificate\")) && { clientCertificate: config.appCredentials.clientCertificate },\r\n knownAuthorities: config.b2cPolicies ?\r\n [UrlString.getDomainFromUrl(Object.entries(config.b2cPolicies)[0][1][\"authority\"])] // in B2C scenarios\r\n :\r\n [],\r\n },\r\n cache: {\r\n cachePlugin,\r\n },\r\n system: {\r\n loggerOptions: {\r\n loggerCallback: (logLevel, message, containsPii) => {\r\n if (containsPii) {\r\n return;\r\n }\r\n switch (logLevel) {\r\n case LogLevel.Error:\r\n console.error(message);\r\n return;\r\n case LogLevel.Info:\r\n console.info(message);\r\n return;\r\n case LogLevel.Verbose:\r\n console.debug(message);\r\n return;\r\n case LogLevel.Warning:\r\n console.warn(message);\r\n return;\r\n }\r\n },\r\n piiLoggingEnabled: false,\r\n logLevel: LogLevel.Verbose,\r\n },\r\n },\r\n };\r\n };\r\n\r\n /**\r\n * verifies if a string is GUID\r\n * @param guid\r\n */\r\n static isGuid(guid: string): boolean {\r\n const regexGuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\r\n return regexGuid.test(guid);\r\n }\r\n}\r\n","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { LogLevel } from \"@azure/msal-common\"\r\n\r\nexport class Logger {\r\n\r\n /**\r\n * Log an error\r\n * @param {string} log\r\n * @returns {void}\r\n */\r\n static logError(log: string): void {\r\n console.error(this.logMessage(log));\r\n }\r\n\r\n /**\r\n * Log a warning\r\n * @param {string} log\r\n * @returns {void}\r\n */\r\n static logWarning(log: string): void {\r\n console.warn(this.logMessage(log));\r\n }\r\n\r\n /**\r\n * Log anything\r\n * @param {string} log\r\n * @returns {void}\r\n */\r\n static logInfo(log: string): void {\r\n console.info(this.logMessage(log));\r\n }\r\n\r\n /**\r\n * Log message with required options.\r\n * @param {string} logMessage \r\n * @returns {string}\r\n */\r\n private static logMessage(logMessage: string): string {\r\n const timestamp = new Date().toUTCString();\r\n\r\n let logHeader: string = `[${timestamp}]`;\r\n\r\n const log = `${logHeader} : @azure-samples/msal-express-wrapper@0.1.0 : ${LogLevel[LogLevel.Verbose]} - ${logMessage}`;\r\n return log;\r\n }\r\n\r\n}","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport jwt from \"jsonwebtoken\";\r\nimport jwksClient from \"jwks-rsa\";\r\n\r\nimport { \r\n StringUtils, \r\n Constants, \r\n TokenClaims \r\n} from \"@azure/msal-common\";\r\n\r\nimport { Configuration } from \"@azure/msal-node\";\r\n\r\nimport { Logger } from \"./Logger\";\r\n\r\nimport { \r\n AppSettings,\r\n Resource, \r\n IdTokenClaims, \r\n AccessTokenClaims \r\n} from \"./Types\";\r\n\r\nimport { \r\n ErrorMessages, \r\n AADAuthorityConstants \r\n} from \"./Constants\";\r\n\r\nexport class TokenValidator {\r\n private appSettings: AppSettings;\r\n private msalConfig: Configuration;\r\n\r\n /**\r\n * @param {AppSettings} appSettings \r\n * @param {Configuration} msalConfig\r\n * @constructor\r\n */\r\n constructor(appSettings: AppSettings, msalConfig: Configuration) {\r\n this.appSettings = appSettings;\r\n this.msalConfig = msalConfig;\r\n }\r\n\r\n /**\r\n * Verifies a given token's signature using jwks-rsa\r\n * @param {string} authToken \r\n * @returns {Promise}\r\n */\r\n async verifyTokenSignature(authToken: string): Promise {\r\n if (StringUtils.isEmpty(authToken)) {\r\n Logger.logError(ErrorMessages.TOKEN_NOT_FOUND);\r\n return false;\r\n }\r\n\r\n // we will first decode to get kid parameter in header\r\n let decodedToken;\r\n\r\n try {\r\n decodedToken = jwt.decode(authToken, { complete: true });\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.TOKEN_NOT_DECODED);\r\n console.log(error);\r\n return false;\r\n }\r\n\r\n // obtains signing keys from discovery endpoint\r\n let keys;\r\n\r\n try {\r\n keys = await this.getSigningKeys(decodedToken.header, decodedToken.payload.tid);\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.KEYS_NOT_OBTAINED);\r\n console.log(error);\r\n return false;\r\n }\r\n\r\n // verify the signature at header section using keys\r\n let verifiedToken: TokenClaims;\r\n\r\n try {\r\n verifiedToken = jwt.verify(authToken, keys);\r\n\r\n /**\r\n * if a multiplexer was used in place of tenantId i.e. if the app\r\n * is multi-tenant, the tenantId should be obtained from the user\"s\r\n * token\"s tid claim for verification purposes\r\n */\r\n if (\r\n this.appSettings.appCredentials.tenantId === AADAuthorityConstants.COMMON ||\r\n this.appSettings.appCredentials.tenantId === AADAuthorityConstants.ORGANIZATIONS ||\r\n this.appSettings.appCredentials.tenantId === AADAuthorityConstants.CONSUMERS\r\n ) {\r\n this.appSettings.appCredentials.tenantId = decodedToken.payload.tid;\r\n }\r\n\r\n return verifiedToken;\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.TOKEN_NOT_VERIFIED);\r\n console.log(error);\r\n return false;\r\n }\r\n };\r\n\r\n /**\r\n * Verifies the access token for signature\r\n * @param {string} idToken: raw Id token\r\n * @returns {Promise}\r\n */\r\n async validateIdToken(idToken: string): Promise {\r\n try {\r\n const verifiedToken = await this.verifyTokenSignature(idToken);\r\n\r\n if (verifiedToken) {\r\n return this.validateIdTokenClaims(verifiedToken as IdTokenClaims);\r\n } else {\r\n return false;\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n return false;\r\n }\r\n };\r\n\r\n /**\r\n * Validates the id token for a set of claims\r\n * @param {IdTokenClaims} idTokenClaims: decoded id token claims\r\n * @returns {boolean}\r\n */\r\n validateIdTokenClaims(idTokenClaims: IdTokenClaims): boolean {\r\n const now = Math.round(new Date().getTime() / 1000); // in UNIX format\r\n\r\n /**\r\n * At the very least, check for issuer, audience, issue and expiry dates.\r\n * For more information on validating id tokens, visit:\r\n * https://docs.microsoft.com/azure/active-directory/develop/id-tokens#validating-an-id_token\r\n */\r\n const checkIssuer = idTokenClaims.iss.includes(this.appSettings.appCredentials.tenantId) ? true : false;\r\n const checkAudience = idTokenClaims.aud === this.msalConfig.auth.clientId ? true : false;\r\n const checkTimestamp = idTokenClaims.iat <= now && idTokenClaims.exp >= now ? true : false;\r\n\r\n return checkIssuer && checkAudience && checkTimestamp;\r\n };\r\n\r\n /**\r\n * Verifies the access token for signature\r\n * @param {string} accessToken: raw JWT token\r\n * @param {string} protectedRoute: used for checking scope\r\n * @returns {Promise}\r\n */\r\n async verifyAccessTokenSignature(accessToken: string, protectedRoute: string): Promise {\r\n try {\r\n const verifiedToken = await this.verifyTokenSignature(accessToken);\r\n\r\n if (verifiedToken) {\r\n return this.validateAccessTokenClaims(verifiedToken as AccessTokenClaims, protectedRoute);\r\n } else {\r\n return false;\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n return false;\r\n }\r\n };\r\n\r\n /**\r\n * Validates the access token for a set of claims\r\n * @param {TokenClaims} verifiedToken: token with a verified signature\r\n * @param {string} protectedRoute: route where this token is required to access\r\n * @returns {boolean}\r\n */\r\n validateAccessTokenClaims(verifiedToken: AccessTokenClaims, protectedRoute: string): boolean {\r\n const now = Math.round(new Date().getTime() / 1000); // in UNIX format\r\n\r\n /**\r\n * At the very least, validate the token with respect to issuer, audience, scope\r\n * and timestamp, though implementation and extent vary. For more information, visit:\r\n * https://docs.microsoft.com/azure/active-directory/develop/access-tokens#validating-tokens\r\n */\r\n const checkIssuer = verifiedToken.iss.includes(this.appSettings.appCredentials.tenantId) ? true : false;\r\n const checkTimestamp = verifiedToken.iat <= now && verifiedToken.iat >= now ? true : false;\r\n\r\n const checkAudience = verifiedToken.aud === this.appSettings.appCredentials.clientId ||\r\n verifiedToken.aud === \"api://\" + this.appSettings.appCredentials.clientId ? true : false;\r\n\r\n const checkScopes = Object.values(this.appSettings.ownedResources).find((resource: Resource) => resource.endpoint === protectedRoute)\r\n .scopes.every(scp => verifiedToken.scp.includes(scp));\r\n\r\n return checkAudience && checkIssuer && checkTimestamp && checkScopes;\r\n };\r\n\r\n /**\r\n * Fetches signing keys of an access token\r\n * from the authority discovery endpoint\r\n * @param {Object} header: token header\r\n * @param {string} tid: tenant id\r\n * @returns {Promise}\r\n */\r\n private async getSigningKeys(header, tid: string): Promise {\r\n let jwksUri;\r\n\r\n // Check if a B2C application i.e. app has b2cPolicies\r\n if (this.appSettings.b2cPolicies) {\r\n jwksUri = `${this.msalConfig.auth.authority}/discovery/v2.0/keys`;\r\n } else {\r\n jwksUri = `https://${Constants.DEFAULT_AUTHORITY_HOST}/${tid}/discovery/v2.0/keys`;\r\n }\r\n\r\n const client = jwksClient({\r\n jwksUri: jwksUri,\r\n });\r\n\r\n return (await client.getSigningKeyAsync(header.kid)).getPublicKey();\r\n };\r\n}\r\n","import { CertificateClient, KeyVaultCertificate } from \"@azure/keyvault-certificates\";\r\nimport { DefaultAzureCredential } from \"@azure/identity\";\r\nimport { KeyVaultSecret, SecretClient } from \"@azure/keyvault-secrets\";\r\n\r\nimport { AppSettings } from \"./Types\";\r\nimport { KeyVaultCredentialTypes } from \"./Constants\";\r\n\r\nexport class KeyVaultManager {\r\n\r\n /**\r\n * Fetches credentials from Key Vault and updates appSettings\r\n * @param {AppSettings} config \r\n * @returns {Promise}\r\n */\r\n async getCredentialFromKeyVault(config: AppSettings): Promise {\r\n\r\n const credential = new DefaultAzureCredential();\r\n\r\n if (!config.appCredentials.keyVaultCredential) {\r\n return config\r\n }\r\n\r\n switch (config.appCredentials.keyVaultCredential.credentialType) {\r\n case KeyVaultCredentialTypes.SECRET: {\r\n try {\r\n const secretResponse = await this.getSecretCredential(config, credential);\r\n config.appCredentials.clientSecret = secretResponse.value;\r\n return config;\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n break;\r\n }\r\n\r\n case KeyVaultCredentialTypes.CERTIFICATE: {\r\n try {\r\n const certificateResponse = await this.getCertificateCredential(config, credential);\r\n const secretResponse = await this.getSecretCredential(config, credential);\r\n\r\n config.appCredentials.clientCertificate = {\r\n thumbprint: certificateResponse.properties.x509Thumbprint.toString(),\r\n privateKey: secretResponse.value.split('-----BEGIN CERTIFICATE-----\\n')[0]\r\n }\r\n return config;\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n break;\r\n }\r\n\r\n default:\r\n break;\r\n }\r\n };\r\n\r\n /**\r\n * Gets a certificate credential from Key Vault\r\n * @param {AppSettings} config \r\n * @param {DefaultAzureCredential} credential \r\n * @returns {Promise}\r\n */\r\n async getCertificateCredential(config: AppSettings, credential: DefaultAzureCredential): Promise {\r\n\r\n // Initialize secretClient with credentials\r\n const secretClient = new CertificateClient(config.appCredentials.keyVaultCredential.keyVaultUrl, credential);\r\n\r\n try {\r\n const keyVaultCertificate = await secretClient.getCertificate(config.appCredentials.keyVaultCredential.credentialName);\r\n return keyVaultCertificate;\r\n } catch (error) {\r\n console.log(error);\r\n return error;\r\n }\r\n }\r\n\r\n /**\r\n * Gets a secret credential from Key Vault\r\n * @param {AppSettings} config \r\n * @param {DefaultAzureCredential} credential \r\n * @returns {Promise}\r\n */\r\n async getSecretCredential(config: AppSettings, credential: DefaultAzureCredential): Promise {\r\n\r\n // Initialize secretClient with credentials\r\n const secretClient = new SecretClient(config.appCredentials.keyVaultCredential.keyVaultUrl, credential);\r\n\r\n try {\r\n const keyVaultSecret = await secretClient.getSecret(config.appCredentials.keyVaultCredential.credentialName);\r\n return keyVaultSecret;\r\n } catch (error) {\r\n console.log(error);\r\n return error;\r\n }\r\n }\r\n}","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport axios, { AxiosResponse, AxiosRequestConfig } from \"axios\";\r\nimport { StringUtils } from \"@azure/msal-common\";\r\n\r\nimport { \r\n AccessConstants, \r\n InfoMessages, \r\n ErrorMessages \r\n} from \"./Constants\";\r\n\r\nimport { Logger } from \"./Logger\";\r\n\r\nexport class FetchManager {\r\n\r\n /**\r\n * Calls a resource endpoint with a raw access token\r\n * using the authorization bearer token scheme\r\n * @param {string} endpoint \r\n * @param {string} accessToken \r\n * @returns {Promise}\r\n */\r\n static callApiEndpoint = async (endpoint: string, accessToken: string): Promise => {\r\n\r\n if (StringUtils.isEmpty(accessToken)) {\r\n throw new Error(ErrorMessages.TOKEN_NOT_FOUND)\r\n }\r\n\r\n const options: AxiosRequestConfig = {\r\n headers: {\r\n Authorization: `Bearer ${accessToken}`\r\n }\r\n };\r\n\r\n try {\r\n Logger.logInfo(InfoMessages.REQUEST_FOR_RESOURCE);\r\n const response: AxiosResponse = await axios.get(endpoint, options);\r\n return response.data;\r\n } catch (error) {\r\n console.log(error)\r\n return error;\r\n }\r\n }\r\n\r\n /**\r\n * Handles queries against Microsoft Graph that return multiple pages of data \r\n * @param {string} accessToken: access token required by endpoint \r\n * @param {string} nextPage: next page link\r\n * @param {Array} data: stores data from each page\r\n * @returns {Promise}\r\n */\r\n static handlePagination = async (accessToken: string, nextPage: string, data: string[] = []): Promise => {\r\n\r\n try {\r\n const graphResponse = await FetchManager.callApiEndpoint(nextPage, accessToken);\r\n graphResponse[\"value\"].map((v) => data.push(v.id));\r\n \r\n if (graphResponse[AccessConstants.PAGINATION_LINK]) {\r\n return await FetchManager.handlePagination(accessToken, graphResponse[AccessConstants.PAGINATION_LINK], data)\r\n } else {\r\n return data;\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n return error;\r\n }\r\n \r\n }\r\n\r\n}\r\n","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { Request } from \"express\";\r\nimport { IUri, UrlString } from \"@azure/msal-common\";\r\n\r\nexport class UrlUtils {\r\n /**\r\n * Gets the absolute URL from a given request and path string\r\n * @param {Request} req: express request object \r\n * @param {string} url: a given URL\r\n * @returns {string}\r\n */\r\n static ensureAbsoluteUrl = (req: Request, url: string): string => {\r\n const urlComponents: IUri = new UrlString(url).getUrlComponents();\r\n\r\n if (!urlComponents.Protocol) {\r\n if (!urlComponents.HostNameAndPort) {\r\n return req.protocol + \"://\" + req.get(\"host\") + url;\r\n }\r\n return req.protocol + \"://\" + url;\r\n } else {\r\n return url;\r\n }\r\n };\r\n\r\n /**\r\n * Gets the path segment from a given URL\r\n * @param {string} url: a given URL\r\n * @returns {string}\r\n */\r\n static getPathFromUrl = (url: string): string => {\r\n const urlComponents: IUri = new UrlString(url).getUrlComponents();\r\n return `/${urlComponents.PathSegments.join(\"/\")}`;\r\n };\r\n}\r\n","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\nimport express from \"express\";\r\n\r\nimport {\r\n RequestHandler,\r\n Request,\r\n Response,\r\n NextFunction,\r\n Router\r\n} from \"express\";\r\n\r\nimport {\r\n InteractionRequiredAuthError,\r\n OIDC_DEFAULT_SCOPES,\r\n PromptValue,\r\n StringUtils,\r\n} from \"@azure/msal-common\";\r\n\r\nimport {\r\n ConfidentialClientApplication,\r\n Configuration,\r\n AccountInfo,\r\n ICachePlugin,\r\n CryptoProvider,\r\n AuthorizationUrlRequest,\r\n AuthorizationCodeRequest,\r\n SilentFlowRequest,\r\n OnBehalfOfRequest,\r\n} from \"@azure/msal-node\";\r\n\r\nimport { ConfigurationUtils } from \"./ConfigurationUtils\";\r\nimport { TokenValidator } from \"./TokenValidator\";\r\nimport { KeyVaultManager } from \"./KeyVaultManager\";\r\nimport { FetchManager } from \"./FetchManager\";\r\nimport { UrlUtils } from \"./UrlUtils\";\r\nimport { Logger } from \"./Logger\";\r\n\r\nimport {\r\n Resource,\r\n AppSettings,\r\n AuthCodeParams,\r\n InitializationOptions,\r\n TokenRequestOptions,\r\n GuardOptions,\r\n AccessRule,\r\n SignInOptions,\r\n SignOutOptions,\r\n HandleRedirectOptions\r\n} from \"./Types\";\r\n\r\nimport {\r\n AppStages,\r\n ErrorMessages,\r\n AccessConstants,\r\n InfoMessages\r\n} from \"./Constants\";\r\n\r\n/**\r\n * A simple wrapper around MSAL Node ConfidentialClientApplication object.\r\n * It offers a collection of middleware and utility methods that automate\r\n * basic authentication and authorization tasks in Express MVC web apps and\r\n * RESTful APIs (coming soon).\r\n */\r\nexport class AuthProvider {\r\n appSettings: AppSettings;\r\n private msalConfig: Configuration;\r\n private cryptoProvider: CryptoProvider;\r\n private tokenValidator: TokenValidator;\r\n private msalClient: ConfidentialClientApplication;\r\n\r\n /**\r\n * @param {AppSettings} appSettings\r\n * @param {ICachePlugin} cache: cachePlugin\r\n * @constructor\r\n */\r\n constructor(appSettings: AppSettings, cache?: ICachePlugin) {\r\n ConfigurationUtils.validateAppSettings(appSettings);\r\n this.appSettings = appSettings;\r\n\r\n this.msalConfig = ConfigurationUtils.getMsalConfiguration(appSettings, cache);\r\n this.msalClient = new ConfidentialClientApplication(this.msalConfig);\r\n\r\n this.tokenValidator = new TokenValidator(this.appSettings, this.msalConfig);\r\n this.cryptoProvider = new CryptoProvider();\r\n }\r\n\r\n /**\r\n * Asynchronously builds authProvider object with credentials fetched from Key Vault\r\n * @param {AppSettings} appSettings\r\n * @param {ICachePlugin} cache: cachePlugin\r\n * @returns \r\n */\r\n static async buildAsync(appSettings: AppSettings, cache?: ICachePlugin): Promise {\r\n try {\r\n const keyVault = new KeyVaultManager();\r\n const appSettingsWithKeyVaultCredentials = await keyVault.getCredentialFromKeyVault(appSettings);\r\n const authProvider = new AuthProvider(appSettingsWithKeyVaultCredentials, cache);\r\n return authProvider;\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n }\r\n\r\n /**\r\n * Initialize AuthProvider and set default routes and handlers\r\n * @param {InitializationOptions} options\r\n * @returns {Router}\r\n */\r\n initialize = (options?: InitializationOptions): Router => {\r\n\r\n // TODO: initialize app defaults\r\n\r\n const appRouter = express.Router();\r\n\r\n // handle redirect\r\n appRouter.get(UrlUtils.getPathFromUrl(this.appSettings.authRoutes.redirect), this.handleRedirect());\r\n\r\n if (this.appSettings.authRoutes.frontChannelLogout) {\r\n /**\r\n * Expose front-channel logout route. For more information, visit: \r\n * https://docs.microsoft.com/azure/active-directory/develop/v2-protocols-oidc#single-sign-out\r\n */\r\n appRouter.get(this.appSettings.authRoutes.frontChannelLogout, (req, res, next) => {\r\n req.session.destroy(() => {\r\n res.sendStatus(200);\r\n });\r\n });\r\n }\r\n\r\n return appRouter;\r\n }\r\n\r\n // ========== ROUTE HANDLERS ===========\r\n\r\n /**\r\n * Initiates sign in flow\r\n * @param {SignInOptions} options: options to modify login request\r\n * @returns {RequestHandler}\r\n */\r\n signIn = (options?: SignInOptions): RequestHandler => {\r\n return (req: Request, res: Response, next: NextFunction): Promise => {\r\n /**\r\n * Request Configuration\r\n * We manipulate these three request objects below\r\n * to acquire a token with the appropriate claims\r\n */\r\n if (!req.session[\"authCodeRequest\"]) {\r\n req.session.authCodeRequest = {\r\n authority: \"\",\r\n scopes: [],\r\n state: {},\r\n redirectUri: \"\",\r\n } as AuthorizationUrlRequest;\r\n }\r\n\r\n if (!req.session[\"tokenRequest\"]) {\r\n req.session.tokenRequest = {\r\n authority: \"\",\r\n scopes: [],\r\n redirectUri: \"\",\r\n code: \"\",\r\n } as AuthorizationCodeRequest;\r\n }\r\n\r\n // signed-in user's account\r\n if (!req.session[\"account\"]) {\r\n req.session.account = {\r\n homeAccountId: \"\",\r\n environment: \"\",\r\n tenantId: \"\",\r\n username: \"\",\r\n idTokenClaims: {},\r\n } as AccountInfo;\r\n }\r\n\r\n // random GUID for csrf protection\r\n req.session.nonce = this.cryptoProvider.createNewGuid();\r\n \r\n // TODO: encrypt state parameter \r\n const state = this.cryptoProvider.base64Encode(\r\n JSON.stringify({\r\n stage: AppStages.SIGN_IN,\r\n path: options.successRedirect,\r\n nonce: req.session.nonce,\r\n })\r\n );\r\n\r\n const params: AuthCodeParams = {\r\n authority: this.msalConfig.auth.authority,\r\n scopes: OIDC_DEFAULT_SCOPES,\r\n state: state,\r\n redirect: UrlUtils.ensureAbsoluteUrl(req, this.appSettings.authRoutes.redirect),\r\n prompt: PromptValue.SELECT_ACCOUNT,\r\n };\r\n\r\n // get url to sign user in\r\n return this.getAuthCode(req, res, next, params);\r\n }\r\n };\r\n\r\n /**\r\n * Initiate sign out and destroy the session\r\n * @param options: options to modify logout request \r\n * @returns {RequestHandler}\r\n */\r\n signOut = (options?: SignOutOptions): RequestHandler => {\r\n return (req: Request, res: Response, next: NextFunction): void => {\r\n const postLogoutRedirectUri = UrlUtils.ensureAbsoluteUrl(req, options.successRedirect);\r\n\r\n /**\r\n * Construct a logout URI and redirect the user to end the\r\n * session with Azure AD/B2C. For more information, visit:\r\n * (AAD) https://docs.microsoft.com/azure/active-directory/develop/v2-protocols-oidc#send-a-sign-out-request\r\n * (B2C) https://docs.microsoft.com/azure/active-directory-b2c/openid-connect#send-a-sign-out-request\r\n */\r\n const logoutURI = `${this.msalConfig.auth.authority}/oauth2/v2.0/logout?post_logout_redirect_uri=${postLogoutRedirectUri}`;\r\n\r\n req.session.isAuthenticated = false;\r\n\r\n req.session.destroy(() => {\r\n res.redirect(logoutURI);\r\n });\r\n }\r\n };\r\n\r\n /**\r\n * Middleware that handles redirect depending on request state\r\n * There are basically 2 stages: sign-in and acquire token\r\n * @param {HandleRedirectOptions} options: options to modify this middleware\r\n * @returns {RequestHandler}\r\n */\r\n private handleRedirect = (options?: HandleRedirectOptions): RequestHandler => {\r\n return async (req: Request, res: Response, next: NextFunction): Promise => {\r\n if (req.query.state) {\r\n const state = JSON.parse(this.cryptoProvider.base64Decode(req.query.state as string));\r\n\r\n // check if nonce matches\r\n if (state.nonce === req.session.nonce) {\r\n switch (state.stage) {\r\n case AppStages.SIGN_IN: {\r\n // token request should have auth code\r\n req.session.tokenRequest.code = req.query.code as string;\r\n\r\n try {\r\n // exchange auth code for tokens\r\n const tokenResponse = await this.msalClient.acquireTokenByCode(req.session.tokenRequest);\r\n\r\n try {\r\n const isIdTokenValid = await this.tokenValidator.validateIdToken(tokenResponse.idToken);\r\n\r\n if (isIdTokenValid) {\r\n // assign session variables\r\n req.session.account = tokenResponse.account;\r\n req.session.isAuthenticated = true;\r\n\r\n res.redirect(state.path);\r\n } else {\r\n Logger.logError(ErrorMessages.INVALID_TOKEN);\r\n res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.CANNOT_VALIDATE_TOKEN);\r\n next(error)\r\n }\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.TOKEN_ACQUISITION_FAILED);\r\n next(error)\r\n }\r\n break;\r\n }\r\n\r\n case AppStages.ACQUIRE_TOKEN: {\r\n // get the name of the resource associated with scope\r\n const resourceName = this.getResourceNameFromScopes(req.session.tokenRequest.scopes);\r\n\r\n req.session.tokenRequest.code = req.query.code as string\r\n\r\n try {\r\n const tokenResponse = await this.msalClient.acquireTokenByCode(req.session.tokenRequest);\r\n req.session.remoteResources[resourceName].accessToken = tokenResponse.accessToken;\r\n res.redirect(state.path);\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.TOKEN_ACQUISITION_FAILED);\r\n next(error);\r\n }\r\n break;\r\n }\r\n\r\n default:\r\n Logger.logError(ErrorMessages.CANNOT_DETERMINE_APP_STAGE);\r\n res.redirect(this.appSettings.authRoutes.error);\r\n break;\r\n }\r\n } else {\r\n Logger.logError(ErrorMessages.NONCE_MISMATCH);\r\n res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n } else {\r\n Logger.logError(ErrorMessages.STATE_NOT_FOUND)\r\n res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n }\r\n };\r\n\r\n // ========== MIDDLEWARE ===========\r\n\r\n /**\r\n * Middleware that gets tokens via acquireToken*\r\n * @param {TokenRequestOptions} options: options to modify this middleware\r\n * @returns {RequestHandler}\r\n */\r\n getToken = (options: TokenRequestOptions): RequestHandler => {\r\n return async (req: Request, res: Response, next: NextFunction): Promise => {\r\n // get scopes for token request\r\n const scopes = options.resource.scopes;\r\n\r\n const resourceName = this.getResourceNameFromScopes(scopes)\r\n\r\n if (!req.session.remoteResources) {\r\n req.session.remoteResources = {};\r\n }\r\n\r\n req.session.remoteResources = {\r\n [resourceName]: {\r\n ...this.appSettings.remoteResources[resourceName],\r\n accessToken: null,\r\n } as Resource\r\n };\r\n\r\n try {\r\n const silentRequest: SilentFlowRequest = {\r\n account: req.session.account,\r\n scopes: scopes,\r\n };\r\n\r\n // acquire token silently to be used in resource call\r\n const tokenResponse = await this.msalClient.acquireTokenSilent(silentRequest);\r\n\r\n // In B2C scenarios, sometimes an access token is returned empty.\r\n // In that case, we will acquire token interactively instead.\r\n if (StringUtils.isEmpty(tokenResponse.accessToken)) {\r\n Logger.logError(ErrorMessages.TOKEN_NOT_FOUND);\r\n throw new InteractionRequiredAuthError(ErrorMessages.INTERACTION_REQUIRED);\r\n }\r\n\r\n req.session.remoteResources[resourceName].accessToken = tokenResponse.accessToken;\r\n next();\r\n } catch (error) {\r\n // in case there are no cached tokens, initiate an interactive call\r\n if (error instanceof InteractionRequiredAuthError) {\r\n const state = this.cryptoProvider.base64Encode(\r\n JSON.stringify({\r\n stage: AppStages.ACQUIRE_TOKEN,\r\n path: req.originalUrl,\r\n nonce: req.session.nonce,\r\n })\r\n );\r\n\r\n const params: AuthCodeParams = {\r\n authority: this.msalConfig.auth.authority,\r\n scopes: scopes,\r\n state: state,\r\n redirect: UrlUtils.ensureAbsoluteUrl(req, this.appSettings.authRoutes.redirect),\r\n account: req.session.account,\r\n };\r\n\r\n // initiate the first leg of auth code grant to get token\r\n return this.getAuthCode(req, res, next, params);\r\n } else {\r\n next(error);\r\n }\r\n }\r\n }\r\n };\r\n\r\n /**\r\n * Middleware that gets tokens via OBO flow. Used in web API scenarios\r\n * @param {TokenRequestOptions} options: options to modify this middleware\r\n * @returns {RequestHandler}\r\n */\r\n getTokenOnBehalf = (options: TokenRequestOptions): RequestHandler => {\r\n return async (req: Request, res: Response, next: NextFunction): Promise => {\r\n const authHeader = req.headers.authorization;\r\n\r\n // get scopes for token request\r\n const scopes = options.resource.scopes;\r\n const resourceName = this.getResourceNameFromScopes(scopes);\r\n\r\n const oboRequest: OnBehalfOfRequest = {\r\n oboAssertion: authHeader.split(\" \")[1],\r\n scopes: scopes,\r\n }\r\n\r\n try {\r\n const tokenResponse = await this.msalClient.acquireTokenOnBehalfOf(oboRequest);\r\n\r\n // as OBO is commonly used in middle-tier web APIs without sessions, attach AT to req\r\n req[\"locals\"] = {\r\n [resourceName]: {\r\n accessToken: tokenResponse.accessToken\r\n }\r\n }\r\n\r\n next();\r\n } catch (error) {\r\n next(error);\r\n }\r\n }\r\n }\r\n\r\n // ============== GUARDS ===============\r\n\r\n /**\r\n * Check if authenticated in session\r\n * @param {GuardOptions} options: options to modify this middleware\r\n * @returns {RequestHandler}\r\n */\r\n isAuthenticated = (options?: GuardOptions): RequestHandler => {\r\n return (req: Request, res: Response, next: NextFunction): void => {\r\n if (req.session) {\r\n if (!req.session.isAuthenticated) {\r\n Logger.logError(ErrorMessages.NOT_PERMITTED);\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n\r\n next();\r\n } else {\r\n Logger.logError(ErrorMessages.SESSION_NOT_FOUND);\r\n res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n }\r\n };\r\n\r\n /**\r\n * Receives access token in req authorization header\r\n * and validates it using the jwt.verify\r\n * @param {GuardOptions} options: options to modify this middleware\r\n * @returns {RequestHandler}\r\n */\r\n isAuthorized = (options?: GuardOptions): RequestHandler => {\r\n return async (req: Request, res: Response, next: NextFunction): Promise => {\r\n const accessToken = req.headers.authorization.split(\" \")[1];\r\n\r\n if (req.headers.authorization) {\r\n if (!(await this.tokenValidator.verifyAccessTokenSignature(accessToken, `${req.baseUrl}${req.path}`))) {\r\n Logger.logError(ErrorMessages.INVALID_TOKEN);\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n\r\n next();\r\n } else {\r\n Logger.logError(ErrorMessages.TOKEN_NOT_FOUND);\r\n res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n }\r\n };\r\n\r\n /**\r\n * Checks if the user has access for this route, defined in access matrix\r\n * @param {GuardOptions} options: options to modify this middleware\r\n * @returns {RequestHandler}\r\n */\r\n hasAccess = (options?: GuardOptions): RequestHandler => {\r\n return async (req: Request, res: Response, next: NextFunction): Promise => {\r\n if (req.session && this.appSettings.accessMatrix) {\r\n\r\n const checkFor = options.accessRule.hasOwnProperty(AccessConstants.GROUPS) ? AccessConstants.GROUPS : AccessConstants.ROLES;\r\n\r\n switch (checkFor) {\r\n case AccessConstants.GROUPS:\r\n\r\n if (req.session.account.idTokenClaims[AccessConstants.GROUPS] === undefined) {\r\n if (req.session.account.idTokenClaims[AccessConstants.CLAIM_NAMES] || req.session.account.idTokenClaims[AccessConstants.CLAIM_SOURCES]) {\r\n Logger.logWarning(InfoMessages.OVERAGE_OCCURRED)\r\n return await this.handleOverage(req, res, next, options.accessRule);\r\n } else {\r\n Logger.logError(ErrorMessages.USER_HAS_NO_GROUP);\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n } else {\r\n const groups = req.session.account.idTokenClaims[AccessConstants.GROUPS];\r\n\r\n if (!this.checkAccessRule(req.method, options.accessRule, groups, AccessConstants.GROUPS)) {\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n }\r\n\r\n next();\r\n break;\r\n\r\n case AccessConstants.ROLES:\r\n if (req.session.account.idTokenClaims[AccessConstants.ROLES] === undefined) {\r\n Logger.logError(ErrorMessages.USER_HAS_NO_ROLE);\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n } else {\r\n const roles = req.session.account.idTokenClaims[AccessConstants.ROLES];\r\n\r\n if (!this.checkAccessRule(req.method, options.accessRule, roles, AccessConstants.ROLES)) {\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n }\r\n\r\n next();\r\n break;\r\n\r\n default:\r\n break;\r\n }\r\n } else {\r\n res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n }\r\n }\r\n\r\n // ============== UTILS ===============\r\n\r\n /**\r\n * This method is used to generate an auth code url request\r\n * @param {Request} req: express request object\r\n * @param {Response} res: express response object\r\n * @param {NextFunction} next: express next function\r\n * @param {AuthCodeParams} params: modifies auth code url request\r\n * @returns {Promise}\r\n */\r\n private async getAuthCode(req: Request, res: Response, next: NextFunction, params: AuthCodeParams): Promise {\r\n // prepare the request\r\n req.session.authCodeRequest.authority = params.authority;\r\n req.session.authCodeRequest.scopes = params.scopes;\r\n req.session.authCodeRequest.state = params.state;\r\n req.session.authCodeRequest.redirectUri = params.redirect;\r\n req.session.authCodeRequest.prompt = params.prompt;\r\n req.session.authCodeRequest.account = params.account;\r\n\r\n req.session.tokenRequest.authority = params.authority;\r\n req.session.tokenRequest.scopes = params.scopes;\r\n req.session.tokenRequest.redirectUri = params.redirect;\r\n\r\n // request an authorization code to exchange for tokens\r\n try {\r\n const response = await this.msalClient.getAuthCodeUrl(req.session.authCodeRequest);\r\n res.redirect(response);\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.AUTH_CODE_NOT_OBTAINED);\r\n next(error);\r\n }\r\n };\r\n\r\n /**\r\n * Handles group overage claims by querying MS Graph /memberOf endpoint\r\n * @param {Request} req: express request object\r\n * @param {Response} res: express response object\r\n * @param {NextFunction} next: express next function\r\n * @param {AccessRule} rule: a given access rule\r\n * @returns {Promise}\r\n */\r\n private async handleOverage(req: Request, res: Response, next: NextFunction, rule: AccessRule): Promise {\r\n const { _claim_names, _claim_sources, ...newIdTokenClaims } = req.session.account.idTokenClaims;\r\n\r\n const silentRequest: SilentFlowRequest = {\r\n account: req.session.account,\r\n scopes: AccessConstants.GRAPH_MEMBER_SCOPES.split(\" \"),\r\n };\r\n\r\n try {\r\n // acquire token silently to be used in resource call\r\n const tokenResponse = await this.msalClient.acquireTokenSilent(silentRequest);\r\n try {\r\n const graphResponse = await FetchManager.callApiEndpoint(AccessConstants.GRAPH_MEMBERS_ENDPOINT, tokenResponse.accessToken);\r\n\r\n /**\r\n * Some queries against Microsoft Graph return multiple pages of data either due to server-side paging \r\n * or due to the use of the $top query parameter to specifically limit the page size in a request. \r\n * When a result set spans multiple pages, Microsoft Graph returns an @odata.nextLink property in \r\n * the response that contains a URL to the next page of results. Learn more at https://docs.microsoft.com/graph/paging\r\n */\r\n if (graphResponse[AccessConstants.PAGINATION_LINK]) {\r\n try {\r\n const userGroups = await FetchManager.handlePagination(tokenResponse.accessToken, graphResponse[AccessConstants.PAGINATION_LINK]);\r\n\r\n req.session.account.idTokenClaims = {\r\n ...newIdTokenClaims,\r\n groups: userGroups\r\n }\r\n\r\n if (!this.checkAccessRule(req.method, rule, req.session.account.idTokenClaims[AccessConstants.GROUPS], AccessConstants.GROUPS)) {\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n } else {\r\n return next();\r\n }\r\n } catch (error) {\r\n next(error);\r\n }\r\n } else {\r\n req.session.account.idTokenClaims = {\r\n ...newIdTokenClaims,\r\n groups: graphResponse[\"value\"].map((v) => v.id)\r\n }\r\n\r\n if (!this.checkAccessRule(req.method, rule, req.session.account.idTokenClaims[AccessConstants.GROUPS], AccessConstants.GROUPS)) {\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n } else {\r\n return next();\r\n }\r\n }\r\n } catch (error) {\r\n next(error);\r\n }\r\n } catch (error) {\r\n next(error);\r\n }\r\n }\r\n\r\n /**\r\n * Checks if the request passes a given access rule\r\n * @param {string} method: HTTP method for this route\r\n * @param {AccessRule} rule: access rule for this route\r\n * @param {Array} creds: user's credentials i.e. roles or groups\r\n * @param {string} credType: roles or groups\r\n * @returns {boolean}\r\n */\r\n private checkAccessRule(method: string, rule: AccessRule, creds: string[], credType: string): boolean {\r\n if (rule.methods.includes(method)) {\r\n switch (credType) {\r\n case AccessConstants.GROUPS:\r\n if (rule.groups.filter(elem => creds.includes(elem)).length < 1) {\r\n Logger.logError(ErrorMessages.USER_NOT_IN_GROUP);\r\n return false;\r\n }\r\n break;\r\n\r\n case AccessConstants.ROLES:\r\n if (rule.roles.filter(elem => creds.includes(elem)).length < 1) {\r\n Logger.logError(ErrorMessages.USER_NOT_IN_ROLE);\r\n return false;\r\n }\r\n break;\r\n\r\n default:\r\n break;\r\n }\r\n } else {\r\n Logger.logError(ErrorMessages.METHOD_NOT_ALLOWED);\r\n return false;\r\n }\r\n\r\n return true;\r\n }\r\n\r\n /**\r\n * Util method to get the resource name for a given scope(s)\r\n * @param {Array} scopes: an array of scopes that the resource is associated with\r\n * @returns {string}\r\n */\r\n private getResourceNameFromScopes(scopes: string[]): string {\r\n // TODO: deep check equality here \r\n\r\n const index = Object.values({ ...this.appSettings.remoteResources, ...this.appSettings.ownedResources })\r\n .findIndex((resource: Resource) => JSON.stringify(resource.scopes) === JSON.stringify(scopes));\r\n\r\n const resourceName = Object.keys({ ...this.appSettings.remoteResources, ...this.appSettings.ownedResources })[index];\r\n return resourceName;\r\n };\r\n}\r\n"],"names":["undefined","AppStages","SIGN_IN","SIGN_OUT","ACQUIRE_TOKEN","AADAuthorityConstants","COMMON","ORGANIZATIONS","CONSUMERS","KeyVaultCredentialTypes","SECRET","CERTIFICATE","AccessConstants","GROUPS","ROLES","CLAIM_NAMES","CLAIM_SOURCES","PAGINATION_LINK","GRAPH_MEMBERS_ENDPOINT","GRAPH_MEMBER_SCOPES","InfoMessages","REQUEST_FOR_RESOURCE","OVERAGE_OCCURRED","ErrorMessages","NOT_PERMITTED","INVALID_TOKEN","CANNOT_DETERMINE_APP_STAGE","CANNOT_VALIDATE_TOKEN","NONCE_MISMATCH","INTERACTION_REQUIRED","TOKEN_ACQUISITION_FAILED","AUTH_CODE_NOT_OBTAINED","TOKEN_NOT_FOUND","TOKEN_NOT_DECODED","TOKEN_NOT_VERIFIED","KEYS_NOT_OBTAINED","STATE_NOT_FOUND","USER_HAS_NO_ROLE","USER_NOT_IN_ROLE","USER_HAS_NO_GROUP","USER_NOT_IN_GROUP","METHOD_NOT_ALLOWED","RULE_NOT_FOUND","SESSION_NOT_FOUND","KEY_VAULT_CONFIG_NOT_FOUND","ConfigurationErrorMessages","NO_CLIENT_ID","INVALID_CLIENT_ID","NO_TENANT_INFO","INVALID_TENANT_INFO","NO_CLIENT_CREDENTIAL","NO_REDIRECT_URI","NO_ERROR_ROUTE","NO_UNAUTHORIZED_ROUTE","ErrorCodes","ConfigurationUtils","validateAppSettings","config","StringUtils","isEmpty","appCredentials","clientId","Error","isGuid","tenantId","Object","values","includes","clientSecret","clientCertificate","authRoutes","redirect","error","unauthorized","getMsalConfiguration","cachePlugin","auth","authority","b2cPolicies","entries","Constants","DEFAULT_AUTHORITY_HOST","hasOwnProperty","knownAuthorities","UrlString","getDomainFromUrl","cache","system","loggerOptions","loggerCallback","logLevel","message","containsPii","LogLevel","console","Info","info","Verbose","debug","Warning","warn","piiLoggingEnabled","guid","regexGuid","test","Logger","logError","log","logMessage","logWarning","logInfo","timestamp","Date","toUTCString","logHeader","TokenValidator","appSettings","msalConfig","verifyTokenSignature","authToken","decodedToken","jwt","decode","complete","getSigningKeys","header","payload","tid","keys","verifiedToken","verify","validateIdToken","idToken","validateIdTokenClaims","idTokenClaims","now","Math","round","getTime","checkIssuer","iss","checkAudience","aud","checkTimestamp","iat","exp","verifyAccessTokenSignature","accessToken","protectedRoute","validateAccessTokenClaims","checkScopes","ownedResources","find","resource","endpoint","scopes","every","scp","jwksUri","client","jwksClient","getSigningKeyAsync","kid","getPublicKey","KeyVaultManager","getCredentialFromKeyVault","credential","DefaultAzureCredential","keyVaultCredential","credentialType","getSecretCredential","secretResponse","value","getCertificateCredential","certificateResponse","thumbprint","properties","x509Thumbprint","toString","privateKey","split","secretClient","CertificateClient","keyVaultUrl","getCertificate","credentialName","keyVaultCertificate","SecretClient","getSecret","keyVaultSecret","FetchManager","options","headers","Authorization","axios","get","response","data","nextPage","callApiEndpoint","graphResponse","map","v","push","id","handlePagination","UrlUtils","req","url","urlComponents","getUrlComponents","Protocol","HostNameAndPort","protocol","PathSegments","join","AuthProvider","appRouter","express","Router","getPathFromUrl","handleRedirect","frontChannelLogout","res","next","session","destroy","sendStatus","authCodeRequest","state","redirectUri","tokenRequest","code","account","homeAccountId","environment","username","nonce","cryptoProvider","createNewGuid","base64Encode","JSON","stringify","stage","path","successRedirect","params","OIDC_DEFAULT_SCOPES","ensureAbsoluteUrl","prompt","PromptValue","SELECT_ACCOUNT","getAuthCode","postLogoutRedirectUri","logoutURI","isAuthenticated","query","parse","base64Decode","msalClient","acquireTokenByCode","tokenResponse","tokenValidator","isIdTokenValid","resourceName","getResourceNameFromScopes","remoteResources","silentRequest","acquireTokenSilent","InteractionRequiredAuthError","originalUrl","authHeader","authorization","oboRequest","oboAssertion","acquireTokenOnBehalfOf","baseUrl","accessMatrix","checkFor","accessRule","handleOverage","groups","checkAccessRule","method","roles","ConfidentialClientApplication","CryptoProvider","buildAsync","keyVault","appSettingsWithKeyVaultCredentials","authProvider","getAuthCodeUrl","rule","_claim_names","newIdTokenClaims","userGroups","creds","credType","methods","filter","elem","length","index","findIndex"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,OAAO,IAAI,UAAU,OAAO,EAAE;AAElC;AACA,EAAE,IAAI,EAAE,GAAG,MAAM,CAAC,SAAS,CAAC;AAC5B,EAAE,IAAI,MAAM,GAAG,EAAE,CAAC,cAAc,CAAC;AACjC,EAAE,IAAIA,WAAS,CAAC;AAChB,EAAE,IAAI,OAAO,GAAG,OAAO,MAAM,KAAK,UAAU,GAAG,MAAM,GAAG,EAAE,CAAC;AAC3D,EAAE,IAAI,cAAc,GAAG,OAAO,CAAC,QAAQ,IAAI,YAAY,CAAC;AACxD,EAAE,IAAI,mBAAmB,GAAG,OAAO,CAAC,aAAa,IAAI,iBAAiB,CAAC;AACvE,EAAE,IAAI,iBAAiB,GAAG,OAAO,CAAC,WAAW,IAAI,eAAe,CAAC;AACjE;AACA,EAAE,SAAS,MAAM,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE;AACnC,IAAI,MAAM,CAAC,cAAc,CAAC,GAAG,EAAE,GAAG,EAAE;AACpC,MAAM,KAAK,EAAE,KAAK;AAClB,MAAM,UAAU,EAAE,IAAI;AACtB,MAAM,YAAY,EAAE,IAAI;AACxB,MAAM,QAAQ,EAAE,IAAI;AACpB,KAAK,CAAC,CAAC;AACP,IAAI,OAAO,GAAG,CAAC,GAAG,CAAC,CAAC;AACpB,GAAG;AACH,EAAE,IAAI;AACN;AACA,IAAI,MAAM,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;AACnB,GAAG,C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apper.cjs.production.min.js index fe3b0e4..4c1503a 100644 --- a/dist/msal-express-wrapper.cjs.production.min.js +++ b/dist/msal-express-wrapper.cjs.production.min.js @@ -1,2 +1,2 @@ -"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}Object.defineProperty(exports,"__esModule",{value:!0});var t=e(require("express")),r=require("@azure/msal-common"),n=require("@azure/msal-node"),o=e(require("jsonwebtoken")),a=e(require("jwks-rsa")),i=require("@azure/keyvault-certificates"),s=require("@azure/identity"),u=require("@azure/keyvault-secrets"),c=e(require("axios"));function p(e,t,r,n,o,a,i){try{var s=e[a](i),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,o)}function l(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var a=e.apply(t,r);function i(e){p(a,n,o,i,s,"next",e)}function s(e){p(a,n,o,i,s,"throw",e)}i(void 0)}))}}function h(){return(h=Object.assign||function(e){for(var t=1;t=0||(o[r]=e[r]);return o}var f,g=(function(e){var t=function(e){var t=Object.prototype,r=t.hasOwnProperty,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",a=n.asyncIterator||"@@asyncIterator",i=n.toStringTag||"@@toStringTag";function s(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{s({},"")}catch(e){s=function(e,t,r){return e[t]=r}}function u(e,t,r,n){var o=Object.create((t&&t.prototype instanceof l?t:l).prototype),a=new R(n||[]);return o._invoke=function(e,t,r){var n="suspendedStart";return function(o,a){if("executing"===n)throw new Error("Generator is already running");if("completed"===n){if("throw"===o)throw a;return{value:void 0,done:!0}}for(r.method=o,r.arg=a;;){var i=r.delegate;if(i){var s=y(i,r);if(s){if(s===p)continue;return s}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if("suspendedStart"===n)throw n="completed",r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n="executing";var u=c(e,t,r);if("normal"===u.type){if(n=r.done?"completed":"suspendedYield",u.arg===p)continue;return{value:u.arg,done:r.done}}"throw"===u.type&&(n="completed",r.method="throw",r.arg=u.arg)}}}(e,r,a),o}function c(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}e.wrap=u;var p={};function l(){}function h(){}function d(){}var f={};f[o]=function(){return this};var g=Object.getPrototypeOf,v=g&&g(g(m([])));v&&v!==t&&r.call(v,o)&&(f=v);var E=d.prototype=l.prototype=Object.create(f);function O(e){["next","throw","return"].forEach((function(t){s(e,t,(function(e){return this._invoke(t,e)}))}))}function N(e,t){var n;this._invoke=function(o,a){function i(){return new t((function(n,i){!function n(o,a,i,s){var u=c(e[o],e,a);if("throw"!==u.type){var p=u.arg,l=p.value;return l&&"object"==typeof l&&r.call(l,"__await")?t.resolve(l.__await).then((function(e){n("next",e,i,s)}),(function(e){n("throw",e,i,s)})):t.resolve(l).then((function(e){p.value=e,i(p)}),(function(e){return n("throw",e,i,s)}))}s(u.arg)}(o,a,n,i)}))}return n=n?n.then(i,i):i()}}function y(e,t){var r=e.iterator[t.method];if(void 0===r){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=void 0,y(e,t),"throw"===t.method))return p;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return p}var n=c(r,e.iterator,t.arg);if("throw"===n.type)return t.method="throw",t.arg=n.arg,t.delegate=null,p;var o=n.arg;return o?o.done?(t[e.resultName]=o.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,p):o:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,p)}function _(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function T(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function R(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(_,this),this.reset(!0)}function m(e){if(e){var t=e[o];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var n=-1,a=function t(){for(;++n=0;--o){var a=this.tryEntries[o],i=a.completion;if("root"===a.tryLoc)return n("end");if(a.tryLoc<=this.prev){var s=r.call(a,"catchLoc"),u=r.call(a,"finallyLoc");if(s&&u){if(this.prev=0;--n){var o=this.tryEntries[n];if(o.tryLoc<=this.prev&&r.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),T(r),p}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;T(r)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,r){return this.delegate={iterator:m(e),resultName:t,nextLoc:r},"next"===this.method&&(this.arg=void 0),p}},e}(e.exports);try{regeneratorRuntime=t}catch(e){Function("r","regeneratorRuntime = r")(t)}}(f={exports:{}}),f.exports),v={SIGN_IN:"sign_in",SIGN_OUT:"sign_out",ACQUIRE_TOKEN:"acquire_token"},E={COMMON:"common",ORGANIZATIONS:"organizations",CONSUMERS:"consumers"},O={SECRET:"secret",CERTIFICATE:"certificate"},N={GROUPS:"groups",ROLES:"roles",CLAIM_NAMES:"_claim_name",CLAIM_SOURCES:"_claim_sources",PAGINATION_LINK:"@odata.nextLink",GRAPH_MEMBERS_ENDPOINT:"https://graph.microsoft.com/v1.0/me/memberOf",GRAPH_MEMBER_SCOPES:"User.Read GroupMember.Read.All"},y={REQUEST_FOR_RESOURCE:"Request made to web API",OVERAGE_OCCURRED:"User has too many groups. Groups overage claim occurred"},_={NOT_PERMITTED:"Not permitted",INVALID_TOKEN:"Invalid token",CANNOT_DETERMINE_APP_STAGE:"Cannot determine application stage",CANNOT_VALIDATE_TOKEN:"Cannot validate token",NONCE_MISMATCH:"Nonce does not match",INTERACTION_REQUIRED:"interaction_required",TOKEN_ACQUISITION_FAILED:"Token acquisition failed",AUTH_CODE_NOT_OBTAINED:"Authorization code cannot be obtained",TOKEN_NOT_FOUND:"No token found",TOKEN_NOT_DECODED:"Token cannot be decoded",TOKEN_NOT_VERIFIED:"Token cannot be verified",KEYS_NOT_OBTAINED:"Signing keys cannot be obtained",STATE_NOT_FOUND:"State not found",USER_HAS_NO_ROLE:"User does not have any roles",USER_NOT_IN_ROLE:"User does not have this role",USER_HAS_NO_GROUP:"User does not have any groups",USER_NOT_IN_GROUP:"User does not have this group",METHOD_NOT_ALLOWED:"Method not allowed for this route",RULE_NOT_FOUND:"No rule found for this route",SESSION_NOT_FOUND:"No session found for this request",KEY_VAULT_CONFIG_NOT_FOUND:"No coordinates found for Key Vault"},T={NO_CLIENT_ID:"No clientId provided!",INVALID_CLIENT_ID:"Invalid clientId!",NO_TENANT_INFO:"No tenant info provided!",INVALID_TENANT_INFO:"Invalid tenant info!",NO_CLIENT_CREDENTIAL:"No client credential provided!",NO_REDIRECT_URI:"No redirect URI provided!",NO_ERROR_ROUTE:"No error route provided!",NO_UNAUTHORIZED_ROUTE:"No unauthorized route provided!"},R=function(){function e(){}return e.validateAppSettings=function(t){if(r.StringUtils.isEmpty(t.appCredentials.clientId))throw new Error(T.NO_CLIENT_ID);if(!e.isGuid(t.appCredentials.clientId))throw new Error(T.INVALID_CLIENT_ID);if(r.StringUtils.isEmpty(t.appCredentials.tenantId))throw new Error(T.NO_TENANT_INFO);if(!e.isGuid(t.appCredentials.tenantId)&&!Object.values(E).includes(t.appCredentials.tenantId))throw new Error(T.INVALID_TENANT_INFO);if(r.StringUtils.isEmpty(t.appCredentials.clientSecret)&&!t.appCredentials.clientCertificate)throw new Error(T.NO_CLIENT_CREDENTIAL);if(r.StringUtils.isEmpty(t.authRoutes.redirect))throw new Error(T.NO_REDIRECT_URI);if(r.StringUtils.isEmpty(t.authRoutes.error))throw new Error(T.NO_ERROR_ROUTE);if(r.StringUtils.isEmpty(t.authRoutes.unauthorized))throw new Error(T.NO_UNAUTHORIZED_ROUTE)},e.getMsalConfiguration=function(e,t){return void 0===t&&(t=null),{auth:h({clientId:e.appCredentials.clientId,authority:e.b2cPolicies?Object.entries(e.b2cPolicies)[0][1].authority:"https://"+r.Constants.DEFAULT_AUTHORITY_HOST+"/"+e.appCredentials.tenantId},e.appCredentials.hasOwnProperty("clientSecret")&&{clientSecret:e.appCredentials.clientSecret},e.appCredentials.hasOwnProperty("clientCertificate")&&{clientCertificate:e.appCredentials.clientCertificate},{knownAuthorities:e.b2cPolicies?[r.UrlString.getDomainFromUrl(Object.entries(e.b2cPolicies)[0][1].authority)]:[]}),cache:{cachePlugin:t},system:{loggerOptions:{loggerCallback:function(e,t,r){if(!r)switch(e){case n.LogLevel.Error:return void console.error(t);case n.LogLevel.Info:return void console.info(t);case n.LogLevel.Verbose:return void console.debug(t);case n.LogLevel.Warning:return void console.warn(t)}},piiLoggingEnabled:!1,logLevel:n.LogLevel.Verbose}}}},e.isGuid=function(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)},e}(),m=function(){function e(){}return e.logError=function(e){console.error(this.logMessage(e))},e.logWarning=function(e){console.warn(this.logMessage(e))},e.logInfo=function(e){console.info(this.logMessage(e))},e.logMessage=function(e){return"["+(new Date).toUTCString()+"] : @azure-samples/msal-express-wrapper@0.1.0 : "+r.LogLevel[r.LogLevel.Verbose]+" - "+e},e}(),C=function(){function e(e,t){this.appSettings=e,this.msalConfig=t}var t=e.prototype;return t.verifyTokenSignature=function(){var e=l(g.mark((function e(t){var n,a,i;return g.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!r.StringUtils.isEmpty(t)){e.next=3;break}return m.logError(_.TOKEN_NOT_FOUND),e.abrupt("return",!1);case 3:e.prev=3,n=o.decode(t,{complete:!0}),e.next=12;break;case 7:return e.prev=7,e.t0=e.catch(3),m.logError(_.TOKEN_NOT_DECODED),console.log(e.t0),e.abrupt("return",!1);case 12:return e.prev=12,e.next=15,this.getSigningKeys(n.header,n.payload.tid);case 15:a=e.sent,e.next=23;break;case 18:return e.prev=18,e.t1=e.catch(12),m.logError(_.KEYS_NOT_OBTAINED),console.log(e.t1),e.abrupt("return",!1);case 23:return e.prev=23,i=o.verify(t,a),this.appSettings.appCredentials.tenantId!==E.COMMON&&this.appSettings.appCredentials.tenantId!==E.ORGANIZATIONS&&this.appSettings.appCredentials.tenantId!==E.CONSUMERS||(this.appSettings.appCredentials.tenantId=n.payload.tid),e.abrupt("return",i);case 29:return e.prev=29,e.t2=e.catch(23),m.logError(_.TOKEN_NOT_VERIFIED),console.log(e.t2),e.abrupt("return",!1);case 34:case"end":return e.stop()}}),e,this,[[3,7],[12,18],[23,29]])})));return function(t){return e.apply(this,arguments)}}(),t.validateIdToken=function(){var e=l(g.mark((function e(t){var r;return g.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this.verifyTokenSignature(t);case 3:if(!(r=e.sent)){e.next=8;break}return e.abrupt("return",this.validateIdTokenClaims(r));case 8:return e.abrupt("return",!1);case 9:e.next=15;break;case 11:return e.prev=11,e.t0=e.catch(0),console.log(e.t0),e.abrupt("return",!1);case 15:case"end":return e.stop()}}),e,this,[[0,11]])})));return function(t){return e.apply(this,arguments)}}(),t.validateIdTokenClaims=function(e){var t=Math.round((new Date).getTime()/1e3);return!!e.iss.includes(this.appSettings.appCredentials.tenantId)&&e.aud===this.msalConfig.auth.clientId&&e.iat<=t&&e.exp>=t},t.verifyAccessTokenSignature=function(){var e=l(g.mark((function e(t,r){var n;return g.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this.verifyTokenSignature(t);case 3:if(!(n=e.sent)){e.next=8;break}return e.abrupt("return",this.validateAccessTokenClaims(n,r));case 8:return e.abrupt("return",!1);case 9:e.next=15;break;case 11:return e.prev=11,e.t0=e.catch(0),console.log(e.t0),e.abrupt("return",!1);case 15:case"end":return e.stop()}}),e,this,[[0,11]])})));return function(t,r){return e.apply(this,arguments)}}(),t.validateAccessTokenClaims=function(e,t){var r=Math.round((new Date).getTime()/1e3),n=!!e.iss.includes(this.appSettings.appCredentials.tenantId),o=e.iat<=r&&e.iat>=r,a=e.aud===this.appSettings.appCredentials.clientId||e.aud==="api://"+this.appSettings.appCredentials.clientId,i=Object.values(this.appSettings.ownedResources).find((function(e){return e.endpoint===t})).scopes.every((function(t){return e.scp.includes(t)}));return a&&n&&o&&i},t.getSigningKeys=function(){var e=l(g.mark((function e(t,n){var o;return g.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return o=a({jwksUri:this.appSettings.b2cPolicies?this.msalConfig.auth.authority+"/discovery/v2.0/keys":"https://"+r.Constants.DEFAULT_AUTHORITY_HOST+"/"+n+"/discovery/v2.0/keys"}),e.next=4,o.getSigningKeyAsync(t.kid);case 4:return e.abrupt("return",e.sent.getPublicKey());case 5:case"end":return e.stop()}}),e,this)})));return function(t,r){return e.apply(this,arguments)}}(),e}(),S=function(){function e(){}var t=e.prototype;return t.getCredentialFromKeyVault=function(){var e=l(g.mark((function e(t){var r,n,o;return g.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=new s.DefaultAzureCredential,t.appCredentials.keyVaultCredential){e.next=3;break}return e.abrupt("return",t);case 3:e.t0=t.appCredentials.keyVaultCredential.credentialType,e.next=e.t0===O.SECRET?6:e.t0===O.CERTIFICATE?18:33;break;case 6:return e.prev=6,e.next=9,this.getSecretCredential(t,r);case 9:return t.appCredentials.clientSecret=e.sent.value,e.abrupt("return",t);case 14:e.prev=14,e.t1=e.catch(6),console.log(e.t1);case 17:return e.abrupt("break",34);case 18:return e.prev=18,e.next=21,this.getCertificateCredential(t,r);case 21:return n=e.sent,e.next=24,this.getSecretCredential(t,r);case 24:return o=e.sent,t.appCredentials.clientCertificate={thumbprint:n.properties.x509Thumbprint.toString(),privateKey:o.value.split("-----BEGIN CERTIFICATE-----\n")[0]},e.abrupt("return",t);case 29:e.prev=29,e.t2=e.catch(18),console.log(e.t2);case 32:case 33:return e.abrupt("break",34);case 34:case"end":return e.stop()}}),e,this,[[6,14],[18,29]])})));return function(t){return e.apply(this,arguments)}}(),t.getCertificateCredential=function(){var e=l(g.mark((function e(t,r){var n;return g.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=new i.CertificateClient(t.appCredentials.keyVaultCredential.keyVaultUrl,r),e.prev=1,e.next=4,n.getCertificate(t.appCredentials.keyVaultCredential.credentialName);case 4:return e.abrupt("return",e.sent);case 8:return e.prev=8,e.t0=e.catch(1),console.log(e.t0),e.abrupt("return",e.t0);case 12:case"end":return e.stop()}}),e,null,[[1,8]])})));return function(t,r){return e.apply(this,arguments)}}(),t.getSecretCredential=function(){var e=l(g.mark((function e(t,r){var n;return g.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=new u.SecretClient(t.appCredentials.keyVaultCredential.keyVaultUrl,r),e.prev=1,e.next=4,n.getSecret(t.appCredentials.keyVaultCredential.credentialName);case 4:return e.abrupt("return",e.sent);case 8:return e.prev=8,e.t0=e.catch(1),console.log(e.t0),e.abrupt("return",e.t0);case 12:case"end":return e.stop()}}),e,null,[[1,8]])})));return function(t,r){return e.apply(this,arguments)}}(),e}(),k=function(){};k.callApiEndpoint=function(){var e=l(g.mark((function e(t,n){var o;return g.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!r.StringUtils.isEmpty(n)){e.next=2;break}throw new Error(_.TOKEN_NOT_FOUND);case 2:return o={headers:{Authorization:"Bearer "+n}},e.prev=3,m.logInfo(y.REQUEST_FOR_RESOURCE),e.next=7,c.get(t,o);case 7:return e.abrupt("return",e.sent.data);case 11:return e.prev=11,e.t0=e.catch(3),console.log(e.t0),e.abrupt("return",e.t0);case 15:case"end":return e.stop()}}),e,null,[[3,11]])})));return function(t,r){return e.apply(this,arguments)}}(),k.handlePagination=function(){var e=l(g.mark((function e(t,r,n){var o;return g.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return void 0===n&&(n=[]),e.prev=1,e.next=4,k.callApiEndpoint(r,t);case 4:if((o=e.sent).value.map((function(e){return n.push(e.id)})),!o[N.PAGINATION_LINK]){e.next=12;break}return e.next=9,k.handlePagination(t,o[N.PAGINATION_LINK],n);case 9:return e.abrupt("return",e.sent);case 12:return e.abrupt("return",n);case 13:e.next=19;break;case 15:return e.prev=15,e.t0=e.catch(1),console.log(e.t0),e.abrupt("return",e.t0);case 19:case"end":return e.stop()}}),e,null,[[1,15]])})));return function(t,r,n){return e.apply(this,arguments)}}();var b=function(){};b.ensureAbsoluteUrl=function(e,t){var n=new r.UrlString(t).getUrlComponents();return n.Protocol?t:n.HostNameAndPort?e.protocol+"://"+t:e.protocol+"://"+e.get("host")+t};var I=["_claim_names","_claim_sources"],A=function(){function e(e,o){var a=this;this.initialize=function(e){var r=t.Router();return r.get(a.appSettings.authRoutes.redirect,a.handleRedirect()),a.appSettings.authRoutes.frontChannelLogout&&r.get(a.appSettings.authRoutes.frontChannelLogout,(function(e,t,r){e.session.destroy((function(){t.sendStatus(200)}))})),r},this.signIn=function(e){return function(t,n,o){t.session.authCodeRequest||(t.session.authCodeRequest={authority:"",scopes:[],state:{},redirectUri:""}),t.session.tokenRequest||(t.session.tokenRequest={authority:"",scopes:[],redirectUri:"",code:""}),t.session.account||(t.session.account={homeAccountId:"",environment:"",tenantId:"",username:"",idTokenClaims:{}}),t.session.nonce=a.cryptoProvider.createNewGuid();var i=a.cryptoProvider.base64Encode(JSON.stringify({stage:v.SIGN_IN,path:e.successRedirect,nonce:t.session.nonce})),s={authority:a.msalConfig.auth.authority,scopes:r.OIDC_DEFAULT_SCOPES,state:i,redirect:b.ensureAbsoluteUrl(t,a.appSettings.authRoutes.redirect),prompt:r.PromptValue.SELECT_ACCOUNT};return a.getAuthCode(t,n,o,s)}},this.signOut=function(e){return function(t,r,n){var o=b.ensureAbsoluteUrl(t,e.successRedirect),i=a.msalConfig.auth.authority+"/oauth2/v2.0/logout?post_logout_redirect_uri="+o;t.session.isAuthenticated=!1,t.session.destroy((function(){r.redirect(i)}))}},this.handleRedirect=function(e){return function(){var e=l(g.mark((function e(t,r,n){var o,i,s;return g.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.query.state){e.next=53;break}if((o=JSON.parse(a.cryptoProvider.base64Decode(t.query.state))).nonce!==t.session.nonce){e.next=49;break}e.t0=o.stage,e.next=e.t0===v.SIGN_IN?6:e.t0===v.ACQUIRE_TOKEN?29:44;break;case 6:return t.session.tokenRequest.code=t.query.code,e.prev=7,e.next=10,a.msalClient.acquireTokenByCode(t.session.tokenRequest);case 10:return i=e.sent,e.prev=11,e.next=14,a.tokenValidator.validateIdToken(i.idToken);case 14:e.sent?(t.session.account=i.account,t.session.isAuthenticated=!0,r.redirect(o.path)):(m.logError(_.INVALID_TOKEN),r.redirect(a.appSettings.authRoutes.unauthorized)),e.next=22;break;case 18:e.prev=18,e.t1=e.catch(11),m.logError(_.CANNOT_VALIDATE_TOKEN),n(e.t1);case 22:e.next=28;break;case 24:e.prev=24,e.t2=e.catch(7),m.logError(_.TOKEN_ACQUISITION_FAILED),n(e.t2);case 28:return e.abrupt("break",47);case 29:return s=a.getResourceNameFromScopes(t.session.tokenRequest.scopes),t.session.tokenRequest.code=t.query.code,e.prev=31,e.next=34,a.msalClient.acquireTokenByCode(t.session.tokenRequest);case 34:t.session.remoteResources[s].accessToken=e.sent.accessToken,r.redirect(o.path),e.next=43;break;case 39:e.prev=39,e.t3=e.catch(31),m.logError(_.TOKEN_ACQUISITION_FAILED),n(e.t3);case 43:return e.abrupt("break",47);case 44:return m.logError(_.CANNOT_DETERMINE_APP_STAGE),r.redirect(a.appSettings.authRoutes.error),e.abrupt("break",47);case 47:e.next=51;break;case 49:m.logError(_.NONCE_MISMATCH),r.redirect(a.appSettings.authRoutes.unauthorized);case 51:e.next=55;break;case 53:m.logError(_.STATE_NOT_FOUND),r.redirect(a.appSettings.authRoutes.unauthorized);case 55:case"end":return e.stop()}}),e,null,[[7,24],[11,18],[31,39]])})));return function(t,r,n){return e.apply(this,arguments)}}()},this.getToken=function(e){return function(){var t=l(g.mark((function t(n,o,i){var s,u,c,p,l,d,f;return g.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return c=a.getResourceNameFromScopes(u=e.resource.scopes),n.session.remoteResources||(n.session.remoteResources={}),n.session.remoteResources=((s={})[c]=h({},a.appSettings.remoteResources[c],{accessToken:null}),s),t.prev=4,p={account:n.session.account,scopes:u},t.next=8,a.msalClient.acquireTokenSilent(p);case 8:if(!r.StringUtils.isEmpty((l=t.sent).accessToken)){t.next=12;break}throw m.logError(_.TOKEN_NOT_FOUND),new r.InteractionRequiredAuthError(_.INTERACTION_REQUIRED);case 12:n.session.remoteResources[c].accessToken=l.accessToken,i(),t.next=25;break;case 16:if(t.prev=16,t.t0=t.catch(4),!(t.t0 instanceof r.InteractionRequiredAuthError)){t.next=24;break}return d=a.cryptoProvider.base64Encode(JSON.stringify({stage:v.ACQUIRE_TOKEN,path:n.originalUrl,nonce:n.session.nonce})),f={authority:a.msalConfig.auth.authority,scopes:u,state:d,redirect:b.ensureAbsoluteUrl(n,a.appSettings.authRoutes.redirect),account:n.session.account},t.abrupt("return",a.getAuthCode(n,o,i,f));case 24:i(t.t0);case 25:case"end":return t.stop()}}),t,null,[[4,16]])})));return function(e,r,n){return t.apply(this,arguments)}}()},this.getTokenOnBehalf=function(e){return function(){var t=l(g.mark((function t(r,n,o){var i,s,u,c,p;return g.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return i=r.headers.authorization,u=a.getResourceNameFromScopes(s=e.resource.scopes),c={oboAssertion:i.split(" ")[1],scopes:s},t.prev=4,t.next=7,a.msalClient.acquireTokenOnBehalfOf(c);case 7:r.locals=((p={})[u]={accessToken:t.sent.accessToken},p),o(),t.next=15;break;case 12:t.prev=12,t.t0=t.catch(4),o(t.t0);case 15:case"end":return t.stop()}}),t,null,[[4,12]])})));return function(e,r,n){return t.apply(this,arguments)}}()},this.isAuthenticated=function(e){return function(e,t,r){if(e.session){if(!e.session.isAuthenticated)return m.logError(_.NOT_PERMITTED),t.redirect(a.appSettings.authRoutes.unauthorized);r()}else m.logError(_.SESSION_NOT_FOUND),t.redirect(a.appSettings.authRoutes.unauthorized)}},this.isAuthorized=function(e){return function(){var e=l(g.mark((function e(t,r,n){var o;return g.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(o=t.headers.authorization.split(" ")[1],!t.headers.authorization){e.next=10;break}return e.next=4,a.tokenValidator.verifyAccessTokenSignature(o,""+t.baseUrl+t.path);case 4:if(e.sent){e.next=7;break}return m.logError(_.INVALID_TOKEN),e.abrupt("return",r.redirect(a.appSettings.authRoutes.unauthorized));case 7:n(),e.next=12;break;case 10:m.logError(_.TOKEN_NOT_FOUND),r.redirect(a.appSettings.authRoutes.unauthorized);case 12:case"end":return e.stop()}}),e)})));return function(t,r,n){return e.apply(this,arguments)}}()},this.hasAccess=function(e){return function(){var t=l(g.mark((function t(r,n,o){var i;return g.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!r.session||!a.appSettings.accessMatrix){t.next=35;break}i=e.accessRule.hasOwnProperty(N.GROUPS)?N.GROUPS:N.ROLES,t.t0=i,t.next=t.t0===N.GROUPS?5:t.t0===N.ROLES?22:32;break;case 5:if(void 0!==r.session.account.idTokenClaims[N.GROUPS]){t.next=17;break}if(!r.session.account.idTokenClaims[N.CLAIM_NAMES]&&!r.session.account.idTokenClaims[N.CLAIM_SOURCES]){t.next=13;break}return m.logWarning(y.OVERAGE_OCCURRED),t.next=10,a.handleOverage(r,n,o,e.accessRule);case 10:return t.abrupt("return",t.sent);case 13:return m.logError(_.USER_HAS_NO_GROUP),t.abrupt("return",n.redirect(a.appSettings.authRoutes.unauthorized));case 15:t.next=20;break;case 17:if(a.checkAccessRule(r.method,e.accessRule,r.session.account.idTokenClaims[N.GROUPS],N.GROUPS)){t.next=20;break}return t.abrupt("return",n.redirect(a.appSettings.authRoutes.unauthorized));case 20:return o(),t.abrupt("break",33);case 22:if(void 0!==r.session.account.idTokenClaims[N.ROLES]){t.next=27;break}return m.logError(_.USER_HAS_NO_ROLE),t.abrupt("return",n.redirect(a.appSettings.authRoutes.unauthorized));case 27:if(a.checkAccessRule(r.method,e.accessRule,r.session.account.idTokenClaims[N.ROLES],N.ROLES)){t.next=30;break}return t.abrupt("return",n.redirect(a.appSettings.authRoutes.unauthorized));case 30:return o(),t.abrupt("break",33);case 32:return t.abrupt("break",33);case 33:t.next=36;break;case 35:n.redirect(a.appSettings.authRoutes.unauthorized);case 36:case"end":return t.stop()}}),t)})));return function(e,r,n){return t.apply(this,arguments)}}()},R.validateAppSettings(e),this.appSettings=e,this.msalConfig=R.getMsalConfiguration(e,o),this.msalClient=new n.ConfidentialClientApplication(this.msalConfig),this.tokenValidator=new C(this.appSettings,this.msalConfig),this.cryptoProvider=new n.CryptoProvider}e.buildAsync=function(){var t=l(g.mark((function t(r,n){var o,a;return g.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,o=new S,t.next=4,o.getCredentialFromKeyVault(r);case 4:return a=new e(t.sent,n),t.abrupt("return",a);case 9:t.prev=9,t.t0=t.catch(0),console.log(t.t0);case 12:case"end":return t.stop()}}),t,null,[[0,9]])})));return function(e,r){return t.apply(this,arguments)}}();var o=e.prototype;return o.getAuthCode=function(){var e=l(g.mark((function e(t,r,n,o){return g.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t.session.authCodeRequest.authority=o.authority,t.session.authCodeRequest.scopes=o.scopes,t.session.authCodeRequest.state=o.state,t.session.authCodeRequest.redirectUri=o.redirect,t.session.authCodeRequest.prompt=o.prompt,t.session.authCodeRequest.account=o.account,t.session.tokenRequest.authority=o.authority,t.session.tokenRequest.scopes=o.scopes,t.session.tokenRequest.redirectUri=o.redirect,e.prev=9,e.next=12,this.msalClient.getAuthCodeUrl(t.session.authCodeRequest);case 12:r.redirect(e.sent),e.next=20;break;case 16:e.prev=16,e.t0=e.catch(9),m.logError(_.AUTH_CODE_NOT_OBTAINED),n(e.t0);case 20:case"end":return e.stop()}}),e,this,[[9,16]])})));return function(t,r,n,o){return e.apply(this,arguments)}}(),o.handleOverage=function(){var e=l(g.mark((function e(t,r,n,o){var a,i,s,u;return g.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return a=d(t.session.account.idTokenClaims,I),i={account:t.session.account,scopes:N.GRAPH_MEMBER_SCOPES.split(" ")},e.prev=2,e.next=5,this.msalClient.acquireTokenSilent(i);case 5:return s=e.sent,e.prev=6,e.next=9,k.callApiEndpoint(N.GRAPH_MEMBERS_ENDPOINT,s.accessToken);case 9:if(!(u=e.sent)[N.PAGINATION_LINK]){e.next=28;break}return e.prev=11,e.next=14,k.handlePagination(s.accessToken,u[N.PAGINATION_LINK]);case 14:if(t.session.account.idTokenClaims=h({},a,{groups:e.sent}),this.checkAccessRule(t.method,o,t.session.account.idTokenClaims[N.GROUPS],N.GROUPS)){e.next=20;break}return e.abrupt("return",r.redirect(this.appSettings.authRoutes.unauthorized));case 20:return e.abrupt("return",n());case 21:e.next=26;break;case 23:e.prev=23,e.t0=e.catch(11),n(e.t0);case 26:e.next=34;break;case 28:if(t.session.account.idTokenClaims=h({},a,{groups:u.value.map((function(e){return e.id}))}),this.checkAccessRule(t.method,o,t.session.account.idTokenClaims[N.GROUPS],N.GROUPS)){e.next=33;break}return e.abrupt("return",r.redirect(this.appSettings.authRoutes.unauthorized));case 33:return e.abrupt("return",n());case 34:e.next=39;break;case 36:e.prev=36,e.t1=e.catch(6),n(e.t1);case 39:e.next=44;break;case 41:e.prev=41,e.t2=e.catch(2),n(e.t2);case 44:case"end":return e.stop()}}),e,this,[[2,41],[6,36],[11,23]])})));return function(t,r,n,o){return e.apply(this,arguments)}}(),o.checkAccessRule=function(e,t,r,n){if(!t.methods.includes(e))return m.logError(_.METHOD_NOT_ALLOWED),!1;switch(n){case N.GROUPS:if(t.groups.filter((function(e){return r.includes(e)})).length<1)return m.logError(_.USER_NOT_IN_GROUP),!1;break;case N.ROLES:if(t.roles.filter((function(e){return r.includes(e)})).length<1)return m.logError(_.USER_NOT_IN_ROLE),!1}return!0},o.getResourceNameFromScopes=function(e){var t=Object.values(h({},this.appSettings.remoteResources,this.appSettings.ownedResources)).findIndex((function(t){return JSON.stringify(t.scopes)===JSON.stringify(e)}));return Object.keys(h({},this.appSettings.remoteResources,this.appSettings.ownedResources))[t]},e}();exports.AADAuthorityConstants=E,exports.AccessConstants=N,exports.AppStages=v,exports.AuthProvider=A,exports.ConfigurationErrorMessages=T,exports.ConfigurationUtils=R,exports.ErrorCodes={65001:"AADSTS65001"},exports.ErrorMessages=_,exports.FetchManager=k,exports.InfoMessages=y,exports.KeyVaultCredentialTypes=O,exports.KeyVaultManager=S,exports.Logger=m,exports.TokenValidator=C,exports.UrlUtils=b; +"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}Object.defineProperty(exports,"__esModule",{value:!0});var t=e(require("express")),r=require("@azure/msal-common"),n=require("@azure/msal-node"),o=e(require("jsonwebtoken")),a=e(require("jwks-rsa")),i=require("@azure/keyvault-certificates"),s=require("@azure/identity"),u=require("@azure/keyvault-secrets"),c=e(require("axios"));function p(e,t,r,n,o,a,i){try{var s=e[a](i),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,o)}function l(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var a=e.apply(t,r);function i(e){p(a,n,o,i,s,"next",e)}function s(e){p(a,n,o,i,s,"throw",e)}i(void 0)}))}}function h(){return(h=Object.assign||function(e){for(var t=1;t=0||(o[r]=e[r]);return o}var f,g=(function(e){var t=function(e){var t=Object.prototype,r=t.hasOwnProperty,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",a=n.asyncIterator||"@@asyncIterator",i=n.toStringTag||"@@toStringTag";function s(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{s({},"")}catch(e){s=function(e,t,r){return e[t]=r}}function u(e,t,r,n){var o=Object.create((t&&t.prototype instanceof l?t:l).prototype),a=new m(n||[]);return o._invoke=function(e,t,r){var n="suspendedStart";return function(o,a){if("executing"===n)throw new Error("Generator is already running");if("completed"===n){if("throw"===o)throw a;return{value:void 0,done:!0}}for(r.method=o,r.arg=a;;){var i=r.delegate;if(i){var s=y(i,r);if(s){if(s===p)continue;return s}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if("suspendedStart"===n)throw n="completed",r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n="executing";var u=c(e,t,r);if("normal"===u.type){if(n=r.done?"completed":"suspendedYield",u.arg===p)continue;return{value:u.arg,done:r.done}}"throw"===u.type&&(n="completed",r.method="throw",r.arg=u.arg)}}}(e,r,a),o}function c(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}e.wrap=u;var p={};function l(){}function h(){}function d(){}var f={};f[o]=function(){return this};var g=Object.getPrototypeOf,v=g&&g(g(R([])));v&&v!==t&&r.call(v,o)&&(f=v);var E=d.prototype=l.prototype=Object.create(f);function O(e){["next","throw","return"].forEach((function(t){s(e,t,(function(e){return this._invoke(t,e)}))}))}function N(e,t){var n;this._invoke=function(o,a){function i(){return new t((function(n,i){!function n(o,a,i,s){var u=c(e[o],e,a);if("throw"!==u.type){var p=u.arg,l=p.value;return l&&"object"==typeof l&&r.call(l,"__await")?t.resolve(l.__await).then((function(e){n("next",e,i,s)}),(function(e){n("throw",e,i,s)})):t.resolve(l).then((function(e){p.value=e,i(p)}),(function(e){return n("throw",e,i,s)}))}s(u.arg)}(o,a,n,i)}))}return n=n?n.then(i,i):i()}}function y(e,t){var r=e.iterator[t.method];if(void 0===r){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=void 0,y(e,t),"throw"===t.method))return p;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return p}var n=c(r,e.iterator,t.arg);if("throw"===n.type)return t.method="throw",t.arg=n.arg,t.delegate=null,p;var o=n.arg;return o?o.done?(t[e.resultName]=o.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,p):o:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,p)}function _(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function T(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function m(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(_,this),this.reset(!0)}function R(e){if(e){var t=e[o];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var n=-1,a=function t(){for(;++n=0;--o){var a=this.tryEntries[o],i=a.completion;if("root"===a.tryLoc)return n("end");if(a.tryLoc<=this.prev){var s=r.call(a,"catchLoc"),u=r.call(a,"finallyLoc");if(s&&u){if(this.prev=0;--n){var o=this.tryEntries[n];if(o.tryLoc<=this.prev&&r.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),T(r),p}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;T(r)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,r){return this.delegate={iterator:R(e),resultName:t,nextLoc:r},"next"===this.method&&(this.arg=void 0),p}},e}(e.exports);try{regeneratorRuntime=t}catch(e){Function("r","regeneratorRuntime = r")(t)}}(f={exports:{}}),f.exports),v={SIGN_IN:"sign_in",SIGN_OUT:"sign_out",ACQUIRE_TOKEN:"acquire_token"},E={COMMON:"common",ORGANIZATIONS:"organizations",CONSUMERS:"consumers"},O={SECRET:"secret",CERTIFICATE:"certificate"},N={GROUPS:"groups",ROLES:"roles",CLAIM_NAMES:"_claim_name",CLAIM_SOURCES:"_claim_sources",PAGINATION_LINK:"@odata.nextLink",GRAPH_MEMBERS_ENDPOINT:"https://graph.microsoft.com/v1.0/me/memberOf",GRAPH_MEMBER_SCOPES:"User.Read GroupMember.Read.All"},y={REQUEST_FOR_RESOURCE:"Request made to web API",OVERAGE_OCCURRED:"User has too many groups. Groups overage claim occurred"},_={NOT_PERMITTED:"Not permitted",INVALID_TOKEN:"Invalid token",CANNOT_DETERMINE_APP_STAGE:"Cannot determine application stage",CANNOT_VALIDATE_TOKEN:"Cannot validate token",NONCE_MISMATCH:"Nonce does not match",INTERACTION_REQUIRED:"interaction_required",TOKEN_ACQUISITION_FAILED:"Token acquisition failed",AUTH_CODE_NOT_OBTAINED:"Authorization code cannot be obtained",TOKEN_NOT_FOUND:"No token found",TOKEN_NOT_DECODED:"Token cannot be decoded",TOKEN_NOT_VERIFIED:"Token cannot be verified",KEYS_NOT_OBTAINED:"Signing keys cannot be obtained",STATE_NOT_FOUND:"State not found",USER_HAS_NO_ROLE:"User does not have any roles",USER_NOT_IN_ROLE:"User does not have this role",USER_HAS_NO_GROUP:"User does not have any groups",USER_NOT_IN_GROUP:"User does not have this group",METHOD_NOT_ALLOWED:"Method not allowed for this route",RULE_NOT_FOUND:"No rule found for this route",SESSION_NOT_FOUND:"No session found for this request",KEY_VAULT_CONFIG_NOT_FOUND:"No coordinates found for Key Vault"},T={NO_CLIENT_ID:"No clientId provided!",INVALID_CLIENT_ID:"Invalid clientId!",NO_TENANT_INFO:"No tenant info provided!",INVALID_TENANT_INFO:"Invalid tenant info!",NO_CLIENT_CREDENTIAL:"No client credential provided!",NO_REDIRECT_URI:"No redirect URI provided!",NO_ERROR_ROUTE:"No error route provided!",NO_UNAUTHORIZED_ROUTE:"No unauthorized route provided!"},m=function(){function e(){}return e.validateAppSettings=function(t){if(r.StringUtils.isEmpty(t.appCredentials.clientId))throw new Error(T.NO_CLIENT_ID);if(!e.isGuid(t.appCredentials.clientId))throw new Error(T.INVALID_CLIENT_ID);if(r.StringUtils.isEmpty(t.appCredentials.tenantId))throw new Error(T.NO_TENANT_INFO);if(!e.isGuid(t.appCredentials.tenantId)&&!Object.values(E).includes(t.appCredentials.tenantId))throw new Error(T.INVALID_TENANT_INFO);if(r.StringUtils.isEmpty(t.appCredentials.clientSecret)&&!t.appCredentials.clientCertificate)throw new Error(T.NO_CLIENT_CREDENTIAL);if(r.StringUtils.isEmpty(t.authRoutes.redirect))throw new Error(T.NO_REDIRECT_URI);if(r.StringUtils.isEmpty(t.authRoutes.error))throw new Error(T.NO_ERROR_ROUTE);if(r.StringUtils.isEmpty(t.authRoutes.unauthorized))throw new Error(T.NO_UNAUTHORIZED_ROUTE)},e.getMsalConfiguration=function(e,t){return void 0===t&&(t=null),{auth:h({clientId:e.appCredentials.clientId,authority:e.b2cPolicies?Object.entries(e.b2cPolicies)[0][1].authority:"https://"+r.Constants.DEFAULT_AUTHORITY_HOST+"/"+e.appCredentials.tenantId},e.appCredentials.hasOwnProperty("clientSecret")&&{clientSecret:e.appCredentials.clientSecret},e.appCredentials.hasOwnProperty("clientCertificate")&&{clientCertificate:e.appCredentials.clientCertificate},{knownAuthorities:e.b2cPolicies?[r.UrlString.getDomainFromUrl(Object.entries(e.b2cPolicies)[0][1].authority)]:[]}),cache:{cachePlugin:t},system:{loggerOptions:{loggerCallback:function(e,t,r){if(!r)switch(e){case n.LogLevel.Error:return void console.error(t);case n.LogLevel.Info:return void console.info(t);case n.LogLevel.Verbose:return void console.debug(t);case n.LogLevel.Warning:return void console.warn(t)}},piiLoggingEnabled:!1,logLevel:n.LogLevel.Verbose}}}},e.isGuid=function(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)},e}(),R=function(){function e(){}return e.logError=function(e){console.error(this.logMessage(e))},e.logWarning=function(e){console.warn(this.logMessage(e))},e.logInfo=function(e){console.info(this.logMessage(e))},e.logMessage=function(e){return"["+(new Date).toUTCString()+"] : @azure-samples/msal-express-wrapper@0.1.0 : "+r.LogLevel[r.LogLevel.Verbose]+" - "+e},e}(),C=function(){function e(e,t){this.appSettings=e,this.msalConfig=t}var t=e.prototype;return t.verifyTokenSignature=function(){var e=l(g.mark((function e(t){var n,a,i;return g.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!r.StringUtils.isEmpty(t)){e.next=3;break}return R.logError(_.TOKEN_NOT_FOUND),e.abrupt("return",!1);case 3:e.prev=3,n=o.decode(t,{complete:!0}),e.next=12;break;case 7:return e.prev=7,e.t0=e.catch(3),R.logError(_.TOKEN_NOT_DECODED),console.log(e.t0),e.abrupt("return",!1);case 12:return e.prev=12,e.next=15,this.getSigningKeys(n.header,n.payload.tid);case 15:a=e.sent,e.next=23;break;case 18:return e.prev=18,e.t1=e.catch(12),R.logError(_.KEYS_NOT_OBTAINED),console.log(e.t1),e.abrupt("return",!1);case 23:return e.prev=23,i=o.verify(t,a),this.appSettings.appCredentials.tenantId!==E.COMMON&&this.appSettings.appCredentials.tenantId!==E.ORGANIZATIONS&&this.appSettings.appCredentials.tenantId!==E.CONSUMERS||(this.appSettings.appCredentials.tenantId=n.payload.tid),e.abrupt("return",i);case 29:return e.prev=29,e.t2=e.catch(23),R.logError(_.TOKEN_NOT_VERIFIED),console.log(e.t2),e.abrupt("return",!1);case 34:case"end":return e.stop()}}),e,this,[[3,7],[12,18],[23,29]])})));return function(t){return e.apply(this,arguments)}}(),t.validateIdToken=function(){var e=l(g.mark((function e(t){var r;return g.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this.verifyTokenSignature(t);case 3:if(!(r=e.sent)){e.next=8;break}return e.abrupt("return",this.validateIdTokenClaims(r));case 8:return e.abrupt("return",!1);case 9:e.next=15;break;case 11:return e.prev=11,e.t0=e.catch(0),console.log(e.t0),e.abrupt("return",!1);case 15:case"end":return e.stop()}}),e,this,[[0,11]])})));return function(t){return e.apply(this,arguments)}}(),t.validateIdTokenClaims=function(e){var t=Math.round((new Date).getTime()/1e3);return!!e.iss.includes(this.appSettings.appCredentials.tenantId)&&e.aud===this.msalConfig.auth.clientId&&e.iat<=t&&e.exp>=t},t.verifyAccessTokenSignature=function(){var e=l(g.mark((function e(t,r){var n;return g.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this.verifyTokenSignature(t);case 3:if(!(n=e.sent)){e.next=8;break}return e.abrupt("return",this.validateAccessTokenClaims(n,r));case 8:return e.abrupt("return",!1);case 9:e.next=15;break;case 11:return e.prev=11,e.t0=e.catch(0),console.log(e.t0),e.abrupt("return",!1);case 15:case"end":return e.stop()}}),e,this,[[0,11]])})));return function(t,r){return e.apply(this,arguments)}}(),t.validateAccessTokenClaims=function(e,t){var r=Math.round((new Date).getTime()/1e3),n=!!e.iss.includes(this.appSettings.appCredentials.tenantId),o=e.iat<=r&&e.iat>=r,a=e.aud===this.appSettings.appCredentials.clientId||e.aud==="api://"+this.appSettings.appCredentials.clientId,i=Object.values(this.appSettings.ownedResources).find((function(e){return e.endpoint===t})).scopes.every((function(t){return e.scp.includes(t)}));return a&&n&&o&&i},t.getSigningKeys=function(){var e=l(g.mark((function e(t,n){var o;return g.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return o=a({jwksUri:this.appSettings.b2cPolicies?this.msalConfig.auth.authority+"/discovery/v2.0/keys":"https://"+r.Constants.DEFAULT_AUTHORITY_HOST+"/"+n+"/discovery/v2.0/keys"}),e.next=4,o.getSigningKeyAsync(t.kid);case 4:return e.abrupt("return",e.sent.getPublicKey());case 5:case"end":return e.stop()}}),e,this)})));return function(t,r){return e.apply(this,arguments)}}(),e}(),S=function(){function e(){}var t=e.prototype;return t.getCredentialFromKeyVault=function(){var e=l(g.mark((function e(t){var r,n,o;return g.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=new s.DefaultAzureCredential,t.appCredentials.keyVaultCredential){e.next=3;break}return e.abrupt("return",t);case 3:e.t0=t.appCredentials.keyVaultCredential.credentialType,e.next=e.t0===O.SECRET?6:e.t0===O.CERTIFICATE?18:33;break;case 6:return e.prev=6,e.next=9,this.getSecretCredential(t,r);case 9:return t.appCredentials.clientSecret=e.sent.value,e.abrupt("return",t);case 14:e.prev=14,e.t1=e.catch(6),console.log(e.t1);case 17:return e.abrupt("break",34);case 18:return e.prev=18,e.next=21,this.getCertificateCredential(t,r);case 21:return n=e.sent,e.next=24,this.getSecretCredential(t,r);case 24:return o=e.sent,t.appCredentials.clientCertificate={thumbprint:n.properties.x509Thumbprint.toString(),privateKey:o.value.split("-----BEGIN CERTIFICATE-----\n")[0]},e.abrupt("return",t);case 29:e.prev=29,e.t2=e.catch(18),console.log(e.t2);case 32:case 33:return e.abrupt("break",34);case 34:case"end":return e.stop()}}),e,this,[[6,14],[18,29]])})));return function(t){return e.apply(this,arguments)}}(),t.getCertificateCredential=function(){var e=l(g.mark((function e(t,r){var n;return g.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=new i.CertificateClient(t.appCredentials.keyVaultCredential.keyVaultUrl,r),e.prev=1,e.next=4,n.getCertificate(t.appCredentials.keyVaultCredential.credentialName);case 4:return e.abrupt("return",e.sent);case 8:return e.prev=8,e.t0=e.catch(1),console.log(e.t0),e.abrupt("return",e.t0);case 12:case"end":return e.stop()}}),e,null,[[1,8]])})));return function(t,r){return e.apply(this,arguments)}}(),t.getSecretCredential=function(){var e=l(g.mark((function e(t,r){var n;return g.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=new u.SecretClient(t.appCredentials.keyVaultCredential.keyVaultUrl,r),e.prev=1,e.next=4,n.getSecret(t.appCredentials.keyVaultCredential.credentialName);case 4:return e.abrupt("return",e.sent);case 8:return e.prev=8,e.t0=e.catch(1),console.log(e.t0),e.abrupt("return",e.t0);case 12:case"end":return e.stop()}}),e,null,[[1,8]])})));return function(t,r){return e.apply(this,arguments)}}(),e}(),k=function(){};k.callApiEndpoint=function(){var e=l(g.mark((function e(t,n){var o;return g.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!r.StringUtils.isEmpty(n)){e.next=2;break}throw new Error(_.TOKEN_NOT_FOUND);case 2:return o={headers:{Authorization:"Bearer "+n}},e.prev=3,R.logInfo(y.REQUEST_FOR_RESOURCE),e.next=7,c.get(t,o);case 7:return e.abrupt("return",e.sent.data);case 11:return e.prev=11,e.t0=e.catch(3),console.log(e.t0),e.abrupt("return",e.t0);case 15:case"end":return e.stop()}}),e,null,[[3,11]])})));return function(t,r){return e.apply(this,arguments)}}(),k.handlePagination=function(){var e=l(g.mark((function e(t,r,n){var o;return g.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return void 0===n&&(n=[]),e.prev=1,e.next=4,k.callApiEndpoint(r,t);case 4:if((o=e.sent).value.map((function(e){return n.push(e.id)})),!o[N.PAGINATION_LINK]){e.next=12;break}return e.next=9,k.handlePagination(t,o[N.PAGINATION_LINK],n);case 9:return e.abrupt("return",e.sent);case 12:return e.abrupt("return",n);case 13:e.next=19;break;case 15:return e.prev=15,e.t0=e.catch(1),console.log(e.t0),e.abrupt("return",e.t0);case 19:case"end":return e.stop()}}),e,null,[[1,15]])})));return function(t,r,n){return e.apply(this,arguments)}}();var b=function(){};b.ensureAbsoluteUrl=function(e,t){var n=new r.UrlString(t).getUrlComponents();return n.Protocol?t:n.HostNameAndPort?e.protocol+"://"+t:e.protocol+"://"+e.get("host")+t},b.getPathFromUrl=function(e){return"/"+new r.UrlString(e).getUrlComponents().PathSegments.join("/")};var I=["_claim_names","_claim_sources"],A=function(){function e(e,o){var a=this;this.initialize=function(e){var r=t.Router();return r.get(b.getPathFromUrl(a.appSettings.authRoutes.redirect),a.handleRedirect()),a.appSettings.authRoutes.frontChannelLogout&&r.get(a.appSettings.authRoutes.frontChannelLogout,(function(e,t,r){e.session.destroy((function(){t.sendStatus(200)}))})),r},this.signIn=function(e){return function(t,n,o){t.session.authCodeRequest||(t.session.authCodeRequest={authority:"",scopes:[],state:{},redirectUri:""}),t.session.tokenRequest||(t.session.tokenRequest={authority:"",scopes:[],redirectUri:"",code:""}),t.session.account||(t.session.account={homeAccountId:"",environment:"",tenantId:"",username:"",idTokenClaims:{}}),t.session.nonce=a.cryptoProvider.createNewGuid();var i=a.cryptoProvider.base64Encode(JSON.stringify({stage:v.SIGN_IN,path:e.successRedirect,nonce:t.session.nonce})),s={authority:a.msalConfig.auth.authority,scopes:r.OIDC_DEFAULT_SCOPES,state:i,redirect:b.ensureAbsoluteUrl(t,a.appSettings.authRoutes.redirect),prompt:r.PromptValue.SELECT_ACCOUNT};return a.getAuthCode(t,n,o,s)}},this.signOut=function(e){return function(t,r,n){var o=b.ensureAbsoluteUrl(t,e.successRedirect),i=a.msalConfig.auth.authority+"/oauth2/v2.0/logout?post_logout_redirect_uri="+o;t.session.isAuthenticated=!1,t.session.destroy((function(){r.redirect(i)}))}},this.handleRedirect=function(e){return function(){var e=l(g.mark((function e(t,r,n){var o,i,s;return g.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.query.state){e.next=53;break}if((o=JSON.parse(a.cryptoProvider.base64Decode(t.query.state))).nonce!==t.session.nonce){e.next=49;break}e.t0=o.stage,e.next=e.t0===v.SIGN_IN?6:e.t0===v.ACQUIRE_TOKEN?29:44;break;case 6:return t.session.tokenRequest.code=t.query.code,e.prev=7,e.next=10,a.msalClient.acquireTokenByCode(t.session.tokenRequest);case 10:return i=e.sent,e.prev=11,e.next=14,a.tokenValidator.validateIdToken(i.idToken);case 14:e.sent?(t.session.account=i.account,t.session.isAuthenticated=!0,r.redirect(o.path)):(R.logError(_.INVALID_TOKEN),r.redirect(a.appSettings.authRoutes.unauthorized)),e.next=22;break;case 18:e.prev=18,e.t1=e.catch(11),R.logError(_.CANNOT_VALIDATE_TOKEN),n(e.t1);case 22:e.next=28;break;case 24:e.prev=24,e.t2=e.catch(7),R.logError(_.TOKEN_ACQUISITION_FAILED),n(e.t2);case 28:return e.abrupt("break",47);case 29:return s=a.getResourceNameFromScopes(t.session.tokenRequest.scopes),t.session.tokenRequest.code=t.query.code,e.prev=31,e.next=34,a.msalClient.acquireTokenByCode(t.session.tokenRequest);case 34:t.session.remoteResources[s].accessToken=e.sent.accessToken,r.redirect(o.path),e.next=43;break;case 39:e.prev=39,e.t3=e.catch(31),R.logError(_.TOKEN_ACQUISITION_FAILED),n(e.t3);case 43:return e.abrupt("break",47);case 44:return R.logError(_.CANNOT_DETERMINE_APP_STAGE),r.redirect(a.appSettings.authRoutes.error),e.abrupt("break",47);case 47:e.next=51;break;case 49:R.logError(_.NONCE_MISMATCH),r.redirect(a.appSettings.authRoutes.unauthorized);case 51:e.next=55;break;case 53:R.logError(_.STATE_NOT_FOUND),r.redirect(a.appSettings.authRoutes.unauthorized);case 55:case"end":return e.stop()}}),e,null,[[7,24],[11,18],[31,39]])})));return function(t,r,n){return e.apply(this,arguments)}}()},this.getToken=function(e){return function(){var t=l(g.mark((function t(n,o,i){var s,u,c,p,l,d,f;return g.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return c=a.getResourceNameFromScopes(u=e.resource.scopes),n.session.remoteResources||(n.session.remoteResources={}),n.session.remoteResources=((s={})[c]=h({},a.appSettings.remoteResources[c],{accessToken:null}),s),t.prev=4,p={account:n.session.account,scopes:u},t.next=8,a.msalClient.acquireTokenSilent(p);case 8:if(!r.StringUtils.isEmpty((l=t.sent).accessToken)){t.next=12;break}throw R.logError(_.TOKEN_NOT_FOUND),new r.InteractionRequiredAuthError(_.INTERACTION_REQUIRED);case 12:n.session.remoteResources[c].accessToken=l.accessToken,i(),t.next=25;break;case 16:if(t.prev=16,t.t0=t.catch(4),!(t.t0 instanceof r.InteractionRequiredAuthError)){t.next=24;break}return d=a.cryptoProvider.base64Encode(JSON.stringify({stage:v.ACQUIRE_TOKEN,path:n.originalUrl,nonce:n.session.nonce})),f={authority:a.msalConfig.auth.authority,scopes:u,state:d,redirect:b.ensureAbsoluteUrl(n,a.appSettings.authRoutes.redirect),account:n.session.account},t.abrupt("return",a.getAuthCode(n,o,i,f));case 24:i(t.t0);case 25:case"end":return t.stop()}}),t,null,[[4,16]])})));return function(e,r,n){return t.apply(this,arguments)}}()},this.getTokenOnBehalf=function(e){return function(){var t=l(g.mark((function t(r,n,o){var i,s,u,c,p;return g.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return i=r.headers.authorization,u=a.getResourceNameFromScopes(s=e.resource.scopes),c={oboAssertion:i.split(" ")[1],scopes:s},t.prev=4,t.next=7,a.msalClient.acquireTokenOnBehalfOf(c);case 7:r.locals=((p={})[u]={accessToken:t.sent.accessToken},p),o(),t.next=15;break;case 12:t.prev=12,t.t0=t.catch(4),o(t.t0);case 15:case"end":return t.stop()}}),t,null,[[4,12]])})));return function(e,r,n){return t.apply(this,arguments)}}()},this.isAuthenticated=function(e){return function(e,t,r){if(e.session){if(!e.session.isAuthenticated)return R.logError(_.NOT_PERMITTED),t.redirect(a.appSettings.authRoutes.unauthorized);r()}else R.logError(_.SESSION_NOT_FOUND),t.redirect(a.appSettings.authRoutes.unauthorized)}},this.isAuthorized=function(e){return function(){var e=l(g.mark((function e(t,r,n){var o;return g.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(o=t.headers.authorization.split(" ")[1],!t.headers.authorization){e.next=10;break}return e.next=4,a.tokenValidator.verifyAccessTokenSignature(o,""+t.baseUrl+t.path);case 4:if(e.sent){e.next=7;break}return R.logError(_.INVALID_TOKEN),e.abrupt("return",r.redirect(a.appSettings.authRoutes.unauthorized));case 7:n(),e.next=12;break;case 10:R.logError(_.TOKEN_NOT_FOUND),r.redirect(a.appSettings.authRoutes.unauthorized);case 12:case"end":return e.stop()}}),e)})));return function(t,r,n){return e.apply(this,arguments)}}()},this.hasAccess=function(e){return function(){var t=l(g.mark((function t(r,n,o){var i;return g.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!r.session||!a.appSettings.accessMatrix){t.next=35;break}i=e.accessRule.hasOwnProperty(N.GROUPS)?N.GROUPS:N.ROLES,t.t0=i,t.next=t.t0===N.GROUPS?5:t.t0===N.ROLES?22:32;break;case 5:if(void 0!==r.session.account.idTokenClaims[N.GROUPS]){t.next=17;break}if(!r.session.account.idTokenClaims[N.CLAIM_NAMES]&&!r.session.account.idTokenClaims[N.CLAIM_SOURCES]){t.next=13;break}return R.logWarning(y.OVERAGE_OCCURRED),t.next=10,a.handleOverage(r,n,o,e.accessRule);case 10:return t.abrupt("return",t.sent);case 13:return R.logError(_.USER_HAS_NO_GROUP),t.abrupt("return",n.redirect(a.appSettings.authRoutes.unauthorized));case 15:t.next=20;break;case 17:if(a.checkAccessRule(r.method,e.accessRule,r.session.account.idTokenClaims[N.GROUPS],N.GROUPS)){t.next=20;break}return t.abrupt("return",n.redirect(a.appSettings.authRoutes.unauthorized));case 20:return o(),t.abrupt("break",33);case 22:if(void 0!==r.session.account.idTokenClaims[N.ROLES]){t.next=27;break}return R.logError(_.USER_HAS_NO_ROLE),t.abrupt("return",n.redirect(a.appSettings.authRoutes.unauthorized));case 27:if(a.checkAccessRule(r.method,e.accessRule,r.session.account.idTokenClaims[N.ROLES],N.ROLES)){t.next=30;break}return t.abrupt("return",n.redirect(a.appSettings.authRoutes.unauthorized));case 30:return o(),t.abrupt("break",33);case 32:return t.abrupt("break",33);case 33:t.next=36;break;case 35:n.redirect(a.appSettings.authRoutes.unauthorized);case 36:case"end":return t.stop()}}),t)})));return function(e,r,n){return t.apply(this,arguments)}}()},m.validateAppSettings(e),this.appSettings=e,this.msalConfig=m.getMsalConfiguration(e,o),this.msalClient=new n.ConfidentialClientApplication(this.msalConfig),this.tokenValidator=new C(this.appSettings,this.msalConfig),this.cryptoProvider=new n.CryptoProvider}e.buildAsync=function(){var t=l(g.mark((function t(r,n){var o,a;return g.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,o=new S,t.next=4,o.getCredentialFromKeyVault(r);case 4:return a=new e(t.sent,n),t.abrupt("return",a);case 9:t.prev=9,t.t0=t.catch(0),console.log(t.t0);case 12:case"end":return t.stop()}}),t,null,[[0,9]])})));return function(e,r){return t.apply(this,arguments)}}();var o=e.prototype;return o.getAuthCode=function(){var e=l(g.mark((function e(t,r,n,o){return g.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t.session.authCodeRequest.authority=o.authority,t.session.authCodeRequest.scopes=o.scopes,t.session.authCodeRequest.state=o.state,t.session.authCodeRequest.redirectUri=o.redirect,t.session.authCodeRequest.prompt=o.prompt,t.session.authCodeRequest.account=o.account,t.session.tokenRequest.authority=o.authority,t.session.tokenRequest.scopes=o.scopes,t.session.tokenRequest.redirectUri=o.redirect,e.prev=9,e.next=12,this.msalClient.getAuthCodeUrl(t.session.authCodeRequest);case 12:r.redirect(e.sent),e.next=20;break;case 16:e.prev=16,e.t0=e.catch(9),R.logError(_.AUTH_CODE_NOT_OBTAINED),n(e.t0);case 20:case"end":return e.stop()}}),e,this,[[9,16]])})));return function(t,r,n,o){return e.apply(this,arguments)}}(),o.handleOverage=function(){var e=l(g.mark((function e(t,r,n,o){var a,i,s,u;return g.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return a=d(t.session.account.idTokenClaims,I),i={account:t.session.account,scopes:N.GRAPH_MEMBER_SCOPES.split(" ")},e.prev=2,e.next=5,this.msalClient.acquireTokenSilent(i);case 5:return s=e.sent,e.prev=6,e.next=9,k.callApiEndpoint(N.GRAPH_MEMBERS_ENDPOINT,s.accessToken);case 9:if(!(u=e.sent)[N.PAGINATION_LINK]){e.next=28;break}return e.prev=11,e.next=14,k.handlePagination(s.accessToken,u[N.PAGINATION_LINK]);case 14:if(t.session.account.idTokenClaims=h({},a,{groups:e.sent}),this.checkAccessRule(t.method,o,t.session.account.idTokenClaims[N.GROUPS],N.GROUPS)){e.next=20;break}return e.abrupt("return",r.redirect(this.appSettings.authRoutes.unauthorized));case 20:return e.abrupt("return",n());case 21:e.next=26;break;case 23:e.prev=23,e.t0=e.catch(11),n(e.t0);case 26:e.next=34;break;case 28:if(t.session.account.idTokenClaims=h({},a,{groups:u.value.map((function(e){return e.id}))}),this.checkAccessRule(t.method,o,t.session.account.idTokenClaims[N.GROUPS],N.GROUPS)){e.next=33;break}return e.abrupt("return",r.redirect(this.appSettings.authRoutes.unauthorized));case 33:return e.abrupt("return",n());case 34:e.next=39;break;case 36:e.prev=36,e.t1=e.catch(6),n(e.t1);case 39:e.next=44;break;case 41:e.prev=41,e.t2=e.catch(2),n(e.t2);case 44:case"end":return e.stop()}}),e,this,[[2,41],[6,36],[11,23]])})));return function(t,r,n,o){return e.apply(this,arguments)}}(),o.checkAccessRule=function(e,t,r,n){if(!t.methods.includes(e))return R.logError(_.METHOD_NOT_ALLOWED),!1;switch(n){case N.GROUPS:if(t.groups.filter((function(e){return r.includes(e)})).length<1)return R.logError(_.USER_NOT_IN_GROUP),!1;break;case N.ROLES:if(t.roles.filter((function(e){return r.includes(e)})).length<1)return R.logError(_.USER_NOT_IN_ROLE),!1}return!0},o.getResourceNameFromScopes=function(e){var t=Object.values(h({},this.appSettings.remoteResources,this.appSettings.ownedResources)).findIndex((function(t){return JSON.stringify(t.scopes)===JSON.stringify(e)}));return Object.keys(h({},this.appSettings.remoteResources,this.appSettings.ownedResources))[t]},e}();exports.AADAuthorityConstants=E,exports.AccessConstants=N,exports.AppStages=v,exports.AuthProvider=A,exports.ConfigurationErrorMessages=T,exports.ConfigurationUtils=m,exports.ErrorCodes={65001:"AADSTS65001"},exports.ErrorMessages=_,exports.FetchManager=k,exports.InfoMessages=y,exports.KeyVaultCredentialTypes=O,exports.KeyVaultManager=S,exports.Logger=R,exports.TokenValidator=C,exports.UrlUtils=b; //# sourceMappingURL=msal-express-wrapper.cjs.production.min.js.map diff --git a/dist/msal-express-wrapper.cjs.production.min.js.map b/dist/msal-express-wrapper.cjs.production.min.js.map index 5aabe5e..14304f3 100644 --- a/dist/msal-express-wrapper.cjs.production.min.js.map +++ b/dist/msal-express-wrapper.cjs.production.min.js.map @@ -1 +1 @@ -{"version":3,"file":"msal-express-wrapper.cjs.production.min.js","sources":["../node_modules/regenerator-runtime/runtime.js","../src/Constants.ts","../src/ConfigurationUtils.ts","../src/Logger.ts","../src/TokenValidator.ts","../src/KeyVaultManager.ts","../src/FetchManager.ts","../src/UrlUtils.ts","../src/AuthProvider.ts"],"sourcesContent":["/**\n * Copyright (c) 2014-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nvar runtime = (function (exports) {\n \"use strict\";\n\n var Op = Object.prototype;\n var hasOwn = Op.hasOwnProperty;\n var undefined; // More compressible than void 0.\n var $Symbol = typeof Symbol === \"function\" ? Symbol : {};\n var iteratorSymbol = $Symbol.iterator || \"@@iterator\";\n var asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\";\n var toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n\n function define(obj, key, value) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n return obj[key];\n }\n try {\n // IE 8 has a broken Object.defineProperty that only works on DOM objects.\n define({}, \"\");\n } catch (err) {\n define = function(obj, key, value) {\n return obj[key] = value;\n };\n }\n\n function wrap(innerFn, outerFn, self, tryLocsList) {\n // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.\n var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;\n var generator = Object.create(protoGenerator.prototype);\n var context = new Context(tryLocsList || []);\n\n // The ._invoke method unifies the implementations of the .next,\n // .throw, and .return methods.\n generator._invoke = makeInvokeMethod(innerFn, self, context);\n\n return generator;\n }\n exports.wrap = wrap;\n\n // Try/catch helper to minimize deoptimizations. Returns a completion\n // record like context.tryEntries[i].completion. This interface could\n // have been (and was previously) designed to take a closure to be\n // invoked without arguments, but in all the cases we care about we\n // already have an existing method we want to call, so there's no need\n // to create a new function object. We can even get away with assuming\n // the method takes exactly one argument, since that happens to be true\n // in every case, so we don't have to touch the arguments object. The\n // only additional allocation required is the completion record, which\n // has a stable shape and so hopefully should be cheap to allocate.\n function tryCatch(fn, obj, arg) {\n try {\n return { type: \"normal\", arg: fn.call(obj, arg) };\n } catch (err) {\n return { type: \"throw\", arg: err };\n }\n }\n\n var GenStateSuspendedStart = \"suspendedStart\";\n var GenStateSuspendedYield = \"suspendedYield\";\n var GenStateExecuting = \"executing\";\n var GenStateCompleted = \"completed\";\n\n // Returning this object from the innerFn has the same effect as\n // breaking out of the dispatch switch statement.\n var ContinueSentinel = {};\n\n // Dummy constructor functions that we use as the .constructor and\n // .constructor.prototype properties for functions that return Generator\n // objects. For full spec compliance, you may wish to configure your\n // minifier not to mangle the names of these two functions.\n function Generator() {}\n function GeneratorFunction() {}\n function GeneratorFunctionPrototype() {}\n\n // This is a polyfill for %IteratorPrototype% for environments that\n // don't natively support it.\n var IteratorPrototype = {};\n IteratorPrototype[iteratorSymbol] = function () {\n return this;\n };\n\n var getProto = Object.getPrototypeOf;\n var NativeIteratorPrototype = getProto && getProto(getProto(values([])));\n if (NativeIteratorPrototype &&\n NativeIteratorPrototype !== Op &&\n hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {\n // This environment has a native %IteratorPrototype%; use it instead\n // of the polyfill.\n IteratorPrototype = NativeIteratorPrototype;\n }\n\n var Gp = GeneratorFunctionPrototype.prototype =\n Generator.prototype = Object.create(IteratorPrototype);\n GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;\n GeneratorFunctionPrototype.constructor = GeneratorFunction;\n GeneratorFunction.displayName = define(\n GeneratorFunctionPrototype,\n toStringTagSymbol,\n \"GeneratorFunction\"\n );\n\n // Helper for defining the .next, .throw, and .return methods of the\n // Iterator interface in terms of a single ._invoke method.\n function defineIteratorMethods(prototype) {\n [\"next\", \"throw\", \"return\"].forEach(function(method) {\n define(prototype, method, function(arg) {\n return this._invoke(method, arg);\n });\n });\n }\n\n exports.isGeneratorFunction = function(genFun) {\n var ctor = typeof genFun === \"function\" && genFun.constructor;\n return ctor\n ? ctor === GeneratorFunction ||\n // For the native GeneratorFunction constructor, the best we can\n // do is to check its .name property.\n (ctor.displayName || ctor.name) === \"GeneratorFunction\"\n : false;\n };\n\n exports.mark = function(genFun) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);\n } else {\n genFun.__proto__ = GeneratorFunctionPrototype;\n define(genFun, toStringTagSymbol, \"GeneratorFunction\");\n }\n genFun.prototype = Object.create(Gp);\n return genFun;\n };\n\n // Within the body of any async function, `await x` is transformed to\n // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test\n // `hasOwn.call(value, \"__await\")` to determine if the yielded value is\n // meant to be awaited.\n exports.awrap = function(arg) {\n return { __await: arg };\n };\n\n function AsyncIterator(generator, PromiseImpl) {\n function invoke(method, arg, resolve, reject) {\n var record = tryCatch(generator[method], generator, arg);\n if (record.type === \"throw\") {\n reject(record.arg);\n } else {\n var result = record.arg;\n var value = result.value;\n if (value &&\n typeof value === \"object\" &&\n hasOwn.call(value, \"__await\")) {\n return PromiseImpl.resolve(value.__await).then(function(value) {\n invoke(\"next\", value, resolve, reject);\n }, function(err) {\n invoke(\"throw\", err, resolve, reject);\n });\n }\n\n return PromiseImpl.resolve(value).then(function(unwrapped) {\n // When a yielded Promise is resolved, its final value becomes\n // the .value of the Promise<{value,done}> result for the\n // current iteration.\n result.value = unwrapped;\n resolve(result);\n }, function(error) {\n // If a rejected Promise was yielded, throw the rejection back\n // into the async generator function so it can be handled there.\n return invoke(\"throw\", error, resolve, reject);\n });\n }\n }\n\n var previousPromise;\n\n function enqueue(method, arg) {\n function callInvokeWithMethodAndArg() {\n return new PromiseImpl(function(resolve, reject) {\n invoke(method, arg, resolve, reject);\n });\n }\n\n return previousPromise =\n // If enqueue has been called before, then we want to wait until\n // all previous Promises have been resolved before calling invoke,\n // so that results are always delivered in the correct order. If\n // enqueue has not been called before, then it is important to\n // call invoke immediately, without waiting on a callback to fire,\n // so that the async generator function has the opportunity to do\n // any necessary setup in a predictable way. This predictability\n // is why the Promise constructor synchronously invokes its\n // executor callback, and why async functions synchronously\n // execute code before the first await. Since we implement simple\n // async functions in terms of async generators, it is especially\n // important to get this right, even though it requires care.\n previousPromise ? previousPromise.then(\n callInvokeWithMethodAndArg,\n // Avoid propagating failures to Promises returned by later\n // invocations of the iterator.\n callInvokeWithMethodAndArg\n ) : callInvokeWithMethodAndArg();\n }\n\n // Define the unified helper method that is used to implement .next,\n // .throw, and .return (see defineIteratorMethods).\n this._invoke = enqueue;\n }\n\n defineIteratorMethods(AsyncIterator.prototype);\n AsyncIterator.prototype[asyncIteratorSymbol] = function () {\n return this;\n };\n exports.AsyncIterator = AsyncIterator;\n\n // Note that simple async functions are implemented on top of\n // AsyncIterator objects; they just return a Promise for the value of\n // the final result produced by the iterator.\n exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {\n if (PromiseImpl === void 0) PromiseImpl = Promise;\n\n var iter = new AsyncIterator(\n wrap(innerFn, outerFn, self, tryLocsList),\n PromiseImpl\n );\n\n return exports.isGeneratorFunction(outerFn)\n ? iter // If outerFn is a generator, return the full iterator.\n : iter.next().then(function(result) {\n return result.done ? result.value : iter.next();\n });\n };\n\n function makeInvokeMethod(innerFn, self, context) {\n var state = GenStateSuspendedStart;\n\n return function invoke(method, arg) {\n if (state === GenStateExecuting) {\n throw new Error(\"Generator is already running\");\n }\n\n if (state === GenStateCompleted) {\n if (method === \"throw\") {\n throw arg;\n }\n\n // Be forgiving, per 25.3.3.3.3 of the spec:\n // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume\n return doneResult();\n }\n\n context.method = method;\n context.arg = arg;\n\n while (true) {\n var delegate = context.delegate;\n if (delegate) {\n var delegateResult = maybeInvokeDelegate(delegate, context);\n if (delegateResult) {\n if (delegateResult === ContinueSentinel) continue;\n return delegateResult;\n }\n }\n\n if (context.method === \"next\") {\n // Setting context._sent for legacy support of Babel's\n // function.sent implementation.\n context.sent = context._sent = context.arg;\n\n } else if (context.method === \"throw\") {\n if (state === GenStateSuspendedStart) {\n state = GenStateCompleted;\n throw context.arg;\n }\n\n context.dispatchException(context.arg);\n\n } else if (context.method === \"return\") {\n context.abrupt(\"return\", context.arg);\n }\n\n state = GenStateExecuting;\n\n var record = tryCatch(innerFn, self, context);\n if (record.type === \"normal\") {\n // If an exception is thrown from innerFn, we leave state ===\n // GenStateExecuting and loop back for another invocation.\n state = context.done\n ? GenStateCompleted\n : GenStateSuspendedYield;\n\n if (record.arg === ContinueSentinel) {\n continue;\n }\n\n return {\n value: record.arg,\n done: context.done\n };\n\n } else if (record.type === \"throw\") {\n state = GenStateCompleted;\n // Dispatch the exception by looping back around to the\n // context.dispatchException(context.arg) call above.\n context.method = \"throw\";\n context.arg = record.arg;\n }\n }\n };\n }\n\n // Call delegate.iterator[context.method](context.arg) and handle the\n // result, either by returning a { value, done } result from the\n // delegate iterator, or by modifying context.method and context.arg,\n // setting context.delegate to null, and returning the ContinueSentinel.\n function maybeInvokeDelegate(delegate, context) {\n var method = delegate.iterator[context.method];\n if (method === undefined) {\n // A .throw or .return when the delegate iterator has no .throw\n // method always terminates the yield* loop.\n context.delegate = null;\n\n if (context.method === \"throw\") {\n // Note: [\"return\"] must be used for ES3 parsing compatibility.\n if (delegate.iterator[\"return\"]) {\n // If the delegate iterator has a return method, give it a\n // chance to clean up.\n context.method = \"return\";\n context.arg = undefined;\n maybeInvokeDelegate(delegate, context);\n\n if (context.method === \"throw\") {\n // If maybeInvokeDelegate(context) changed context.method from\n // \"return\" to \"throw\", let that override the TypeError below.\n return ContinueSentinel;\n }\n }\n\n context.method = \"throw\";\n context.arg = new TypeError(\n \"The iterator does not provide a 'throw' method\");\n }\n\n return ContinueSentinel;\n }\n\n var record = tryCatch(method, delegate.iterator, context.arg);\n\n if (record.type === \"throw\") {\n context.method = \"throw\";\n context.arg = record.arg;\n context.delegate = null;\n return ContinueSentinel;\n }\n\n var info = record.arg;\n\n if (! info) {\n context.method = \"throw\";\n context.arg = new TypeError(\"iterator result is not an object\");\n context.delegate = null;\n return ContinueSentinel;\n }\n\n if (info.done) {\n // Assign the result of the finished delegate to the temporary\n // variable specified by delegate.resultName (see delegateYield).\n context[delegate.resultName] = info.value;\n\n // Resume execution at the desired location (see delegateYield).\n context.next = delegate.nextLoc;\n\n // If context.method was \"throw\" but the delegate handled the\n // exception, let the outer generator proceed normally. If\n // context.method was \"next\", forget context.arg since it has been\n // \"consumed\" by the delegate iterator. If context.method was\n // \"return\", allow the original .return call to continue in the\n // outer generator.\n if (context.method !== \"return\") {\n context.method = \"next\";\n context.arg = undefined;\n }\n\n } else {\n // Re-yield the result returned by the delegate method.\n return info;\n }\n\n // The delegate iterator is finished, so forget it and continue with\n // the outer generator.\n context.delegate = null;\n return ContinueSentinel;\n }\n\n // Define Generator.prototype.{next,throw,return} in terms of the\n // unified ._invoke helper method.\n defineIteratorMethods(Gp);\n\n define(Gp, toStringTagSymbol, \"Generator\");\n\n // A Generator should always return itself as the iterator object when the\n // @@iterator function is called on it. Some browsers' implementations of the\n // iterator prototype chain incorrectly implement this, causing the Generator\n // object to not be returned from this call. This ensures that doesn't happen.\n // See https://github.com/facebook/regenerator/issues/274 for more details.\n Gp[iteratorSymbol] = function() {\n return this;\n };\n\n Gp.toString = function() {\n return \"[object Generator]\";\n };\n\n function pushTryEntry(locs) {\n var entry = { tryLoc: locs[0] };\n\n if (1 in locs) {\n entry.catchLoc = locs[1];\n }\n\n if (2 in locs) {\n entry.finallyLoc = locs[2];\n entry.afterLoc = locs[3];\n }\n\n this.tryEntries.push(entry);\n }\n\n function resetTryEntry(entry) {\n var record = entry.completion || {};\n record.type = \"normal\";\n delete record.arg;\n entry.completion = record;\n }\n\n function Context(tryLocsList) {\n // The root entry object (effectively a try statement without a catch\n // or a finally block) gives us a place to store values thrown from\n // locations where there is no enclosing try statement.\n this.tryEntries = [{ tryLoc: \"root\" }];\n tryLocsList.forEach(pushTryEntry, this);\n this.reset(true);\n }\n\n exports.keys = function(object) {\n var keys = [];\n for (var key in object) {\n keys.push(key);\n }\n keys.reverse();\n\n // Rather than returning an object with a next method, we keep\n // things simple and return the next function itself.\n return function next() {\n while (keys.length) {\n var key = keys.pop();\n if (key in object) {\n next.value = key;\n next.done = false;\n return next;\n }\n }\n\n // To avoid creating an additional object, we just hang the .value\n // and .done properties off the next function object itself. This\n // also ensures that the minifier will not anonymize the function.\n next.done = true;\n return next;\n };\n };\n\n function values(iterable) {\n if (iterable) {\n var iteratorMethod = iterable[iteratorSymbol];\n if (iteratorMethod) {\n return iteratorMethod.call(iterable);\n }\n\n if (typeof iterable.next === \"function\") {\n return iterable;\n }\n\n if (!isNaN(iterable.length)) {\n var i = -1, next = function next() {\n while (++i < iterable.length) {\n if (hasOwn.call(iterable, i)) {\n next.value = iterable[i];\n next.done = false;\n return next;\n }\n }\n\n next.value = undefined;\n next.done = true;\n\n return next;\n };\n\n return next.next = next;\n }\n }\n\n // Return an iterator with no values.\n return { next: doneResult };\n }\n exports.values = values;\n\n function doneResult() {\n return { value: undefined, done: true };\n }\n\n Context.prototype = {\n constructor: Context,\n\n reset: function(skipTempReset) {\n this.prev = 0;\n this.next = 0;\n // Resetting context._sent for legacy support of Babel's\n // function.sent implementation.\n this.sent = this._sent = undefined;\n this.done = false;\n this.delegate = null;\n\n this.method = \"next\";\n this.arg = undefined;\n\n this.tryEntries.forEach(resetTryEntry);\n\n if (!skipTempReset) {\n for (var name in this) {\n // Not sure about the optimal order of these conditions:\n if (name.charAt(0) === \"t\" &&\n hasOwn.call(this, name) &&\n !isNaN(+name.slice(1))) {\n this[name] = undefined;\n }\n }\n }\n },\n\n stop: function() {\n this.done = true;\n\n var rootEntry = this.tryEntries[0];\n var rootRecord = rootEntry.completion;\n if (rootRecord.type === \"throw\") {\n throw rootRecord.arg;\n }\n\n return this.rval;\n },\n\n dispatchException: function(exception) {\n if (this.done) {\n throw exception;\n }\n\n var context = this;\n function handle(loc, caught) {\n record.type = \"throw\";\n record.arg = exception;\n context.next = loc;\n\n if (caught) {\n // If the dispatched exception was caught by a catch block,\n // then let that catch block handle the exception normally.\n context.method = \"next\";\n context.arg = undefined;\n }\n\n return !! caught;\n }\n\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n var record = entry.completion;\n\n if (entry.tryLoc === \"root\") {\n // Exception thrown outside of any try block that could handle\n // it, so set the completion value of the entire function to\n // throw the exception.\n return handle(\"end\");\n }\n\n if (entry.tryLoc <= this.prev) {\n var hasCatch = hasOwn.call(entry, \"catchLoc\");\n var hasFinally = hasOwn.call(entry, \"finallyLoc\");\n\n if (hasCatch && hasFinally) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n } else if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else if (hasCatch) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n }\n\n } else if (hasFinally) {\n if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else {\n throw new Error(\"try statement without catch or finally\");\n }\n }\n }\n },\n\n abrupt: function(type, arg) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc <= this.prev &&\n hasOwn.call(entry, \"finallyLoc\") &&\n this.prev < entry.finallyLoc) {\n var finallyEntry = entry;\n break;\n }\n }\n\n if (finallyEntry &&\n (type === \"break\" ||\n type === \"continue\") &&\n finallyEntry.tryLoc <= arg &&\n arg <= finallyEntry.finallyLoc) {\n // Ignore the finally entry if control is not jumping to a\n // location outside the try/catch block.\n finallyEntry = null;\n }\n\n var record = finallyEntry ? finallyEntry.completion : {};\n record.type = type;\n record.arg = arg;\n\n if (finallyEntry) {\n this.method = \"next\";\n this.next = finallyEntry.finallyLoc;\n return ContinueSentinel;\n }\n\n return this.complete(record);\n },\n\n complete: function(record, afterLoc) {\n if (record.type === \"throw\") {\n throw record.arg;\n }\n\n if (record.type === \"break\" ||\n record.type === \"continue\") {\n this.next = record.arg;\n } else if (record.type === \"return\") {\n this.rval = this.arg = record.arg;\n this.method = \"return\";\n this.next = \"end\";\n } else if (record.type === \"normal\" && afterLoc) {\n this.next = afterLoc;\n }\n\n return ContinueSentinel;\n },\n\n finish: function(finallyLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.finallyLoc === finallyLoc) {\n this.complete(entry.completion, entry.afterLoc);\n resetTryEntry(entry);\n return ContinueSentinel;\n }\n }\n },\n\n \"catch\": function(tryLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc === tryLoc) {\n var record = entry.completion;\n if (record.type === \"throw\") {\n var thrown = record.arg;\n resetTryEntry(entry);\n }\n return thrown;\n }\n }\n\n // The context.catch method must only be called with a location\n // argument that corresponds to a known catch block.\n throw new Error(\"illegal catch attempt\");\n },\n\n delegateYield: function(iterable, resultName, nextLoc) {\n this.delegate = {\n iterator: values(iterable),\n resultName: resultName,\n nextLoc: nextLoc\n };\n\n if (this.method === \"next\") {\n // Deliberately forget the last sent value so that we don't\n // accidentally pass it on to the delegate.\n this.arg = undefined;\n }\n\n return ContinueSentinel;\n }\n };\n\n // Regardless of whether this script is executing as a CommonJS module\n // or not, return the runtime object so that we can declare the variable\n // regeneratorRuntime in the outer scope, which allows this module to be\n // injected easily by `bin/regenerator --include-runtime script.js`.\n return exports;\n\n}(\n // If this script is executing as a CommonJS module, use module.exports\n // as the regeneratorRuntime namespace. Otherwise create a new empty\n // object. Either way, the resulting object will be used to initialize\n // the regeneratorRuntime variable at the top of this file.\n typeof module === \"object\" ? module.exports : {}\n));\n\ntry {\n regeneratorRuntime = runtime;\n} catch (accidentalStrictMode) {\n // This module should not be running in strict mode, so the above\n // assignment should always work unless something is misconfigured. Just\n // in case runtime.js accidentally runs in strict mode, we can escape\n // strict mode using a global Function call. This could conceivably fail\n // if a Content Security Policy forbids using Function, but in that case\n // the proper solution is to fix the accidental strict mode problem. If\n // you've misconfigured your bundler to force strict mode and applied a\n // CSP to forbid Function, and you're not willing to fix either of those\n // problems, please detail your unique predicament in a GitHub issue.\n Function(\"r\", \"regeneratorRuntime = r\")(runtime);\n}\n","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\n/**\r\n * Basic authentication stages used to determine\r\n * appropriate action after redirect occurs\r\n */\r\nexport const AppStages = {\r\n SIGN_IN: \"sign_in\",\r\n SIGN_OUT: \"sign_out\",\r\n ACQUIRE_TOKEN: \"acquire_token\",\r\n};\r\n\r\n/**\r\n * String constants related to AAD Authority\r\n */\r\nexport const AADAuthorityConstants = {\r\n COMMON: \"common\",\r\n ORGANIZATIONS: \"organizations\",\r\n CONSUMERS: \"consumers\"\r\n}\r\n\r\n/**\r\n * String constants related to AAD Authority\r\n */\r\nexport const KeyVaultCredentialTypes = {\r\n SECRET: \"secret\",\r\n CERTIFICATE: \"certificate\",\r\n}\r\n\r\n/**\r\n * Constants used in access control scenarios\r\n */\r\nexport const AccessConstants = {\r\n GROUPS: \"groups\",\r\n ROLES: \"roles\",\r\n CLAIM_NAMES: \"_claim_name\",\r\n CLAIM_SOURCES: \"_claim_sources\",\r\n PAGINATION_LINK: \"@odata.nextLink\",\r\n GRAPH_MEMBERS_ENDPOINT: \"https://graph.microsoft.com/v1.0/me/memberOf\",\r\n GRAPH_MEMBER_SCOPES: \"User.Read GroupMember.Read.All\"\r\n};\r\n\r\nexport const InfoMessages = {\r\n REQUEST_FOR_RESOURCE: \"Request made to web API\",\r\n OVERAGE_OCCURRED: \"User has too many groups. Groups overage claim occurred\"\r\n}\r\n\r\n/**\r\n * Various error constants\r\n */\r\nexport const ErrorMessages = {\r\n NOT_PERMITTED: \"Not permitted\",\r\n INVALID_TOKEN: \"Invalid token\",\r\n CANNOT_DETERMINE_APP_STAGE: \"Cannot determine application stage\",\r\n CANNOT_VALIDATE_TOKEN: \"Cannot validate token\",\r\n NONCE_MISMATCH: \"Nonce does not match\",\r\n INTERACTION_REQUIRED: \"interaction_required\",\r\n TOKEN_ACQUISITION_FAILED: \"Token acquisition failed\",\r\n AUTH_CODE_NOT_OBTAINED: \"Authorization code cannot be obtained\",\r\n TOKEN_NOT_FOUND: \"No token found\",\r\n TOKEN_NOT_DECODED: \"Token cannot be decoded\",\r\n TOKEN_NOT_VERIFIED: \"Token cannot be verified\",\r\n KEYS_NOT_OBTAINED: \"Signing keys cannot be obtained\",\r\n STATE_NOT_FOUND: \"State not found\",\r\n USER_HAS_NO_ROLE: \"User does not have any roles\",\r\n USER_NOT_IN_ROLE: \"User does not have this role\",\r\n USER_HAS_NO_GROUP: \"User does not have any groups\",\r\n USER_NOT_IN_GROUP: \"User does not have this group\",\r\n METHOD_NOT_ALLOWED: \"Method not allowed for this route\",\r\n RULE_NOT_FOUND: \"No rule found for this route\",\r\n SESSION_NOT_FOUND: \"No session found for this request\",\r\n KEY_VAULT_CONFIG_NOT_FOUND: \"No coordinates found for Key Vault\"\r\n};\r\n\r\nexport const ConfigurationErrorMessages = {\r\n NO_CLIENT_ID: \"No clientId provided!\",\r\n INVALID_CLIENT_ID: \"Invalid clientId!\",\r\n NO_TENANT_INFO: \"No tenant info provided!\",\r\n INVALID_TENANT_INFO: \"Invalid tenant info!\",\r\n NO_CLIENT_CREDENTIAL: \"No client credential provided!\",\r\n NO_REDIRECT_URI: \"No redirect URI provided!\",\r\n NO_ERROR_ROUTE: \"No error route provided!\",\r\n NO_UNAUTHORIZED_ROUTE: \"No unauthorized route provided!\"\r\n}\r\n\r\n/**\r\n * For more information, visit: https://login.microsoftonline.com/error\r\n */\r\nexport const ErrorCodes = {\r\n 65001: \"AADSTS65001\", // consent required\r\n};","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { \r\n UrlString, \r\n StringUtils,\r\n Constants, \r\n} from \"@azure/msal-common\";\r\n\r\nimport { \r\n ICachePlugin,\r\n Configuration,\r\n LogLevel \r\n} from \"@azure/msal-node\";\r\n\r\nimport { AppSettings } from \"./Types\";\r\n\r\nimport { \r\n AADAuthorityConstants, \r\n ConfigurationErrorMessages \r\n} from \"./Constants\";\r\n\r\nexport class ConfigurationUtils {\r\n\r\n /**\r\n * Validates the fields in the configuration file\r\n * @param {AppSettings} config: configuration object\r\n * @returns {void}\r\n */\r\n static validateAppSettings(config: AppSettings): void {\r\n if (StringUtils.isEmpty(config.appCredentials.clientId)) {\r\n throw new Error(ConfigurationErrorMessages.NO_CLIENT_ID);\r\n } else if (!ConfigurationUtils.isGuid(config.appCredentials.clientId)) {\r\n throw new Error(ConfigurationErrorMessages.INVALID_CLIENT_ID);\r\n }\r\n\r\n if (StringUtils.isEmpty(config.appCredentials.tenantId)) {\r\n throw new Error(ConfigurationErrorMessages.NO_TENANT_INFO);\r\n } else if (!ConfigurationUtils.isGuid(config.appCredentials.tenantId) && !Object.values(AADAuthorityConstants).includes(config.appCredentials.tenantId)) {\r\n throw new Error(ConfigurationErrorMessages.INVALID_TENANT_INFO);\r\n }\r\n\r\n if (StringUtils.isEmpty(config.appCredentials.clientSecret) && !config.appCredentials.clientCertificate) {\r\n throw new Error(ConfigurationErrorMessages.NO_CLIENT_CREDENTIAL);\r\n }\r\n\r\n if (StringUtils.isEmpty(config.authRoutes.redirect)) {\r\n throw new Error(ConfigurationErrorMessages.NO_REDIRECT_URI);\r\n }\r\n\r\n if (StringUtils.isEmpty(config.authRoutes.error)) {\r\n throw new Error(ConfigurationErrorMessages.NO_ERROR_ROUTE);\r\n }\r\n\r\n if (StringUtils.isEmpty(config.authRoutes.unauthorized)) {\r\n throw new Error(ConfigurationErrorMessages.NO_UNAUTHORIZED_ROUTE);\r\n }\r\n };\r\n\r\n\r\n /**\r\n * Maps the custom configuration object to configuration\r\n * object expected by MSAL Node ConfidentialClientApplication class\r\n * @param {AppSettings} config: configuration object\r\n * @param {ICachePlugin} cachePlugin: persistent cache implementation\r\n * @returns {Configuration}\r\n */\r\n static getMsalConfiguration(config: AppSettings, cachePlugin: ICachePlugin = null): Configuration {\r\n return {\r\n auth: {\r\n clientId: config.appCredentials.clientId,\r\n authority: config.b2cPolicies ?\r\n Object.entries(config.b2cPolicies)[0][1][\"authority\"]\r\n :\r\n `https://${Constants.DEFAULT_AUTHORITY_HOST}/${config.appCredentials.tenantId}`,\r\n ...(config.appCredentials.hasOwnProperty(\"clientSecret\")) && { clientSecret: config.appCredentials.clientSecret },\r\n ...(config.appCredentials.hasOwnProperty(\"clientCertificate\")) && { clientCertificate: config.appCredentials.clientCertificate },\r\n knownAuthorities: config.b2cPolicies ?\r\n [UrlString.getDomainFromUrl(Object.entries(config.b2cPolicies)[0][1][\"authority\"])] // in B2C scenarios\r\n :\r\n [],\r\n },\r\n cache: {\r\n cachePlugin,\r\n },\r\n system: {\r\n loggerOptions: {\r\n loggerCallback: (logLevel, message, containsPii) => {\r\n if (containsPii) {\r\n return;\r\n }\r\n switch (logLevel) {\r\n case LogLevel.Error:\r\n console.error(message);\r\n return;\r\n case LogLevel.Info:\r\n console.info(message);\r\n return;\r\n case LogLevel.Verbose:\r\n console.debug(message);\r\n return;\r\n case LogLevel.Warning:\r\n console.warn(message);\r\n return;\r\n }\r\n },\r\n piiLoggingEnabled: false,\r\n logLevel: LogLevel.Verbose,\r\n },\r\n },\r\n };\r\n };\r\n\r\n /**\r\n * verifies if a string is GUID\r\n * @param guid\r\n */\r\n static isGuid(guid: string): boolean {\r\n const regexGuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\r\n return regexGuid.test(guid);\r\n }\r\n}\r\n","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { LogLevel } from \"@azure/msal-common\"\r\n\r\nexport class Logger {\r\n\r\n /**\r\n * Log an error\r\n * @param {string} log\r\n * @returns {void}\r\n */\r\n static logError(log: string): void {\r\n console.error(this.logMessage(log));\r\n }\r\n\r\n /**\r\n * Log a warning\r\n * @param {string} log\r\n * @returns {void}\r\n */\r\n static logWarning(log: string): void {\r\n console.warn(this.logMessage(log));\r\n }\r\n\r\n /**\r\n * Log anything\r\n * @param {string} log\r\n * @returns {void}\r\n */\r\n static logInfo(log: string): void {\r\n console.info(this.logMessage(log));\r\n }\r\n\r\n /**\r\n * Log message with required options.\r\n * @param {string} logMessage \r\n * @returns {string}\r\n */\r\n private static logMessage(logMessage: string): string {\r\n const timestamp = new Date().toUTCString();\r\n\r\n let logHeader: string = `[${timestamp}]`;\r\n\r\n const log = `${logHeader} : @azure-samples/msal-express-wrapper@0.1.0 : ${LogLevel[LogLevel.Verbose]} - ${logMessage}`;\r\n return log;\r\n }\r\n\r\n}","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport jwt from \"jsonwebtoken\";\r\nimport jwksClient from \"jwks-rsa\";\r\n\r\nimport { \r\n StringUtils, \r\n Constants, \r\n TokenClaims \r\n} from \"@azure/msal-common\";\r\n\r\nimport { Configuration } from \"@azure/msal-node\";\r\n\r\nimport { Logger } from \"./Logger\";\r\n\r\nimport { \r\n AppSettings,\r\n Resource, \r\n IdTokenClaims, \r\n AccessTokenClaims \r\n} from \"./Types\";\r\n\r\nimport { \r\n ErrorMessages, \r\n AADAuthorityConstants \r\n} from \"./Constants\";\r\n\r\nexport class TokenValidator {\r\n private appSettings: AppSettings;\r\n private msalConfig: Configuration;\r\n\r\n /**\r\n * @param {AppSettings} appSettings \r\n * @param {Configuration} msalConfig\r\n * @constructor\r\n */\r\n constructor(appSettings: AppSettings, msalConfig: Configuration) {\r\n this.appSettings = appSettings;\r\n this.msalConfig = msalConfig;\r\n }\r\n\r\n /**\r\n * Verifies a given token's signature using jwks-rsa\r\n * @param {string} authToken \r\n * @returns {Promise}\r\n */\r\n async verifyTokenSignature(authToken: string): Promise {\r\n if (StringUtils.isEmpty(authToken)) {\r\n Logger.logError(ErrorMessages.TOKEN_NOT_FOUND);\r\n return false;\r\n }\r\n\r\n // we will first decode to get kid parameter in header\r\n let decodedToken;\r\n\r\n try {\r\n decodedToken = jwt.decode(authToken, { complete: true });\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.TOKEN_NOT_DECODED);\r\n console.log(error);\r\n return false;\r\n }\r\n\r\n // obtains signing keys from discovery endpoint\r\n let keys;\r\n\r\n try {\r\n keys = await this.getSigningKeys(decodedToken.header, decodedToken.payload.tid);\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.KEYS_NOT_OBTAINED);\r\n console.log(error);\r\n return false;\r\n }\r\n\r\n // verify the signature at header section using keys\r\n let verifiedToken: TokenClaims;\r\n\r\n try {\r\n verifiedToken = jwt.verify(authToken, keys);\r\n\r\n /**\r\n * if a multiplexer was used in place of tenantId i.e. if the app\r\n * is multi-tenant, the tenantId should be obtained from the user\"s\r\n * token\"s tid claim for verification purposes\r\n */\r\n if (\r\n this.appSettings.appCredentials.tenantId === AADAuthorityConstants.COMMON ||\r\n this.appSettings.appCredentials.tenantId === AADAuthorityConstants.ORGANIZATIONS ||\r\n this.appSettings.appCredentials.tenantId === AADAuthorityConstants.CONSUMERS\r\n ) {\r\n this.appSettings.appCredentials.tenantId = decodedToken.payload.tid;\r\n }\r\n\r\n return verifiedToken;\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.TOKEN_NOT_VERIFIED);\r\n console.log(error);\r\n return false;\r\n }\r\n };\r\n\r\n /**\r\n * Verifies the access token for signature\r\n * @param {string} idToken: raw Id token\r\n * @returns {Promise}\r\n */\r\n async validateIdToken(idToken: string): Promise {\r\n try {\r\n const verifiedToken = await this.verifyTokenSignature(idToken);\r\n\r\n if (verifiedToken) {\r\n return this.validateIdTokenClaims(verifiedToken as IdTokenClaims);\r\n } else {\r\n return false;\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n return false;\r\n }\r\n };\r\n\r\n /**\r\n * Validates the id token for a set of claims\r\n * @param {IdTokenClaims} idTokenClaims: decoded id token claims\r\n * @returns {boolean}\r\n */\r\n validateIdTokenClaims(idTokenClaims: IdTokenClaims): boolean {\r\n const now = Math.round(new Date().getTime() / 1000); // in UNIX format\r\n\r\n /**\r\n * At the very least, check for issuer, audience, issue and expiry dates.\r\n * For more information on validating id tokens, visit:\r\n * https://docs.microsoft.com/azure/active-directory/develop/id-tokens#validating-an-id_token\r\n */\r\n const checkIssuer = idTokenClaims.iss.includes(this.appSettings.appCredentials.tenantId) ? true : false;\r\n const checkAudience = idTokenClaims.aud === this.msalConfig.auth.clientId ? true : false;\r\n const checkTimestamp = idTokenClaims.iat <= now && idTokenClaims.exp >= now ? true : false;\r\n\r\n return checkIssuer && checkAudience && checkTimestamp;\r\n };\r\n\r\n /**\r\n * Verifies the access token for signature\r\n * @param {string} accessToken: raw JWT token\r\n * @param {string} protectedRoute: used for checking scope\r\n * @returns {Promise}\r\n */\r\n async verifyAccessTokenSignature(accessToken: string, protectedRoute: string): Promise {\r\n try {\r\n const verifiedToken = await this.verifyTokenSignature(accessToken);\r\n\r\n if (verifiedToken) {\r\n return this.validateAccessTokenClaims(verifiedToken as AccessTokenClaims, protectedRoute);\r\n } else {\r\n return false;\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n return false;\r\n }\r\n };\r\n\r\n /**\r\n * Validates the access token for a set of claims\r\n * @param {TokenClaims} verifiedToken: token with a verified signature\r\n * @param {string} protectedRoute: route where this token is required to access\r\n * @returns {boolean}\r\n */\r\n validateAccessTokenClaims(verifiedToken: AccessTokenClaims, protectedRoute: string): boolean {\r\n const now = Math.round(new Date().getTime() / 1000); // in UNIX format\r\n\r\n /**\r\n * At the very least, validate the token with respect to issuer, audience, scope\r\n * and timestamp, though implementation and extent vary. For more information, visit:\r\n * https://docs.microsoft.com/azure/active-directory/develop/access-tokens#validating-tokens\r\n */\r\n const checkIssuer = verifiedToken.iss.includes(this.appSettings.appCredentials.tenantId) ? true : false;\r\n const checkTimestamp = verifiedToken.iat <= now && verifiedToken.iat >= now ? true : false;\r\n\r\n const checkAudience = verifiedToken.aud === this.appSettings.appCredentials.clientId ||\r\n verifiedToken.aud === \"api://\" + this.appSettings.appCredentials.clientId ? true : false;\r\n\r\n const checkScopes = Object.values(this.appSettings.ownedResources).find((resource: Resource) => resource.endpoint === protectedRoute)\r\n .scopes.every(scp => verifiedToken.scp.includes(scp));\r\n\r\n return checkAudience && checkIssuer && checkTimestamp && checkScopes;\r\n };\r\n\r\n /**\r\n * Fetches signing keys of an access token\r\n * from the authority discovery endpoint\r\n * @param {Object} header: token header\r\n * @param {string} tid: tenant id\r\n * @returns {Promise}\r\n */\r\n private async getSigningKeys(header, tid: string): Promise {\r\n let jwksUri;\r\n\r\n // Check if a B2C application i.e. app has b2cPolicies\r\n if (this.appSettings.b2cPolicies) {\r\n jwksUri = `${this.msalConfig.auth.authority}/discovery/v2.0/keys`;\r\n } else {\r\n jwksUri = `https://${Constants.DEFAULT_AUTHORITY_HOST}/${tid}/discovery/v2.0/keys`;\r\n }\r\n\r\n const client = jwksClient({\r\n jwksUri: jwksUri,\r\n });\r\n\r\n return (await client.getSigningKeyAsync(header.kid)).getPublicKey();\r\n };\r\n}\r\n","import { CertificateClient, KeyVaultCertificate } from \"@azure/keyvault-certificates\";\r\nimport { DefaultAzureCredential } from \"@azure/identity\";\r\nimport { KeyVaultSecret, SecretClient } from \"@azure/keyvault-secrets\";\r\n\r\nimport { AppSettings } from \"./Types\";\r\nimport { KeyVaultCredentialTypes } from \"./Constants\";\r\n\r\nexport class KeyVaultManager {\r\n\r\n /**\r\n * Fetches credentials from Key Vault and updates appSettings\r\n * @param {AppSettings} config \r\n * @returns {Promise}\r\n */\r\n async getCredentialFromKeyVault(config: AppSettings): Promise {\r\n\r\n const credential = new DefaultAzureCredential();\r\n\r\n if (!config.appCredentials.keyVaultCredential) {\r\n return config\r\n }\r\n\r\n switch (config.appCredentials.keyVaultCredential.credentialType) {\r\n case KeyVaultCredentialTypes.SECRET: {\r\n try {\r\n const secretResponse = await this.getSecretCredential(config, credential);\r\n config.appCredentials.clientSecret = secretResponse.value;\r\n return config;\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n break;\r\n }\r\n\r\n case KeyVaultCredentialTypes.CERTIFICATE: {\r\n try {\r\n const certificateResponse = await this.getCertificateCredential(config, credential);\r\n const secretResponse = await this.getSecretCredential(config, credential);\r\n\r\n config.appCredentials.clientCertificate = {\r\n thumbprint: certificateResponse.properties.x509Thumbprint.toString(),\r\n privateKey: secretResponse.value.split('-----BEGIN CERTIFICATE-----\\n')[0]\r\n }\r\n return config;\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n break;\r\n }\r\n\r\n default:\r\n break;\r\n }\r\n };\r\n\r\n /**\r\n * Gets a certificate credential from Key Vault\r\n * @param {AppSettings} config \r\n * @param {DefaultAzureCredential} credential \r\n * @returns {Promise}\r\n */\r\n async getCertificateCredential(config: AppSettings, credential: DefaultAzureCredential): Promise {\r\n\r\n // Initialize secretClient with credentials\r\n const secretClient = new CertificateClient(config.appCredentials.keyVaultCredential.keyVaultUrl, credential);\r\n\r\n try {\r\n const keyVaultCertificate = await secretClient.getCertificate(config.appCredentials.keyVaultCredential.credentialName);\r\n return keyVaultCertificate;\r\n } catch (error) {\r\n console.log(error);\r\n return error;\r\n }\r\n }\r\n\r\n /**\r\n * Gets a secret credential from Key Vault\r\n * @param {AppSettings} config \r\n * @param {DefaultAzureCredential} credential \r\n * @returns {Promise}\r\n */\r\n async getSecretCredential(config: AppSettings, credential: DefaultAzureCredential): Promise {\r\n\r\n // Initialize secretClient with credentials\r\n const secretClient = new SecretClient(config.appCredentials.keyVaultCredential.keyVaultUrl, credential);\r\n\r\n try {\r\n const keyVaultSecret = await secretClient.getSecret(config.appCredentials.keyVaultCredential.credentialName);\r\n return keyVaultSecret;\r\n } catch (error) {\r\n console.log(error);\r\n return error;\r\n }\r\n }\r\n}","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport axios, { AxiosResponse, AxiosRequestConfig } from \"axios\";\r\nimport { StringUtils } from \"@azure/msal-common\";\r\n\r\nimport { \r\n AccessConstants, \r\n InfoMessages, \r\n ErrorMessages \r\n} from \"./Constants\";\r\n\r\nimport { Logger } from \"./Logger\";\r\n\r\nexport class FetchManager {\r\n\r\n /**\r\n * Calls a resource endpoint with a raw access token\r\n * using the authorization bearer token scheme\r\n * @param {string} endpoint \r\n * @param {string} accessToken \r\n * @returns {Promise}\r\n */\r\n static callApiEndpoint = async (endpoint: string, accessToken: string): Promise => {\r\n\r\n if (StringUtils.isEmpty(accessToken)) {\r\n throw new Error(ErrorMessages.TOKEN_NOT_FOUND)\r\n }\r\n\r\n const options: AxiosRequestConfig = {\r\n headers: {\r\n Authorization: `Bearer ${accessToken}`\r\n }\r\n };\r\n\r\n try {\r\n Logger.logInfo(InfoMessages.REQUEST_FOR_RESOURCE);\r\n const response: AxiosResponse = await axios.get(endpoint, options);\r\n return response.data;\r\n } catch (error) {\r\n console.log(error)\r\n return error;\r\n }\r\n }\r\n\r\n /**\r\n * Handles queries against Microsoft Graph that return multiple pages of data \r\n * @param {string} accessToken: access token required by endpoint \r\n * @param {string} nextPage: next page link\r\n * @param {Array} data: stores data from each page\r\n * @returns {Promise}\r\n */\r\n static handlePagination = async (accessToken: string, nextPage: string, data: string[] = []): Promise => {\r\n\r\n try {\r\n const graphResponse = await FetchManager.callApiEndpoint(nextPage, accessToken);\r\n graphResponse[\"value\"].map((v) => data.push(v.id));\r\n \r\n if (graphResponse[AccessConstants.PAGINATION_LINK]) {\r\n return await FetchManager.handlePagination(accessToken, graphResponse[AccessConstants.PAGINATION_LINK], data)\r\n } else {\r\n return data;\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n return error;\r\n }\r\n \r\n }\r\n\r\n}\r\n","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { Request } from \"express\";\r\nimport { IUri, UrlString } from \"@azure/msal-common\";\r\n\r\nexport class UrlUtils {\r\n /**\r\n * Gets the absolute URL from a given request and path string\r\n * @param {Request} req: express request object \r\n * @param {string} url: a given URL\r\n * @returns {string}\r\n */\r\n static ensureAbsoluteUrl = (req: Request, url: string): string => {\r\n const urlComponents: IUri = new UrlString(url).getUrlComponents();\r\n\r\n if (!urlComponents.Protocol) {\r\n if (!urlComponents.HostNameAndPort) {\r\n return req.protocol + \"://\" + req.get(\"host\") + url;\r\n }\r\n return req.protocol + \"://\" + url;\r\n } else {\r\n return url;\r\n }\r\n };\r\n}\r\n","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\nimport express from \"express\";\r\n\r\nimport {\r\n RequestHandler,\r\n Request,\r\n Response,\r\n NextFunction,\r\n Router\r\n} from \"express\";\r\n\r\nimport {\r\n InteractionRequiredAuthError,\r\n OIDC_DEFAULT_SCOPES,\r\n PromptValue,\r\n StringUtils,\r\n} from \"@azure/msal-common\";\r\n\r\nimport {\r\n ConfidentialClientApplication,\r\n Configuration,\r\n AccountInfo,\r\n ICachePlugin,\r\n CryptoProvider,\r\n AuthorizationUrlRequest,\r\n AuthorizationCodeRequest,\r\n SilentFlowRequest,\r\n OnBehalfOfRequest,\r\n} from \"@azure/msal-node\";\r\n\r\nimport { ConfigurationUtils } from \"./ConfigurationUtils\";\r\nimport { TokenValidator } from \"./TokenValidator\";\r\nimport { KeyVaultManager } from \"./KeyVaultManager\";\r\nimport { FetchManager } from \"./FetchManager\";\r\nimport { UrlUtils } from \"./UrlUtils\";\r\nimport { Logger } from \"./Logger\";\r\n\r\nimport {\r\n Resource,\r\n AppSettings,\r\n AuthCodeParams,\r\n InitializationOptions,\r\n TokenRequestOptions,\r\n GuardOptions,\r\n AccessRule,\r\n SignInOptions,\r\n SignOutOptions,\r\n HandleRedirectOptions\r\n} from \"./Types\";\r\n\r\nimport {\r\n AppStages,\r\n ErrorMessages,\r\n AccessConstants,\r\n InfoMessages\r\n} from \"./Constants\";\r\n\r\n/**\r\n * A simple wrapper around MSAL Node ConfidentialClientApplication object.\r\n * It offers a collection of middleware and utility methods that automate\r\n * basic authentication and authorization tasks in Express MVC web apps and\r\n * RESTful APIs (coming soon).\r\n */\r\nexport class AuthProvider {\r\n appSettings: AppSettings;\r\n private msalConfig: Configuration;\r\n private cryptoProvider: CryptoProvider;\r\n private tokenValidator: TokenValidator;\r\n private msalClient: ConfidentialClientApplication;\r\n\r\n /**\r\n * @param {AppSettings} appSettings\r\n * @param {ICachePlugin} cache: cachePlugin\r\n * @constructor\r\n */\r\n constructor(appSettings: AppSettings, cache?: ICachePlugin) {\r\n ConfigurationUtils.validateAppSettings(appSettings);\r\n this.appSettings = appSettings;\r\n\r\n this.msalConfig = ConfigurationUtils.getMsalConfiguration(appSettings, cache);\r\n this.msalClient = new ConfidentialClientApplication(this.msalConfig);\r\n\r\n this.tokenValidator = new TokenValidator(this.appSettings, this.msalConfig);\r\n this.cryptoProvider = new CryptoProvider();\r\n }\r\n\r\n /**\r\n * Asynchronously builds authProvider object with credentials fetched from Key Vault\r\n * @param {AppSettings} appSettings\r\n * @param {ICachePlugin} cache: cachePlugin\r\n * @returns \r\n */\r\n static async buildAsync(appSettings: AppSettings, cache?: ICachePlugin): Promise {\r\n try {\r\n const keyVault = new KeyVaultManager();\r\n const appSettingsWithKeyVaultCredentials = await keyVault.getCredentialFromKeyVault(appSettings);\r\n const authProvider = new AuthProvider(appSettingsWithKeyVaultCredentials, cache);\r\n return authProvider;\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n }\r\n\r\n /**\r\n * Initialize AuthProvider and set default routes and handlers\r\n * @param {InitializationOptions} options\r\n * @returns {Router}\r\n */\r\n initialize = (options?: InitializationOptions): Router => {\r\n\r\n // TODO: initialize app defaults\r\n\r\n const appRouter = express.Router();\r\n\r\n // handle redirect\r\n appRouter.get(this.appSettings.authRoutes.redirect, this.handleRedirect());\r\n\r\n if (this.appSettings.authRoutes.frontChannelLogout) {\r\n /**\r\n * Expose front-channel logout route. For more information, visit: \r\n * https://docs.microsoft.com/azure/active-directory/develop/v2-protocols-oidc#single-sign-out\r\n */\r\n appRouter.get(this.appSettings.authRoutes.frontChannelLogout, (req, res, next) => {\r\n req.session.destroy(() => {\r\n res.sendStatus(200);\r\n });\r\n });\r\n }\r\n\r\n return appRouter;\r\n }\r\n\r\n // ========== ROUTE HANDLERS ===========\r\n\r\n /**\r\n * Initiates sign in flow\r\n * @param {SignInOptions} options: options to modify login request\r\n * @returns {RequestHandler}\r\n */\r\n signIn = (options?: SignInOptions): RequestHandler => {\r\n return (req: Request, res: Response, next: NextFunction): Promise => {\r\n /**\r\n * Request Configuration\r\n * We manipulate these three request objects below\r\n * to acquire a token with the appropriate claims\r\n */\r\n if (!req.session[\"authCodeRequest\"]) {\r\n req.session.authCodeRequest = {\r\n authority: \"\",\r\n scopes: [],\r\n state: {},\r\n redirectUri: \"\",\r\n } as AuthorizationUrlRequest;\r\n }\r\n\r\n if (!req.session[\"tokenRequest\"]) {\r\n req.session.tokenRequest = {\r\n authority: \"\",\r\n scopes: [],\r\n redirectUri: \"\",\r\n code: \"\",\r\n } as AuthorizationCodeRequest;\r\n }\r\n\r\n // signed-in user's account\r\n if (!req.session[\"account\"]) {\r\n req.session.account = {\r\n homeAccountId: \"\",\r\n environment: \"\",\r\n tenantId: \"\",\r\n username: \"\",\r\n idTokenClaims: {},\r\n } as AccountInfo;\r\n }\r\n\r\n // random GUID for csrf protection\r\n req.session.nonce = this.cryptoProvider.createNewGuid();\r\n \r\n // TODO: encrypt state parameter \r\n const state = this.cryptoProvider.base64Encode(\r\n JSON.stringify({\r\n stage: AppStages.SIGN_IN,\r\n path: options.successRedirect,\r\n nonce: req.session.nonce,\r\n })\r\n );\r\n\r\n const params: AuthCodeParams = {\r\n authority: this.msalConfig.auth.authority,\r\n scopes: OIDC_DEFAULT_SCOPES,\r\n state: state,\r\n redirect: UrlUtils.ensureAbsoluteUrl(req, this.appSettings.authRoutes.redirect),\r\n prompt: PromptValue.SELECT_ACCOUNT,\r\n };\r\n\r\n // get url to sign user in\r\n return this.getAuthCode(req, res, next, params);\r\n }\r\n };\r\n\r\n /**\r\n * Initiate sign out and destroy the session\r\n * @param options: options to modify logout request \r\n * @returns {RequestHandler}\r\n */\r\n signOut = (options?: SignOutOptions): RequestHandler => {\r\n return (req: Request, res: Response, next: NextFunction): void => {\r\n const postLogoutRedirectUri = UrlUtils.ensureAbsoluteUrl(req, options.successRedirect);\r\n\r\n /**\r\n * Construct a logout URI and redirect the user to end the\r\n * session with Azure AD/B2C. For more information, visit:\r\n * (AAD) https://docs.microsoft.com/azure/active-directory/develop/v2-protocols-oidc#send-a-sign-out-request\r\n * (B2C) https://docs.microsoft.com/azure/active-directory-b2c/openid-connect#send-a-sign-out-request\r\n */\r\n const logoutURI = `${this.msalConfig.auth.authority}/oauth2/v2.0/logout?post_logout_redirect_uri=${postLogoutRedirectUri}`;\r\n\r\n req.session.isAuthenticated = false;\r\n\r\n req.session.destroy(() => {\r\n res.redirect(logoutURI);\r\n });\r\n }\r\n };\r\n\r\n /**\r\n * Middleware that handles redirect depending on request state\r\n * There are basically 2 stages: sign-in and acquire token\r\n * @param {HandleRedirectOptions} options: options to modify this middleware\r\n * @returns {RequestHandler}\r\n */\r\n private handleRedirect = (options?: HandleRedirectOptions): RequestHandler => {\r\n return async (req: Request, res: Response, next: NextFunction): Promise => {\r\n if (req.query.state) {\r\n const state = JSON.parse(this.cryptoProvider.base64Decode(req.query.state as string));\r\n\r\n // check if nonce matches\r\n if (state.nonce === req.session.nonce) {\r\n switch (state.stage) {\r\n case AppStages.SIGN_IN: {\r\n // token request should have auth code\r\n req.session.tokenRequest.code = req.query.code as string;\r\n\r\n try {\r\n // exchange auth code for tokens\r\n const tokenResponse = await this.msalClient.acquireTokenByCode(req.session.tokenRequest);\r\n\r\n try {\r\n const isIdTokenValid = await this.tokenValidator.validateIdToken(tokenResponse.idToken);\r\n\r\n if (isIdTokenValid) {\r\n // assign session variables\r\n req.session.account = tokenResponse.account;\r\n req.session.isAuthenticated = true;\r\n\r\n res.redirect(state.path);\r\n } else {\r\n Logger.logError(ErrorMessages.INVALID_TOKEN);\r\n res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.CANNOT_VALIDATE_TOKEN);\r\n next(error)\r\n }\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.TOKEN_ACQUISITION_FAILED);\r\n next(error)\r\n }\r\n break;\r\n }\r\n\r\n case AppStages.ACQUIRE_TOKEN: {\r\n // get the name of the resource associated with scope\r\n const resourceName = this.getResourceNameFromScopes(req.session.tokenRequest.scopes);\r\n\r\n req.session.tokenRequest.code = req.query.code as string\r\n\r\n try {\r\n const tokenResponse = await this.msalClient.acquireTokenByCode(req.session.tokenRequest);\r\n req.session.remoteResources[resourceName].accessToken = tokenResponse.accessToken;\r\n res.redirect(state.path);\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.TOKEN_ACQUISITION_FAILED);\r\n next(error);\r\n }\r\n break;\r\n }\r\n\r\n default:\r\n Logger.logError(ErrorMessages.CANNOT_DETERMINE_APP_STAGE);\r\n res.redirect(this.appSettings.authRoutes.error);\r\n break;\r\n }\r\n } else {\r\n Logger.logError(ErrorMessages.NONCE_MISMATCH);\r\n res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n } else {\r\n Logger.logError(ErrorMessages.STATE_NOT_FOUND)\r\n res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n }\r\n };\r\n\r\n // ========== MIDDLEWARE ===========\r\n\r\n /**\r\n * Middleware that gets tokens via acquireToken*\r\n * @param {TokenRequestOptions} options: options to modify this middleware\r\n * @returns {RequestHandler}\r\n */\r\n getToken = (options: TokenRequestOptions): RequestHandler => {\r\n return async (req: Request, res: Response, next: NextFunction): Promise => {\r\n // get scopes for token request\r\n const scopes = options.resource.scopes;\r\n\r\n const resourceName = this.getResourceNameFromScopes(scopes)\r\n\r\n if (!req.session.remoteResources) {\r\n req.session.remoteResources = {};\r\n }\r\n\r\n req.session.remoteResources = {\r\n [resourceName]: {\r\n ...this.appSettings.remoteResources[resourceName],\r\n accessToken: null,\r\n } as Resource\r\n };\r\n\r\n try {\r\n const silentRequest: SilentFlowRequest = {\r\n account: req.session.account,\r\n scopes: scopes,\r\n };\r\n\r\n // acquire token silently to be used in resource call\r\n const tokenResponse = await this.msalClient.acquireTokenSilent(silentRequest);\r\n\r\n // In B2C scenarios, sometimes an access token is returned empty.\r\n // In that case, we will acquire token interactively instead.\r\n if (StringUtils.isEmpty(tokenResponse.accessToken)) {\r\n Logger.logError(ErrorMessages.TOKEN_NOT_FOUND);\r\n throw new InteractionRequiredAuthError(ErrorMessages.INTERACTION_REQUIRED);\r\n }\r\n\r\n req.session.remoteResources[resourceName].accessToken = tokenResponse.accessToken;\r\n next();\r\n } catch (error) {\r\n // in case there are no cached tokens, initiate an interactive call\r\n if (error instanceof InteractionRequiredAuthError) {\r\n const state = this.cryptoProvider.base64Encode(\r\n JSON.stringify({\r\n stage: AppStages.ACQUIRE_TOKEN,\r\n path: req.originalUrl,\r\n nonce: req.session.nonce,\r\n })\r\n );\r\n\r\n const params: AuthCodeParams = {\r\n authority: this.msalConfig.auth.authority,\r\n scopes: scopes,\r\n state: state,\r\n redirect: UrlUtils.ensureAbsoluteUrl(req, this.appSettings.authRoutes.redirect),\r\n account: req.session.account,\r\n };\r\n\r\n // initiate the first leg of auth code grant to get token\r\n return this.getAuthCode(req, res, next, params);\r\n } else {\r\n next(error);\r\n }\r\n }\r\n }\r\n };\r\n\r\n /**\r\n * Middleware that gets tokens via OBO flow. Used in web API scenarios\r\n * @param {TokenRequestOptions} options: options to modify this middleware\r\n * @returns {RequestHandler}\r\n */\r\n getTokenOnBehalf = (options: TokenRequestOptions): RequestHandler => {\r\n return async (req: Request, res: Response, next: NextFunction): Promise => {\r\n const authHeader = req.headers.authorization;\r\n\r\n // get scopes for token request\r\n const scopes = options.resource.scopes;\r\n const resourceName = this.getResourceNameFromScopes(scopes);\r\n\r\n const oboRequest: OnBehalfOfRequest = {\r\n oboAssertion: authHeader.split(\" \")[1],\r\n scopes: scopes,\r\n }\r\n\r\n try {\r\n const tokenResponse = await this.msalClient.acquireTokenOnBehalfOf(oboRequest);\r\n\r\n // as OBO is commonly used in middle-tier web APIs without sessions, attach AT to req\r\n req[\"locals\"] = {\r\n [resourceName]: {\r\n accessToken: tokenResponse.accessToken\r\n }\r\n }\r\n\r\n next();\r\n } catch (error) {\r\n next(error);\r\n }\r\n }\r\n }\r\n\r\n // ============== GUARDS ===============\r\n\r\n /**\r\n * Check if authenticated in session\r\n * @param {GuardOptions} options: options to modify this middleware\r\n * @returns {RequestHandler}\r\n */\r\n isAuthenticated = (options?: GuardOptions): RequestHandler => {\r\n return (req: Request, res: Response, next: NextFunction): void => {\r\n if (req.session) {\r\n if (!req.session.isAuthenticated) {\r\n Logger.logError(ErrorMessages.NOT_PERMITTED);\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n\r\n next();\r\n } else {\r\n Logger.logError(ErrorMessages.SESSION_NOT_FOUND);\r\n res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n }\r\n };\r\n\r\n /**\r\n * Receives access token in req authorization header\r\n * and validates it using the jwt.verify\r\n * @param {GuardOptions} options: options to modify this middleware\r\n * @returns {RequestHandler}\r\n */\r\n isAuthorized = (options?: GuardOptions): RequestHandler => {\r\n return async (req: Request, res: Response, next: NextFunction): Promise => {\r\n const accessToken = req.headers.authorization.split(\" \")[1];\r\n\r\n if (req.headers.authorization) {\r\n if (!(await this.tokenValidator.verifyAccessTokenSignature(accessToken, `${req.baseUrl}${req.path}`))) {\r\n Logger.logError(ErrorMessages.INVALID_TOKEN);\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n\r\n next();\r\n } else {\r\n Logger.logError(ErrorMessages.TOKEN_NOT_FOUND);\r\n res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n }\r\n };\r\n\r\n /**\r\n * Checks if the user has access for this route, defined in access matrix\r\n * @param {GuardOptions} options: options to modify this middleware\r\n * @returns {RequestHandler}\r\n */\r\n hasAccess = (options?: GuardOptions): RequestHandler => {\r\n return async (req: Request, res: Response, next: NextFunction): Promise => {\r\n if (req.session && this.appSettings.accessMatrix) {\r\n\r\n const checkFor = options.accessRule.hasOwnProperty(AccessConstants.GROUPS) ? AccessConstants.GROUPS : AccessConstants.ROLES;\r\n\r\n switch (checkFor) {\r\n case AccessConstants.GROUPS:\r\n\r\n if (req.session.account.idTokenClaims[AccessConstants.GROUPS] === undefined) {\r\n if (req.session.account.idTokenClaims[AccessConstants.CLAIM_NAMES] || req.session.account.idTokenClaims[AccessConstants.CLAIM_SOURCES]) {\r\n Logger.logWarning(InfoMessages.OVERAGE_OCCURRED)\r\n return await this.handleOverage(req, res, next, options.accessRule);\r\n } else {\r\n Logger.logError(ErrorMessages.USER_HAS_NO_GROUP);\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n } else {\r\n const groups = req.session.account.idTokenClaims[AccessConstants.GROUPS];\r\n\r\n if (!this.checkAccessRule(req.method, options.accessRule, groups, AccessConstants.GROUPS)) {\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n }\r\n\r\n next();\r\n break;\r\n\r\n case AccessConstants.ROLES:\r\n if (req.session.account.idTokenClaims[AccessConstants.ROLES] === undefined) {\r\n Logger.logError(ErrorMessages.USER_HAS_NO_ROLE);\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n } else {\r\n const roles = req.session.account.idTokenClaims[AccessConstants.ROLES];\r\n\r\n if (!this.checkAccessRule(req.method, options.accessRule, roles, AccessConstants.ROLES)) {\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n }\r\n\r\n next();\r\n break;\r\n\r\n default:\r\n break;\r\n }\r\n } else {\r\n res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n }\r\n }\r\n\r\n // ============== UTILS ===============\r\n\r\n /**\r\n * This method is used to generate an auth code url request\r\n * @param {Request} req: express request object\r\n * @param {Response} res: express response object\r\n * @param {NextFunction} next: express next function\r\n * @param {AuthCodeParams} params: modifies auth code url request\r\n * @returns {Promise}\r\n */\r\n private async getAuthCode(req: Request, res: Response, next: NextFunction, params: AuthCodeParams): Promise {\r\n // prepare the request\r\n req.session.authCodeRequest.authority = params.authority;\r\n req.session.authCodeRequest.scopes = params.scopes;\r\n req.session.authCodeRequest.state = params.state;\r\n req.session.authCodeRequest.redirectUri = params.redirect;\r\n req.session.authCodeRequest.prompt = params.prompt;\r\n req.session.authCodeRequest.account = params.account;\r\n\r\n req.session.tokenRequest.authority = params.authority;\r\n req.session.tokenRequest.scopes = params.scopes;\r\n req.session.tokenRequest.redirectUri = params.redirect;\r\n\r\n // request an authorization code to exchange for tokens\r\n try {\r\n const response = await this.msalClient.getAuthCodeUrl(req.session.authCodeRequest);\r\n res.redirect(response);\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.AUTH_CODE_NOT_OBTAINED);\r\n next(error);\r\n }\r\n };\r\n\r\n /**\r\n * Handles group overage claims by querying MS Graph /memberOf endpoint\r\n * @param {Request} req: express request object\r\n * @param {Response} res: express response object\r\n * @param {NextFunction} next: express next function\r\n * @param {AccessRule} rule: a given access rule\r\n * @returns {Promise}\r\n */\r\n private async handleOverage(req: Request, res: Response, next: NextFunction, rule: AccessRule): Promise {\r\n const { _claim_names, _claim_sources, ...newIdTokenClaims } = req.session.account.idTokenClaims;\r\n\r\n const silentRequest: SilentFlowRequest = {\r\n account: req.session.account,\r\n scopes: AccessConstants.GRAPH_MEMBER_SCOPES.split(\" \"),\r\n };\r\n\r\n try {\r\n // acquire token silently to be used in resource call\r\n const tokenResponse = await this.msalClient.acquireTokenSilent(silentRequest);\r\n try {\r\n const graphResponse = await FetchManager.callApiEndpoint(AccessConstants.GRAPH_MEMBERS_ENDPOINT, tokenResponse.accessToken);\r\n\r\n /**\r\n * Some queries against Microsoft Graph return multiple pages of data either due to server-side paging \r\n * or due to the use of the $top query parameter to specifically limit the page size in a request. \r\n * When a result set spans multiple pages, Microsoft Graph returns an @odata.nextLink property in \r\n * the response that contains a URL to the next page of results. Learn more at https://docs.microsoft.com/graph/paging\r\n */\r\n if (graphResponse[AccessConstants.PAGINATION_LINK]) {\r\n try {\r\n const userGroups = await FetchManager.handlePagination(tokenResponse.accessToken, graphResponse[AccessConstants.PAGINATION_LINK]);\r\n\r\n req.session.account.idTokenClaims = {\r\n ...newIdTokenClaims,\r\n groups: userGroups\r\n }\r\n\r\n if (!this.checkAccessRule(req.method, rule, req.session.account.idTokenClaims[AccessConstants.GROUPS], AccessConstants.GROUPS)) {\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n } else {\r\n return next();\r\n }\r\n } catch (error) {\r\n next(error);\r\n }\r\n } else {\r\n req.session.account.idTokenClaims = {\r\n ...newIdTokenClaims,\r\n groups: graphResponse[\"value\"].map((v) => v.id)\r\n }\r\n\r\n if (!this.checkAccessRule(req.method, rule, req.session.account.idTokenClaims[AccessConstants.GROUPS], AccessConstants.GROUPS)) {\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n } else {\r\n return next();\r\n }\r\n }\r\n } catch (error) {\r\n next(error);\r\n }\r\n } catch (error) {\r\n next(error);\r\n }\r\n }\r\n\r\n /**\r\n * Checks if the request passes a given access rule\r\n * @param {string} method: HTTP method for this route\r\n * @param {AccessRule} rule: access rule for this route\r\n * @param {Array} creds: user's credentials i.e. roles or groups\r\n * @param {string} credType: roles or groups\r\n * @returns {boolean}\r\n */\r\n private checkAccessRule(method: string, rule: AccessRule, creds: string[], credType: string): boolean {\r\n if (rule.methods.includes(method)) {\r\n switch (credType) {\r\n case AccessConstants.GROUPS:\r\n if (rule.groups.filter(elem => creds.includes(elem)).length < 1) {\r\n Logger.logError(ErrorMessages.USER_NOT_IN_GROUP);\r\n return false;\r\n }\r\n break;\r\n\r\n case AccessConstants.ROLES:\r\n if (rule.roles.filter(elem => creds.includes(elem)).length < 1) {\r\n Logger.logError(ErrorMessages.USER_NOT_IN_ROLE);\r\n return false;\r\n }\r\n break;\r\n\r\n default:\r\n break;\r\n }\r\n } else {\r\n Logger.logError(ErrorMessages.METHOD_NOT_ALLOWED);\r\n return false;\r\n }\r\n\r\n return true;\r\n }\r\n\r\n /**\r\n * Util method to get the resource name for a given scope(s)\r\n * @param {Array} scopes: an array of scopes that the resource is associated with\r\n * @returns {string}\r\n */\r\n private getResourceNameFromScopes(scopes: string[]): string {\r\n // TODO: deep check equality here \r\n\r\n const index = Object.values({ ...this.appSettings.remoteResources, ...this.appSettings.ownedResources })\r\n .findIndex((resource: Resource) => JSON.stringify(resource.scopes) === JSON.stringify(scopes));\r\n\r\n const resourceName = Object.keys({ ...this.appSettings.remoteResources, ...this.appSettings.ownedResources })[index];\r\n return resourceName;\r\n };\r\n}\r\n"],"names":["runtime","exports","Op","Object","prototype","hasOwn","hasOwnProperty","$Symbol","Symbol","iteratorSymbol","iterator","asyncIteratorSymbol","asyncIterator","toStringTagSymbol","toStringTag","define","obj","key","value","defineProperty","enumerable","configurable","writable","err","wrap","innerFn","outerFn","self","tryLocsList","generator","create","Generator","context","Context","_invoke","state","method","arg","Error","undefined","done","delegate","delegateResult","maybeInvokeDelegate","ContinueSentinel","sent","_sent","dispatchException","abrupt","record","tryCatch","type","makeInvokeMethod","fn","call","GeneratorFunction","GeneratorFunctionPrototype","IteratorPrototype","this","getProto","getPrototypeOf","NativeIteratorPrototype","values","Gp","defineIteratorMethods","forEach","AsyncIterator","PromiseImpl","previousPromise","callInvokeWithMethodAndArg","resolve","reject","invoke","result","__await","then","unwrapped","error","TypeError","info","resultName","next","nextLoc","pushTryEntry","locs","entry","tryLoc","catchLoc","finallyLoc","afterLoc","tryEntries","push","resetTryEntry","completion","reset","iterable","iteratorMethod","isNaN","length","i","doneResult","constructor","displayName","isGeneratorFunction","genFun","ctor","name","mark","setPrototypeOf","__proto__","awrap","async","Promise","iter","toString","keys","object","reverse","pop","skipTempReset","prev","charAt","slice","stop","rootRecord","rval","exception","handle","loc","caught","hasCatch","hasFinally","finallyEntry","complete","finish","catch","thrown","delegateYield","module","regeneratorRuntime","accidentalStrictMode","Function","AppStages","SIGN_IN","SIGN_OUT","ACQUIRE_TOKEN","AADAuthorityConstants","COMMON","ORGANIZATIONS","CONSUMERS","KeyVaultCredentialTypes","SECRET","CERTIFICATE","AccessConstants","GROUPS","ROLES","CLAIM_NAMES","CLAIM_SOURCES","PAGINATION_LINK","GRAPH_MEMBERS_ENDPOINT","GRAPH_MEMBER_SCOPES","InfoMessages","REQUEST_FOR_RESOURCE","OVERAGE_OCCURRED","ErrorMessages","NOT_PERMITTED","INVALID_TOKEN","CANNOT_DETERMINE_APP_STAGE","CANNOT_VALIDATE_TOKEN","NONCE_MISMATCH","INTERACTION_REQUIRED","TOKEN_ACQUISITION_FAILED","AUTH_CODE_NOT_OBTAINED","TOKEN_NOT_FOUND","TOKEN_NOT_DECODED","TOKEN_NOT_VERIFIED","KEYS_NOT_OBTAINED","STATE_NOT_FOUND","USER_HAS_NO_ROLE","USER_NOT_IN_ROLE","USER_HAS_NO_GROUP","USER_NOT_IN_GROUP","METHOD_NOT_ALLOWED","RULE_NOT_FOUND","SESSION_NOT_FOUND","KEY_VAULT_CONFIG_NOT_FOUND","ConfigurationErrorMessages","NO_CLIENT_ID","INVALID_CLIENT_ID","NO_TENANT_INFO","INVALID_TENANT_INFO","NO_CLIENT_CREDENTIAL","NO_REDIRECT_URI","NO_ERROR_ROUTE","NO_UNAUTHORIZED_ROUTE","ConfigurationUtils","validateAppSettings","config","StringUtils","isEmpty","appCredentials","clientId","isGuid","tenantId","includes","clientSecret","clientCertificate","authRoutes","redirect","unauthorized","getMsalConfiguration","cachePlugin","auth","authority","b2cPolicies","entries","Constants","DEFAULT_AUTHORITY_HOST","knownAuthorities","UrlString","getDomainFromUrl","cache","system","loggerOptions","loggerCallback","logLevel","message","containsPii","LogLevel","console","Info","Verbose","debug","Warning","warn","piiLoggingEnabled","guid","test","Logger","logError","log","logMessage","logWarning","logInfo","Date","toUTCString","logHeader","TokenValidator","appSettings","msalConfig","verifyTokenSignature","authToken","decodedToken","jwt","decode","getSigningKeys","header","payload","tid","verifiedToken","verify","validateIdToken","idToken","validateIdTokenClaims","idTokenClaims","now","Math","round","getTime","iss","aud","iat","exp","verifyAccessTokenSignature","accessToken","protectedRoute","validateAccessTokenClaims","checkIssuer","checkTimestamp","checkAudience","checkScopes","ownedResources","find","resource","endpoint","scopes","every","scp","client","jwksClient","jwksUri","getSigningKeyAsync","kid","getPublicKey","KeyVaultManager","getCredentialFromKeyVault","credential","DefaultAzureCredential","keyVaultCredential","credentialType","getSecretCredential","getCertificateCredential","certificateResponse","secretResponse","thumbprint","properties","x509Thumbprint","privateKey","split","secretClient","CertificateClient","keyVaultUrl","getCertificate","credentialName","SecretClient","getSecret","FetchManager","options","headers","Authorization","axios","get","data","nextPage","callApiEndpoint","graphResponse","map","v","id","handlePagination","UrlUtils","req","url","urlComponents","getUrlComponents","Protocol","HostNameAndPort","protocol","AuthProvider","appRouter","express","Router","_this","handleRedirect","frontChannelLogout","res","session","destroy","sendStatus","authCodeRequest","redirectUri","tokenRequest","code","account","homeAccountId","environment","username","nonce","cryptoProvider","createNewGuid","base64Encode","JSON","stringify","stage","path","successRedirect","params","OIDC_DEFAULT_SCOPES","ensureAbsoluteUrl","prompt","PromptValue","SELECT_ACCOUNT","getAuthCode","postLogoutRedirectUri","logoutURI","isAuthenticated","query","parse","base64Decode","msalClient","acquireTokenByCode","tokenResponse","tokenValidator","resourceName","getResourceNameFromScopes","remoteResources","silentRequest","acquireTokenSilent","InteractionRequiredAuthError","_context2","originalUrl","authHeader","authorization","oboRequest","oboAssertion","acquireTokenOnBehalfOf","baseUrl","accessMatrix","checkFor","accessRule","handleOverage","checkAccessRule","ConfidentialClientApplication","CryptoProvider","buildAsync","keyVault","authProvider","getAuthCodeUrl","rule","_claim_names","newIdTokenClaims","groups","creds","credType","methods","filter","elem","roles","index","findIndex"],"mappings":"gkCAOA,IAA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EAAOC,SAAS3E,EAAce,mBACvB,SAYhB,KAQH6M,0BAAA,SAA0BnG,OAGxBqI,EAAQ/Z,OAAO2D,YAAYJ,KAAK8L,YAAYyI,gBAAoBvU,KAAK8L,YAAYiC,iBAClF0I,WAAU,SAACxI,UAAuB8E,KAAKC,UAAU/E,EAASE,UAAY4E,KAAKC,UAAU7E,aAErE1R,OAAOgH,UAAUzD,KAAK8L,YAAYyI,gBAAoBvU,KAAK8L,YAAYiC,iBAAkByI,mMP3jB5F,OACf"} \ No newline at end of file +{"version":3,"file":"msal-express-wrapper.cjs.production.min.js","sources":["../node_modules/regenerator-runtime/runtime.js","../src/Constants.ts","../src/ConfigurationUtils.ts","../src/Logger.ts","../src/TokenValidator.ts","../src/KeyVaultManager.ts","../src/FetchManager.ts","../src/UrlUtils.ts","../src/AuthProvider.ts"],"sourcesContent":["/**\n * Copyright (c) 2014-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nvar runtime = (function (exports) {\n \"use strict\";\n\n var Op = Object.prototype;\n var hasOwn = Op.hasOwnProperty;\n var undefined; // More compressible than void 0.\n var $Symbol = typeof Symbol === \"function\" ? Symbol : {};\n var iteratorSymbol = $Symbol.iterator || \"@@iterator\";\n var asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\";\n var toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n\n function define(obj, key, value) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n return obj[key];\n }\n try {\n // IE 8 has a broken Object.defineProperty that only works on DOM objects.\n define({}, \"\");\n } catch (err) {\n define = function(obj, key, value) {\n return obj[key] = value;\n };\n }\n\n function wrap(innerFn, outerFn, self, tryLocsList) {\n // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.\n var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;\n var generator = Object.create(protoGenerator.prototype);\n var context = new Context(tryLocsList || []);\n\n // The ._invoke method unifies the implementations of the .next,\n // .throw, and .return methods.\n generator._invoke = makeInvokeMethod(innerFn, self, context);\n\n return generator;\n }\n exports.wrap = wrap;\n\n // Try/catch helper to minimize deoptimizations. Returns a completion\n // record like context.tryEntries[i].completion. This interface could\n // have been (and was previously) designed to take a closure to be\n // invoked without arguments, but in all the cases we care about we\n // already have an existing method we want to call, so there's no need\n // to create a new function object. We can even get away with assuming\n // the method takes exactly one argument, since that happens to be true\n // in every case, so we don't have to touch the arguments object. The\n // only additional allocation required is the completion record, which\n // has a stable shape and so hopefully should be cheap to allocate.\n function tryCatch(fn, obj, arg) {\n try {\n return { type: \"normal\", arg: fn.call(obj, arg) };\n } catch (err) {\n return { type: \"throw\", arg: err };\n }\n }\n\n var GenStateSuspendedStart = \"suspendedStart\";\n var GenStateSuspendedYield = \"suspendedYield\";\n var GenStateExecuting = \"executing\";\n var GenStateCompleted = \"completed\";\n\n // Returning this object from the innerFn has the same effect as\n // breaking out of the dispatch switch statement.\n var ContinueSentinel = {};\n\n // Dummy constructor functions that we use as the .constructor and\n // .constructor.prototype properties for functions that return Generator\n // objects. For full spec compliance, you may wish to configure your\n // minifier not to mangle the names of these two functions.\n function Generator() {}\n function GeneratorFunction() {}\n function GeneratorFunctionPrototype() {}\n\n // This is a polyfill for %IteratorPrototype% for environments that\n // don't natively support it.\n var IteratorPrototype = {};\n IteratorPrototype[iteratorSymbol] = function () {\n return this;\n };\n\n var getProto = Object.getPrototypeOf;\n var NativeIteratorPrototype = getProto && getProto(getProto(values([])));\n if (NativeIteratorPrototype &&\n NativeIteratorPrototype !== Op &&\n hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {\n // This environment has a native %IteratorPrototype%; use it instead\n // of the polyfill.\n IteratorPrototype = NativeIteratorPrototype;\n }\n\n var Gp = GeneratorFunctionPrototype.prototype =\n Generator.prototype = Object.create(IteratorPrototype);\n GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;\n GeneratorFunctionPrototype.constructor = GeneratorFunction;\n GeneratorFunction.displayName = define(\n GeneratorFunctionPrototype,\n toStringTagSymbol,\n \"GeneratorFunction\"\n );\n\n // Helper for defining the .next, .throw, and .return methods of the\n // Iterator interface in terms of a single ._invoke method.\n function defineIteratorMethods(prototype) {\n [\"next\", \"throw\", \"return\"].forEach(function(method) {\n define(prototype, method, function(arg) {\n return this._invoke(method, arg);\n });\n });\n }\n\n exports.isGeneratorFunction = function(genFun) {\n var ctor = typeof genFun === \"function\" && genFun.constructor;\n return ctor\n ? ctor === GeneratorFunction ||\n // For the native GeneratorFunction constructor, the best we can\n // do is to check its .name property.\n (ctor.displayName || ctor.name) === \"GeneratorFunction\"\n : false;\n };\n\n exports.mark = function(genFun) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);\n } else {\n genFun.__proto__ = GeneratorFunctionPrototype;\n define(genFun, toStringTagSymbol, \"GeneratorFunction\");\n }\n genFun.prototype = Object.create(Gp);\n return genFun;\n };\n\n // Within the body of any async function, `await x` is transformed to\n // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test\n // `hasOwn.call(value, \"__await\")` to determine if the yielded value is\n // meant to be awaited.\n exports.awrap = function(arg) {\n return { __await: arg };\n };\n\n function AsyncIterator(generator, PromiseImpl) {\n function invoke(method, arg, resolve, reject) {\n var record = tryCatch(generator[method], generator, arg);\n if (record.type === \"throw\") {\n reject(record.arg);\n } else {\n var result = record.arg;\n var value = result.value;\n if (value &&\n typeof value === \"object\" &&\n hasOwn.call(value, \"__await\")) {\n return PromiseImpl.resolve(value.__await).then(function(value) {\n invoke(\"next\", value, resolve, reject);\n }, function(err) {\n invoke(\"throw\", err, resolve, reject);\n });\n }\n\n return PromiseImpl.resolve(value).then(function(unwrapped) {\n // When a yielded Promise is resolved, its final value becomes\n // the .value of the Promise<{value,done}> result for the\n // current iteration.\n result.value = unwrapped;\n resolve(result);\n }, function(error) {\n // If a rejected Promise was yielded, throw the rejection back\n // into the async generator function so it can be handled there.\n return invoke(\"throw\", error, resolve, reject);\n });\n }\n }\n\n var previousPromise;\n\n function enqueue(method, arg) {\n function callInvokeWithMethodAndArg() {\n return new PromiseImpl(function(resolve, reject) {\n invoke(method, arg, resolve, reject);\n });\n }\n\n return previousPromise =\n // If enqueue has been called before, then we want to wait until\n // all previous Promises have been resolved before calling invoke,\n // so that results are always delivered in the correct order. If\n // enqueue has not been called before, then it is important to\n // call invoke immediately, without waiting on a callback to fire,\n // so that the async generator function has the opportunity to do\n // any necessary setup in a predictable way. This predictability\n // is why the Promise constructor synchronously invokes its\n // executor callback, and why async functions synchronously\n // execute code before the first await. Since we implement simple\n // async functions in terms of async generators, it is especially\n // important to get this right, even though it requires care.\n previousPromise ? previousPromise.then(\n callInvokeWithMethodAndArg,\n // Avoid propagating failures to Promises returned by later\n // invocations of the iterator.\n callInvokeWithMethodAndArg\n ) : callInvokeWithMethodAndArg();\n }\n\n // Define the unified helper method that is used to implement .next,\n // .throw, and .return (see defineIteratorMethods).\n this._invoke = enqueue;\n }\n\n defineIteratorMethods(AsyncIterator.prototype);\n AsyncIterator.prototype[asyncIteratorSymbol] = function () {\n return this;\n };\n exports.AsyncIterator = AsyncIterator;\n\n // Note that simple async functions are implemented on top of\n // AsyncIterator objects; they just return a Promise for the value of\n // the final result produced by the iterator.\n exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {\n if (PromiseImpl === void 0) PromiseImpl = Promise;\n\n var iter = new AsyncIterator(\n wrap(innerFn, outerFn, self, tryLocsList),\n PromiseImpl\n );\n\n return exports.isGeneratorFunction(outerFn)\n ? iter // If outerFn is a generator, return the full iterator.\n : iter.next().then(function(result) {\n return result.done ? result.value : iter.next();\n });\n };\n\n function makeInvokeMethod(innerFn, self, context) {\n var state = GenStateSuspendedStart;\n\n return function invoke(method, arg) {\n if (state === GenStateExecuting) {\n throw new Error(\"Generator is already running\");\n }\n\n if (state === GenStateCompleted) {\n if (method === \"throw\") {\n throw arg;\n }\n\n // Be forgiving, per 25.3.3.3.3 of the spec:\n // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume\n return doneResult();\n }\n\n context.method = method;\n context.arg = arg;\n\n while (true) {\n var delegate = context.delegate;\n if (delegate) {\n var delegateResult = maybeInvokeDelegate(delegate, context);\n if (delegateResult) {\n if (delegateResult === ContinueSentinel) continue;\n return delegateResult;\n }\n }\n\n if (context.method === \"next\") {\n // Setting context._sent for legacy support of Babel's\n // function.sent implementation.\n context.sent = context._sent = context.arg;\n\n } else if (context.method === \"throw\") {\n if (state === GenStateSuspendedStart) {\n state = GenStateCompleted;\n throw context.arg;\n }\n\n context.dispatchException(context.arg);\n\n } else if (context.method === \"return\") {\n context.abrupt(\"return\", context.arg);\n }\n\n state = GenStateExecuting;\n\n var record = tryCatch(innerFn, self, context);\n if (record.type === \"normal\") {\n // If an exception is thrown from innerFn, we leave state ===\n // GenStateExecuting and loop back for another invocation.\n state = context.done\n ? GenStateCompleted\n : GenStateSuspendedYield;\n\n if (record.arg === ContinueSentinel) {\n continue;\n }\n\n return {\n value: record.arg,\n done: context.done\n };\n\n } else if (record.type === \"throw\") {\n state = GenStateCompleted;\n // Dispatch the exception by looping back around to the\n // context.dispatchException(context.arg) call above.\n context.method = \"throw\";\n context.arg = record.arg;\n }\n }\n };\n }\n\n // Call delegate.iterator[context.method](context.arg) and handle the\n // result, either by returning a { value, done } result from the\n // delegate iterator, or by modifying context.method and context.arg,\n // setting context.delegate to null, and returning the ContinueSentinel.\n function maybeInvokeDelegate(delegate, context) {\n var method = delegate.iterator[context.method];\n if (method === undefined) {\n // A .throw or .return when the delegate iterator has no .throw\n // method always terminates the yield* loop.\n context.delegate = null;\n\n if (context.method === \"throw\") {\n // Note: [\"return\"] must be used for ES3 parsing compatibility.\n if (delegate.iterator[\"return\"]) {\n // If the delegate iterator has a return method, give it a\n // chance to clean up.\n context.method = \"return\";\n context.arg = undefined;\n maybeInvokeDelegate(delegate, context);\n\n if (context.method === \"throw\") {\n // If maybeInvokeDelegate(context) changed context.method from\n // \"return\" to \"throw\", let that override the TypeError below.\n return ContinueSentinel;\n }\n }\n\n context.method = \"throw\";\n context.arg = new TypeError(\n \"The iterator does not provide a 'throw' method\");\n }\n\n return ContinueSentinel;\n }\n\n var record = tryCatch(method, delegate.iterator, context.arg);\n\n if (record.type === \"throw\") {\n context.method = \"throw\";\n context.arg = record.arg;\n context.delegate = null;\n return ContinueSentinel;\n }\n\n var info = record.arg;\n\n if (! info) {\n context.method = \"throw\";\n context.arg = new TypeError(\"iterator result is not an object\");\n context.delegate = null;\n return ContinueSentinel;\n }\n\n if (info.done) {\n // Assign the result of the finished delegate to the temporary\n // variable specified by delegate.resultName (see delegateYield).\n context[delegate.resultName] = info.value;\n\n // Resume execution at the desired location (see delegateYield).\n context.next = delegate.nextLoc;\n\n // If context.method was \"throw\" but the delegate handled the\n // exception, let the outer generator proceed normally. If\n // context.method was \"next\", forget context.arg since it has been\n // \"consumed\" by the delegate iterator. If context.method was\n // \"return\", allow the original .return call to continue in the\n // outer generator.\n if (context.method !== \"return\") {\n context.method = \"next\";\n context.arg = undefined;\n }\n\n } else {\n // Re-yield the result returned by the delegate method.\n return info;\n }\n\n // The delegate iterator is finished, so forget it and continue with\n // the outer generator.\n context.delegate = null;\n return ContinueSentinel;\n }\n\n // Define Generator.prototype.{next,throw,return} in terms of the\n // unified ._invoke helper method.\n defineIteratorMethods(Gp);\n\n define(Gp, toStringTagSymbol, \"Generator\");\n\n // A Generator should always return itself as the iterator object when the\n // @@iterator function is called on it. Some browsers' implementations of the\n // iterator prototype chain incorrectly implement this, causing the Generator\n // object to not be returned from this call. This ensures that doesn't happen.\n // See https://github.com/facebook/regenerator/issues/274 for more details.\n Gp[iteratorSymbol] = function() {\n return this;\n };\n\n Gp.toString = function() {\n return \"[object Generator]\";\n };\n\n function pushTryEntry(locs) {\n var entry = { tryLoc: locs[0] };\n\n if (1 in locs) {\n entry.catchLoc = locs[1];\n }\n\n if (2 in locs) {\n entry.finallyLoc = locs[2];\n entry.afterLoc = locs[3];\n }\n\n this.tryEntries.push(entry);\n }\n\n function resetTryEntry(entry) {\n var record = entry.completion || {};\n record.type = \"normal\";\n delete record.arg;\n entry.completion = record;\n }\n\n function Context(tryLocsList) {\n // The root entry object (effectively a try statement without a catch\n // or a finally block) gives us a place to store values thrown from\n // locations where there is no enclosing try statement.\n this.tryEntries = [{ tryLoc: \"root\" }];\n tryLocsList.forEach(pushTryEntry, this);\n this.reset(true);\n }\n\n exports.keys = function(object) {\n var keys = [];\n for (var key in object) {\n keys.push(key);\n }\n keys.reverse();\n\n // Rather than returning an object with a next method, we keep\n // things simple and return the next function itself.\n return function next() {\n while (keys.length) {\n var key = keys.pop();\n if (key in object) {\n next.value = key;\n next.done = false;\n return next;\n }\n }\n\n // To avoid creating an additional object, we just hang the .value\n // and .done properties off the next function object itself. This\n // also ensures that the minifier will not anonymize the function.\n next.done = true;\n return next;\n };\n };\n\n function values(iterable) {\n if (iterable) {\n var iteratorMethod = iterable[iteratorSymbol];\n if (iteratorMethod) {\n return iteratorMethod.call(iterable);\n }\n\n if (typeof iterable.next === \"function\") {\n return iterable;\n }\n\n if (!isNaN(iterable.length)) {\n var i = -1, next = function next() {\n while (++i < iterable.length) {\n if (hasOwn.call(iterable, i)) {\n next.value = iterable[i];\n next.done = false;\n return next;\n }\n }\n\n next.value = undefined;\n next.done = true;\n\n return next;\n };\n\n return next.next = next;\n }\n }\n\n // Return an iterator with no values.\n return { next: doneResult };\n }\n exports.values = values;\n\n function doneResult() {\n return { value: undefined, done: true };\n }\n\n Context.prototype = {\n constructor: Context,\n\n reset: function(skipTempReset) {\n this.prev = 0;\n this.next = 0;\n // Resetting context._sent for legacy support of Babel's\n // function.sent implementation.\n this.sent = this._sent = undefined;\n this.done = false;\n this.delegate = null;\n\n this.method = \"next\";\n this.arg = undefined;\n\n this.tryEntries.forEach(resetTryEntry);\n\n if (!skipTempReset) {\n for (var name in this) {\n // Not sure about the optimal order of these conditions:\n if (name.charAt(0) === \"t\" &&\n hasOwn.call(this, name) &&\n !isNaN(+name.slice(1))) {\n this[name] = undefined;\n }\n }\n }\n },\n\n stop: function() {\n this.done = true;\n\n var rootEntry = this.tryEntries[0];\n var rootRecord = rootEntry.completion;\n if (rootRecord.type === \"throw\") {\n throw rootRecord.arg;\n }\n\n return this.rval;\n },\n\n dispatchException: function(exception) {\n if (this.done) {\n throw exception;\n }\n\n var context = this;\n function handle(loc, caught) {\n record.type = \"throw\";\n record.arg = exception;\n context.next = loc;\n\n if (caught) {\n // If the dispatched exception was caught by a catch block,\n // then let that catch block handle the exception normally.\n context.method = \"next\";\n context.arg = undefined;\n }\n\n return !! caught;\n }\n\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n var record = entry.completion;\n\n if (entry.tryLoc === \"root\") {\n // Exception thrown outside of any try block that could handle\n // it, so set the completion value of the entire function to\n // throw the exception.\n return handle(\"end\");\n }\n\n if (entry.tryLoc <= this.prev) {\n var hasCatch = hasOwn.call(entry, \"catchLoc\");\n var hasFinally = hasOwn.call(entry, \"finallyLoc\");\n\n if (hasCatch && hasFinally) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n } else if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else if (hasCatch) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n }\n\n } else if (hasFinally) {\n if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else {\n throw new Error(\"try statement without catch or finally\");\n }\n }\n }\n },\n\n abrupt: function(type, arg) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc <= this.prev &&\n hasOwn.call(entry, \"finallyLoc\") &&\n this.prev < entry.finallyLoc) {\n var finallyEntry = entry;\n break;\n }\n }\n\n if (finallyEntry &&\n (type === \"break\" ||\n type === \"continue\") &&\n finallyEntry.tryLoc <= arg &&\n arg <= finallyEntry.finallyLoc) {\n // Ignore the finally entry if control is not jumping to a\n // location outside the try/catch block.\n finallyEntry = null;\n }\n\n var record = finallyEntry ? finallyEntry.completion : {};\n record.type = type;\n record.arg = arg;\n\n if (finallyEntry) {\n this.method = \"next\";\n this.next = finallyEntry.finallyLoc;\n return ContinueSentinel;\n }\n\n return this.complete(record);\n },\n\n complete: function(record, afterLoc) {\n if (record.type === \"throw\") {\n throw record.arg;\n }\n\n if (record.type === \"break\" ||\n record.type === \"continue\") {\n this.next = record.arg;\n } else if (record.type === \"return\") {\n this.rval = this.arg = record.arg;\n this.method = \"return\";\n this.next = \"end\";\n } else if (record.type === \"normal\" && afterLoc) {\n this.next = afterLoc;\n }\n\n return ContinueSentinel;\n },\n\n finish: function(finallyLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.finallyLoc === finallyLoc) {\n this.complete(entry.completion, entry.afterLoc);\n resetTryEntry(entry);\n return ContinueSentinel;\n }\n }\n },\n\n \"catch\": function(tryLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc === tryLoc) {\n var record = entry.completion;\n if (record.type === \"throw\") {\n var thrown = record.arg;\n resetTryEntry(entry);\n }\n return thrown;\n }\n }\n\n // The context.catch method must only be called with a location\n // argument that corresponds to a known catch block.\n throw new Error(\"illegal catch attempt\");\n },\n\n delegateYield: function(iterable, resultName, nextLoc) {\n this.delegate = {\n iterator: values(iterable),\n resultName: resultName,\n nextLoc: nextLoc\n };\n\n if (this.method === \"next\") {\n // Deliberately forget the last sent value so that we don't\n // accidentally pass it on to the delegate.\n this.arg = undefined;\n }\n\n return ContinueSentinel;\n }\n };\n\n // Regardless of whether this script is executing as a CommonJS module\n // or not, return the runtime object so that we can declare the variable\n // regeneratorRuntime in the outer scope, which allows this module to be\n // injected easily by `bin/regenerator --include-runtime script.js`.\n return exports;\n\n}(\n // If this script is executing as a CommonJS module, use module.exports\n // as the regeneratorRuntime namespace. Otherwise create a new empty\n // object. Either way, the resulting object will be used to initialize\n // the regeneratorRuntime variable at the top of this file.\n typeof module === \"object\" ? module.exports : {}\n));\n\ntry {\n regeneratorRuntime = runtime;\n} catch (accidentalStrictMode) {\n // This module should not be running in strict mode, so the above\n // assignment should always work unless something is misconfigured. Just\n // in case runtime.js accidentally runs in strict mode, we can escape\n // strict mode using a global Function call. This could conceivably fail\n // if a Content Security Policy forbids using Function, but in that case\n // the proper solution is to fix the accidental strict mode problem. If\n // you've misconfigured your bundler to force strict mode and applied a\n // CSP to forbid Function, and you're not willing to fix either of those\n // problems, please detail your unique predicament in a GitHub issue.\n Function(\"r\", \"regeneratorRuntime = r\")(runtime);\n}\n","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\n/**\r\n * Basic authentication stages used to determine\r\n * appropriate action after redirect occurs\r\n */\r\nexport const AppStages = {\r\n SIGN_IN: \"sign_in\",\r\n SIGN_OUT: \"sign_out\",\r\n ACQUIRE_TOKEN: \"acquire_token\",\r\n};\r\n\r\n/**\r\n * String constants related to AAD Authority\r\n */\r\nexport const AADAuthorityConstants = {\r\n COMMON: \"common\",\r\n ORGANIZATIONS: \"organizations\",\r\n CONSUMERS: \"consumers\"\r\n}\r\n\r\n/**\r\n * String constants related to AAD Authority\r\n */\r\nexport const KeyVaultCredentialTypes = {\r\n SECRET: \"secret\",\r\n CERTIFICATE: \"certificate\",\r\n}\r\n\r\n/**\r\n * Constants used in access control scenarios\r\n */\r\nexport const AccessConstants = {\r\n GROUPS: \"groups\",\r\n ROLES: \"roles\",\r\n CLAIM_NAMES: \"_claim_name\",\r\n CLAIM_SOURCES: \"_claim_sources\",\r\n PAGINATION_LINK: \"@odata.nextLink\",\r\n GRAPH_MEMBERS_ENDPOINT: \"https://graph.microsoft.com/v1.0/me/memberOf\",\r\n GRAPH_MEMBER_SCOPES: \"User.Read GroupMember.Read.All\"\r\n};\r\n\r\nexport const InfoMessages = {\r\n REQUEST_FOR_RESOURCE: \"Request made to web API\",\r\n OVERAGE_OCCURRED: \"User has too many groups. Groups overage claim occurred\"\r\n}\r\n\r\n/**\r\n * Various error constants\r\n */\r\nexport const ErrorMessages = {\r\n NOT_PERMITTED: \"Not permitted\",\r\n INVALID_TOKEN: \"Invalid token\",\r\n CANNOT_DETERMINE_APP_STAGE: \"Cannot determine application stage\",\r\n CANNOT_VALIDATE_TOKEN: \"Cannot validate token\",\r\n NONCE_MISMATCH: \"Nonce does not match\",\r\n INTERACTION_REQUIRED: \"interaction_required\",\r\n TOKEN_ACQUISITION_FAILED: \"Token acquisition failed\",\r\n AUTH_CODE_NOT_OBTAINED: \"Authorization code cannot be obtained\",\r\n TOKEN_NOT_FOUND: \"No token found\",\r\n TOKEN_NOT_DECODED: \"Token cannot be decoded\",\r\n TOKEN_NOT_VERIFIED: \"Token cannot be verified\",\r\n KEYS_NOT_OBTAINED: \"Signing keys cannot be obtained\",\r\n STATE_NOT_FOUND: \"State not found\",\r\n USER_HAS_NO_ROLE: \"User does not have any roles\",\r\n USER_NOT_IN_ROLE: \"User does not have this role\",\r\n USER_HAS_NO_GROUP: \"User does not have any groups\",\r\n USER_NOT_IN_GROUP: \"User does not have this group\",\r\n METHOD_NOT_ALLOWED: \"Method not allowed for this route\",\r\n RULE_NOT_FOUND: \"No rule found for this route\",\r\n SESSION_NOT_FOUND: \"No session found for this request\",\r\n KEY_VAULT_CONFIG_NOT_FOUND: \"No coordinates found for Key Vault\"\r\n};\r\n\r\nexport const ConfigurationErrorMessages = {\r\n NO_CLIENT_ID: \"No clientId provided!\",\r\n INVALID_CLIENT_ID: \"Invalid clientId!\",\r\n NO_TENANT_INFO: \"No tenant info provided!\",\r\n INVALID_TENANT_INFO: \"Invalid tenant info!\",\r\n NO_CLIENT_CREDENTIAL: \"No client credential provided!\",\r\n NO_REDIRECT_URI: \"No redirect URI provided!\",\r\n NO_ERROR_ROUTE: \"No error route provided!\",\r\n NO_UNAUTHORIZED_ROUTE: \"No unauthorized route provided!\"\r\n}\r\n\r\n/**\r\n * For more information, visit: https://login.microsoftonline.com/error\r\n */\r\nexport const ErrorCodes = {\r\n 65001: \"AADSTS65001\", // consent required\r\n};","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { \r\n UrlString, \r\n StringUtils,\r\n Constants, \r\n} from \"@azure/msal-common\";\r\n\r\nimport { \r\n ICachePlugin,\r\n Configuration,\r\n LogLevel \r\n} from \"@azure/msal-node\";\r\n\r\nimport { AppSettings } from \"./Types\";\r\n\r\nimport { \r\n AADAuthorityConstants, \r\n ConfigurationErrorMessages \r\n} from \"./Constants\";\r\n\r\nexport class ConfigurationUtils {\r\n\r\n /**\r\n * Validates the fields in the configuration file\r\n * @param {AppSettings} config: configuration object\r\n * @returns {void}\r\n */\r\n static validateAppSettings(config: AppSettings): void {\r\n if (StringUtils.isEmpty(config.appCredentials.clientId)) {\r\n throw new Error(ConfigurationErrorMessages.NO_CLIENT_ID);\r\n } else if (!ConfigurationUtils.isGuid(config.appCredentials.clientId)) {\r\n throw new Error(ConfigurationErrorMessages.INVALID_CLIENT_ID);\r\n }\r\n\r\n if (StringUtils.isEmpty(config.appCredentials.tenantId)) {\r\n throw new Error(ConfigurationErrorMessages.NO_TENANT_INFO);\r\n } else if (!ConfigurationUtils.isGuid(config.appCredentials.tenantId) && !Object.values(AADAuthorityConstants).includes(config.appCredentials.tenantId)) {\r\n throw new Error(ConfigurationErrorMessages.INVALID_TENANT_INFO);\r\n }\r\n\r\n if (StringUtils.isEmpty(config.appCredentials.clientSecret) && !config.appCredentials.clientCertificate) {\r\n throw new Error(ConfigurationErrorMessages.NO_CLIENT_CREDENTIAL);\r\n }\r\n\r\n if (StringUtils.isEmpty(config.authRoutes.redirect)) {\r\n throw new Error(ConfigurationErrorMessages.NO_REDIRECT_URI);\r\n }\r\n\r\n if (StringUtils.isEmpty(config.authRoutes.error)) {\r\n throw new Error(ConfigurationErrorMessages.NO_ERROR_ROUTE);\r\n }\r\n\r\n if (StringUtils.isEmpty(config.authRoutes.unauthorized)) {\r\n throw new Error(ConfigurationErrorMessages.NO_UNAUTHORIZED_ROUTE);\r\n }\r\n };\r\n\r\n\r\n /**\r\n * Maps the custom configuration object to configuration\r\n * object expected by MSAL Node ConfidentialClientApplication class\r\n * @param {AppSettings} config: configuration object\r\n * @param {ICachePlugin} cachePlugin: persistent cache implementation\r\n * @returns {Configuration}\r\n */\r\n static getMsalConfiguration(config: AppSettings, cachePlugin: ICachePlugin = null): Configuration {\r\n return {\r\n auth: {\r\n clientId: config.appCredentials.clientId,\r\n authority: config.b2cPolicies ?\r\n Object.entries(config.b2cPolicies)[0][1][\"authority\"]\r\n :\r\n `https://${Constants.DEFAULT_AUTHORITY_HOST}/${config.appCredentials.tenantId}`,\r\n ...(config.appCredentials.hasOwnProperty(\"clientSecret\")) && { clientSecret: config.appCredentials.clientSecret },\r\n ...(config.appCredentials.hasOwnProperty(\"clientCertificate\")) && { clientCertificate: config.appCredentials.clientCertificate },\r\n knownAuthorities: config.b2cPolicies ?\r\n [UrlString.getDomainFromUrl(Object.entries(config.b2cPolicies)[0][1][\"authority\"])] // in B2C scenarios\r\n :\r\n [],\r\n },\r\n cache: {\r\n cachePlugin,\r\n },\r\n system: {\r\n loggerOptions: {\r\n loggerCallback: (logLevel, message, containsPii) => {\r\n if (containsPii) {\r\n return;\r\n }\r\n switch (logLevel) {\r\n case LogLevel.Error:\r\n console.error(message);\r\n return;\r\n case LogLevel.Info:\r\n console.info(message);\r\n return;\r\n case LogLevel.Verbose:\r\n console.debug(message);\r\n return;\r\n case LogLevel.Warning:\r\n console.warn(message);\r\n return;\r\n }\r\n },\r\n piiLoggingEnabled: false,\r\n logLevel: LogLevel.Verbose,\r\n },\r\n },\r\n };\r\n };\r\n\r\n /**\r\n * verifies if a string is GUID\r\n * @param guid\r\n */\r\n static isGuid(guid: string): boolean {\r\n const regexGuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\r\n return regexGuid.test(guid);\r\n }\r\n}\r\n","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { LogLevel } from \"@azure/msal-common\"\r\n\r\nexport class Logger {\r\n\r\n /**\r\n * Log an error\r\n * @param {string} log\r\n * @returns {void}\r\n */\r\n static logError(log: string): void {\r\n console.error(this.logMessage(log));\r\n }\r\n\r\n /**\r\n * Log a warning\r\n * @param {string} log\r\n * @returns {void}\r\n */\r\n static logWarning(log: string): void {\r\n console.warn(this.logMessage(log));\r\n }\r\n\r\n /**\r\n * Log anything\r\n * @param {string} log\r\n * @returns {void}\r\n */\r\n static logInfo(log: string): void {\r\n console.info(this.logMessage(log));\r\n }\r\n\r\n /**\r\n * Log message with required options.\r\n * @param {string} logMessage \r\n * @returns {string}\r\n */\r\n private static logMessage(logMessage: string): string {\r\n const timestamp = new Date().toUTCString();\r\n\r\n let logHeader: string = `[${timestamp}]`;\r\n\r\n const log = `${logHeader} : @azure-samples/msal-express-wrapper@0.1.0 : ${LogLevel[LogLevel.Verbose]} - ${logMessage}`;\r\n return log;\r\n }\r\n\r\n}","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport jwt from \"jsonwebtoken\";\r\nimport jwksClient from \"jwks-rsa\";\r\n\r\nimport { \r\n StringUtils, \r\n Constants, \r\n TokenClaims \r\n} from \"@azure/msal-common\";\r\n\r\nimport { Configuration } from \"@azure/msal-node\";\r\n\r\nimport { Logger } from \"./Logger\";\r\n\r\nimport { \r\n AppSettings,\r\n Resource, \r\n IdTokenClaims, \r\n AccessTokenClaims \r\n} from \"./Types\";\r\n\r\nimport { \r\n ErrorMessages, \r\n AADAuthorityConstants \r\n} from \"./Constants\";\r\n\r\nexport class TokenValidator {\r\n private appSettings: AppSettings;\r\n private msalConfig: Configuration;\r\n\r\n /**\r\n * @param {AppSettings} appSettings \r\n * @param {Configuration} msalConfig\r\n * @constructor\r\n */\r\n constructor(appSettings: AppSettings, msalConfig: Configuration) {\r\n this.appSettings = appSettings;\r\n this.msalConfig = msalConfig;\r\n }\r\n\r\n /**\r\n * Verifies a given token's signature using jwks-rsa\r\n * @param {string} authToken \r\n * @returns {Promise}\r\n */\r\n async verifyTokenSignature(authToken: string): Promise {\r\n if (StringUtils.isEmpty(authToken)) {\r\n Logger.logError(ErrorMessages.TOKEN_NOT_FOUND);\r\n return false;\r\n }\r\n\r\n // we will first decode to get kid parameter in header\r\n let decodedToken;\r\n\r\n try {\r\n decodedToken = jwt.decode(authToken, { complete: true });\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.TOKEN_NOT_DECODED);\r\n console.log(error);\r\n return false;\r\n }\r\n\r\n // obtains signing keys from discovery endpoint\r\n let keys;\r\n\r\n try {\r\n keys = await this.getSigningKeys(decodedToken.header, decodedToken.payload.tid);\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.KEYS_NOT_OBTAINED);\r\n console.log(error);\r\n return false;\r\n }\r\n\r\n // verify the signature at header section using keys\r\n let verifiedToken: TokenClaims;\r\n\r\n try {\r\n verifiedToken = jwt.verify(authToken, keys);\r\n\r\n /**\r\n * if a multiplexer was used in place of tenantId i.e. if the app\r\n * is multi-tenant, the tenantId should be obtained from the user\"s\r\n * token\"s tid claim for verification purposes\r\n */\r\n if (\r\n this.appSettings.appCredentials.tenantId === AADAuthorityConstants.COMMON ||\r\n this.appSettings.appCredentials.tenantId === AADAuthorityConstants.ORGANIZATIONS ||\r\n this.appSettings.appCredentials.tenantId === AADAuthorityConstants.CONSUMERS\r\n ) {\r\n this.appSettings.appCredentials.tenantId = decodedToken.payload.tid;\r\n }\r\n\r\n return verifiedToken;\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.TOKEN_NOT_VERIFIED);\r\n console.log(error);\r\n return false;\r\n }\r\n };\r\n\r\n /**\r\n * Verifies the access token for signature\r\n * @param {string} idToken: raw Id token\r\n * @returns {Promise}\r\n */\r\n async validateIdToken(idToken: string): Promise {\r\n try {\r\n const verifiedToken = await this.verifyTokenSignature(idToken);\r\n\r\n if (verifiedToken) {\r\n return this.validateIdTokenClaims(verifiedToken as IdTokenClaims);\r\n } else {\r\n return false;\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n return false;\r\n }\r\n };\r\n\r\n /**\r\n * Validates the id token for a set of claims\r\n * @param {IdTokenClaims} idTokenClaims: decoded id token claims\r\n * @returns {boolean}\r\n */\r\n validateIdTokenClaims(idTokenClaims: IdTokenClaims): boolean {\r\n const now = Math.round(new Date().getTime() / 1000); // in UNIX format\r\n\r\n /**\r\n * At the very least, check for issuer, audience, issue and expiry dates.\r\n * For more information on validating id tokens, visit:\r\n * https://docs.microsoft.com/azure/active-directory/develop/id-tokens#validating-an-id_token\r\n */\r\n const checkIssuer = idTokenClaims.iss.includes(this.appSettings.appCredentials.tenantId) ? true : false;\r\n const checkAudience = idTokenClaims.aud === this.msalConfig.auth.clientId ? true : false;\r\n const checkTimestamp = idTokenClaims.iat <= now && idTokenClaims.exp >= now ? true : false;\r\n\r\n return checkIssuer && checkAudience && checkTimestamp;\r\n };\r\n\r\n /**\r\n * Verifies the access token for signature\r\n * @param {string} accessToken: raw JWT token\r\n * @param {string} protectedRoute: used for checking scope\r\n * @returns {Promise}\r\n */\r\n async verifyAccessTokenSignature(accessToken: string, protectedRoute: string): Promise {\r\n try {\r\n const verifiedToken = await this.verifyTokenSignature(accessToken);\r\n\r\n if (verifiedToken) {\r\n return this.validateAccessTokenClaims(verifiedToken as AccessTokenClaims, protectedRoute);\r\n } else {\r\n return false;\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n return false;\r\n }\r\n };\r\n\r\n /**\r\n * Validates the access token for a set of claims\r\n * @param {TokenClaims} verifiedToken: token with a verified signature\r\n * @param {string} protectedRoute: route where this token is required to access\r\n * @returns {boolean}\r\n */\r\n validateAccessTokenClaims(verifiedToken: AccessTokenClaims, protectedRoute: string): boolean {\r\n const now = Math.round(new Date().getTime() / 1000); // in UNIX format\r\n\r\n /**\r\n * At the very least, validate the token with respect to issuer, audience, scope\r\n * and timestamp, though implementation and extent vary. For more information, visit:\r\n * https://docs.microsoft.com/azure/active-directory/develop/access-tokens#validating-tokens\r\n */\r\n const checkIssuer = verifiedToken.iss.includes(this.appSettings.appCredentials.tenantId) ? true : false;\r\n const checkTimestamp = verifiedToken.iat <= now && verifiedToken.iat >= now ? true : false;\r\n\r\n const checkAudience = verifiedToken.aud === this.appSettings.appCredentials.clientId ||\r\n verifiedToken.aud === \"api://\" + this.appSettings.appCredentials.clientId ? true : false;\r\n\r\n const checkScopes = Object.values(this.appSettings.ownedResources).find((resource: Resource) => resource.endpoint === protectedRoute)\r\n .scopes.every(scp => verifiedToken.scp.includes(scp));\r\n\r\n return checkAudience && checkIssuer && checkTimestamp && checkScopes;\r\n };\r\n\r\n /**\r\n * Fetches signing keys of an access token\r\n * from the authority discovery endpoint\r\n * @param {Object} header: token header\r\n * @param {string} tid: tenant id\r\n * @returns {Promise}\r\n */\r\n private async getSigningKeys(header, tid: string): Promise {\r\n let jwksUri;\r\n\r\n // Check if a B2C application i.e. app has b2cPolicies\r\n if (this.appSettings.b2cPolicies) {\r\n jwksUri = `${this.msalConfig.auth.authority}/discovery/v2.0/keys`;\r\n } else {\r\n jwksUri = `https://${Constants.DEFAULT_AUTHORITY_HOST}/${tid}/discovery/v2.0/keys`;\r\n }\r\n\r\n const client = jwksClient({\r\n jwksUri: jwksUri,\r\n });\r\n\r\n return (await client.getSigningKeyAsync(header.kid)).getPublicKey();\r\n };\r\n}\r\n","import { CertificateClient, KeyVaultCertificate } from \"@azure/keyvault-certificates\";\r\nimport { DefaultAzureCredential } from \"@azure/identity\";\r\nimport { KeyVaultSecret, SecretClient } from \"@azure/keyvault-secrets\";\r\n\r\nimport { AppSettings } from \"./Types\";\r\nimport { KeyVaultCredentialTypes } from \"./Constants\";\r\n\r\nexport class KeyVaultManager {\r\n\r\n /**\r\n * Fetches credentials from Key Vault and updates appSettings\r\n * @param {AppSettings} config \r\n * @returns {Promise}\r\n */\r\n async getCredentialFromKeyVault(config: AppSettings): Promise {\r\n\r\n const credential = new DefaultAzureCredential();\r\n\r\n if (!config.appCredentials.keyVaultCredential) {\r\n return config\r\n }\r\n\r\n switch (config.appCredentials.keyVaultCredential.credentialType) {\r\n case KeyVaultCredentialTypes.SECRET: {\r\n try {\r\n const secretResponse = await this.getSecretCredential(config, credential);\r\n config.appCredentials.clientSecret = secretResponse.value;\r\n return config;\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n break;\r\n }\r\n\r\n case KeyVaultCredentialTypes.CERTIFICATE: {\r\n try {\r\n const certificateResponse = await this.getCertificateCredential(config, credential);\r\n const secretResponse = await this.getSecretCredential(config, credential);\r\n\r\n config.appCredentials.clientCertificate = {\r\n thumbprint: certificateResponse.properties.x509Thumbprint.toString(),\r\n privateKey: secretResponse.value.split('-----BEGIN CERTIFICATE-----\\n')[0]\r\n }\r\n return config;\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n break;\r\n }\r\n\r\n default:\r\n break;\r\n }\r\n };\r\n\r\n /**\r\n * Gets a certificate credential from Key Vault\r\n * @param {AppSettings} config \r\n * @param {DefaultAzureCredential} credential \r\n * @returns {Promise}\r\n */\r\n async getCertificateCredential(config: AppSettings, credential: DefaultAzureCredential): Promise {\r\n\r\n // Initialize secretClient with credentials\r\n const secretClient = new CertificateClient(config.appCredentials.keyVaultCredential.keyVaultUrl, credential);\r\n\r\n try {\r\n const keyVaultCertificate = await secretClient.getCertificate(config.appCredentials.keyVaultCredential.credentialName);\r\n return keyVaultCertificate;\r\n } catch (error) {\r\n console.log(error);\r\n return error;\r\n }\r\n }\r\n\r\n /**\r\n * Gets a secret credential from Key Vault\r\n * @param {AppSettings} config \r\n * @param {DefaultAzureCredential} credential \r\n * @returns {Promise}\r\n */\r\n async getSecretCredential(config: AppSettings, credential: DefaultAzureCredential): Promise {\r\n\r\n // Initialize secretClient with credentials\r\n const secretClient = new SecretClient(config.appCredentials.keyVaultCredential.keyVaultUrl, credential);\r\n\r\n try {\r\n const keyVaultSecret = await secretClient.getSecret(config.appCredentials.keyVaultCredential.credentialName);\r\n return keyVaultSecret;\r\n } catch (error) {\r\n console.log(error);\r\n return error;\r\n }\r\n }\r\n}","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport axios, { AxiosResponse, AxiosRequestConfig } from \"axios\";\r\nimport { StringUtils } from \"@azure/msal-common\";\r\n\r\nimport { \r\n AccessConstants, \r\n InfoMessages, \r\n ErrorMessages \r\n} from \"./Constants\";\r\n\r\nimport { Logger } from \"./Logger\";\r\n\r\nexport class FetchManager {\r\n\r\n /**\r\n * Calls a resource endpoint with a raw access token\r\n * using the authorization bearer token scheme\r\n * @param {string} endpoint \r\n * @param {string} accessToken \r\n * @returns {Promise}\r\n */\r\n static callApiEndpoint = async (endpoint: string, accessToken: string): Promise => {\r\n\r\n if (StringUtils.isEmpty(accessToken)) {\r\n throw new Error(ErrorMessages.TOKEN_NOT_FOUND)\r\n }\r\n\r\n const options: AxiosRequestConfig = {\r\n headers: {\r\n Authorization: `Bearer ${accessToken}`\r\n }\r\n };\r\n\r\n try {\r\n Logger.logInfo(InfoMessages.REQUEST_FOR_RESOURCE);\r\n const response: AxiosResponse = await axios.get(endpoint, options);\r\n return response.data;\r\n } catch (error) {\r\n console.log(error)\r\n return error;\r\n }\r\n }\r\n\r\n /**\r\n * Handles queries against Microsoft Graph that return multiple pages of data \r\n * @param {string} accessToken: access token required by endpoint \r\n * @param {string} nextPage: next page link\r\n * @param {Array} data: stores data from each page\r\n * @returns {Promise}\r\n */\r\n static handlePagination = async (accessToken: string, nextPage: string, data: string[] = []): Promise => {\r\n\r\n try {\r\n const graphResponse = await FetchManager.callApiEndpoint(nextPage, accessToken);\r\n graphResponse[\"value\"].map((v) => data.push(v.id));\r\n \r\n if (graphResponse[AccessConstants.PAGINATION_LINK]) {\r\n return await FetchManager.handlePagination(accessToken, graphResponse[AccessConstants.PAGINATION_LINK], data)\r\n } else {\r\n return data;\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n return error;\r\n }\r\n \r\n }\r\n\r\n}\r\n","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { Request } from \"express\";\r\nimport { IUri, UrlString } from \"@azure/msal-common\";\r\n\r\nexport class UrlUtils {\r\n /**\r\n * Gets the absolute URL from a given request and path string\r\n * @param {Request} req: express request object \r\n * @param {string} url: a given URL\r\n * @returns {string}\r\n */\r\n static ensureAbsoluteUrl = (req: Request, url: string): string => {\r\n const urlComponents: IUri = new UrlString(url).getUrlComponents();\r\n\r\n if (!urlComponents.Protocol) {\r\n if (!urlComponents.HostNameAndPort) {\r\n return req.protocol + \"://\" + req.get(\"host\") + url;\r\n }\r\n return req.protocol + \"://\" + url;\r\n } else {\r\n return url;\r\n }\r\n };\r\n\r\n /**\r\n * Gets the path segment from a given URL\r\n * @param {string} url: a given URL\r\n * @returns {string}\r\n */\r\n static getPathFromUrl = (url: string): string => {\r\n const urlComponents: IUri = new UrlString(url).getUrlComponents();\r\n return `/${urlComponents.PathSegments.join(\"/\")}`;\r\n };\r\n}\r\n","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\nimport express from \"express\";\r\n\r\nimport {\r\n RequestHandler,\r\n Request,\r\n Response,\r\n NextFunction,\r\n Router\r\n} from \"express\";\r\n\r\nimport {\r\n InteractionRequiredAuthError,\r\n OIDC_DEFAULT_SCOPES,\r\n PromptValue,\r\n StringUtils,\r\n} from \"@azure/msal-common\";\r\n\r\nimport {\r\n ConfidentialClientApplication,\r\n Configuration,\r\n AccountInfo,\r\n ICachePlugin,\r\n CryptoProvider,\r\n AuthorizationUrlRequest,\r\n AuthorizationCodeRequest,\r\n SilentFlowRequest,\r\n OnBehalfOfRequest,\r\n} from \"@azure/msal-node\";\r\n\r\nimport { ConfigurationUtils } from \"./ConfigurationUtils\";\r\nimport { TokenValidator } from \"./TokenValidator\";\r\nimport { KeyVaultManager } from \"./KeyVaultManager\";\r\nimport { FetchManager } from \"./FetchManager\";\r\nimport { UrlUtils } from \"./UrlUtils\";\r\nimport { Logger } from \"./Logger\";\r\n\r\nimport {\r\n Resource,\r\n AppSettings,\r\n AuthCodeParams,\r\n InitializationOptions,\r\n TokenRequestOptions,\r\n GuardOptions,\r\n AccessRule,\r\n SignInOptions,\r\n SignOutOptions,\r\n HandleRedirectOptions\r\n} from \"./Types\";\r\n\r\nimport {\r\n AppStages,\r\n ErrorMessages,\r\n AccessConstants,\r\n InfoMessages\r\n} from \"./Constants\";\r\n\r\n/**\r\n * A simple wrapper around MSAL Node ConfidentialClientApplication object.\r\n * It offers a collection of middleware and utility methods that automate\r\n * basic authentication and authorization tasks in Express MVC web apps and\r\n * RESTful APIs (coming soon).\r\n */\r\nexport class AuthProvider {\r\n appSettings: AppSettings;\r\n private msalConfig: Configuration;\r\n private cryptoProvider: CryptoProvider;\r\n private tokenValidator: TokenValidator;\r\n private msalClient: ConfidentialClientApplication;\r\n\r\n /**\r\n * @param {AppSettings} appSettings\r\n * @param {ICachePlugin} cache: cachePlugin\r\n * @constructor\r\n */\r\n constructor(appSettings: AppSettings, cache?: ICachePlugin) {\r\n ConfigurationUtils.validateAppSettings(appSettings);\r\n this.appSettings = appSettings;\r\n\r\n this.msalConfig = ConfigurationUtils.getMsalConfiguration(appSettings, cache);\r\n this.msalClient = new ConfidentialClientApplication(this.msalConfig);\r\n\r\n this.tokenValidator = new TokenValidator(this.appSettings, this.msalConfig);\r\n this.cryptoProvider = new CryptoProvider();\r\n }\r\n\r\n /**\r\n * Asynchronously builds authProvider object with credentials fetched from Key Vault\r\n * @param {AppSettings} appSettings\r\n * @param {ICachePlugin} cache: cachePlugin\r\n * @returns \r\n */\r\n static async buildAsync(appSettings: AppSettings, cache?: ICachePlugin): Promise {\r\n try {\r\n const keyVault = new KeyVaultManager();\r\n const appSettingsWithKeyVaultCredentials = await keyVault.getCredentialFromKeyVault(appSettings);\r\n const authProvider = new AuthProvider(appSettingsWithKeyVaultCredentials, cache);\r\n return authProvider;\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n }\r\n\r\n /**\r\n * Initialize AuthProvider and set default routes and handlers\r\n * @param {InitializationOptions} options\r\n * @returns {Router}\r\n */\r\n initialize = (options?: InitializationOptions): Router => {\r\n\r\n // TODO: initialize app defaults\r\n\r\n const appRouter = express.Router();\r\n\r\n // handle redirect\r\n appRouter.get(UrlUtils.getPathFromUrl(this.appSettings.authRoutes.redirect), this.handleRedirect());\r\n\r\n if (this.appSettings.authRoutes.frontChannelLogout) {\r\n /**\r\n * Expose front-channel logout route. For more information, visit: \r\n * https://docs.microsoft.com/azure/active-directory/develop/v2-protocols-oidc#single-sign-out\r\n */\r\n appRouter.get(this.appSettings.authRoutes.frontChannelLogout, (req, res, next) => {\r\n req.session.destroy(() => {\r\n res.sendStatus(200);\r\n });\r\n });\r\n }\r\n\r\n return appRouter;\r\n }\r\n\r\n // ========== ROUTE HANDLERS ===========\r\n\r\n /**\r\n * Initiates sign in flow\r\n * @param {SignInOptions} options: options to modify login request\r\n * @returns {RequestHandler}\r\n */\r\n signIn = (options?: SignInOptions): RequestHandler => {\r\n return (req: Request, res: Response, next: NextFunction): Promise => {\r\n /**\r\n * Request Configuration\r\n * We manipulate these three request objects below\r\n * to acquire a token with the appropriate claims\r\n */\r\n if (!req.session[\"authCodeRequest\"]) {\r\n req.session.authCodeRequest = {\r\n authority: \"\",\r\n scopes: [],\r\n state: {},\r\n redirectUri: \"\",\r\n } as AuthorizationUrlRequest;\r\n }\r\n\r\n if (!req.session[\"tokenRequest\"]) {\r\n req.session.tokenRequest = {\r\n authority: \"\",\r\n scopes: [],\r\n redirectUri: \"\",\r\n code: \"\",\r\n } as AuthorizationCodeRequest;\r\n }\r\n\r\n // signed-in user's account\r\n if (!req.session[\"account\"]) {\r\n req.session.account = {\r\n homeAccountId: \"\",\r\n environment: \"\",\r\n tenantId: \"\",\r\n username: \"\",\r\n idTokenClaims: {},\r\n } as AccountInfo;\r\n }\r\n\r\n // random GUID for csrf protection\r\n req.session.nonce = this.cryptoProvider.createNewGuid();\r\n \r\n // TODO: encrypt state parameter \r\n const state = this.cryptoProvider.base64Encode(\r\n JSON.stringify({\r\n stage: AppStages.SIGN_IN,\r\n path: options.successRedirect,\r\n nonce: req.session.nonce,\r\n })\r\n );\r\n\r\n const params: AuthCodeParams = {\r\n authority: this.msalConfig.auth.authority,\r\n scopes: OIDC_DEFAULT_SCOPES,\r\n state: state,\r\n redirect: UrlUtils.ensureAbsoluteUrl(req, this.appSettings.authRoutes.redirect),\r\n prompt: PromptValue.SELECT_ACCOUNT,\r\n };\r\n\r\n // get url to sign user in\r\n return this.getAuthCode(req, res, next, params);\r\n }\r\n };\r\n\r\n /**\r\n * Initiate sign out and destroy the session\r\n * @param options: options to modify logout request \r\n * @returns {RequestHandler}\r\n */\r\n signOut = (options?: SignOutOptions): RequestHandler => {\r\n return (req: Request, res: Response, next: NextFunction): void => {\r\n const postLogoutRedirectUri = UrlUtils.ensureAbsoluteUrl(req, options.successRedirect);\r\n\r\n /**\r\n * Construct a logout URI and redirect the user to end the\r\n * session with Azure AD/B2C. For more information, visit:\r\n * (AAD) https://docs.microsoft.com/azure/active-directory/develop/v2-protocols-oidc#send-a-sign-out-request\r\n * (B2C) https://docs.microsoft.com/azure/active-directory-b2c/openid-connect#send-a-sign-out-request\r\n */\r\n const logoutURI = `${this.msalConfig.auth.authority}/oauth2/v2.0/logout?post_logout_redirect_uri=${postLogoutRedirectUri}`;\r\n\r\n req.session.isAuthenticated = false;\r\n\r\n req.session.destroy(() => {\r\n res.redirect(logoutURI);\r\n });\r\n }\r\n };\r\n\r\n /**\r\n * Middleware that handles redirect depending on request state\r\n * There are basically 2 stages: sign-in and acquire token\r\n * @param {HandleRedirectOptions} options: options to modify this middleware\r\n * @returns {RequestHandler}\r\n */\r\n private handleRedirect = (options?: HandleRedirectOptions): RequestHandler => {\r\n return async (req: Request, res: Response, next: NextFunction): Promise => {\r\n if (req.query.state) {\r\n const state = JSON.parse(this.cryptoProvider.base64Decode(req.query.state as string));\r\n\r\n // check if nonce matches\r\n if (state.nonce === req.session.nonce) {\r\n switch (state.stage) {\r\n case AppStages.SIGN_IN: {\r\n // token request should have auth code\r\n req.session.tokenRequest.code = req.query.code as string;\r\n\r\n try {\r\n // exchange auth code for tokens\r\n const tokenResponse = await this.msalClient.acquireTokenByCode(req.session.tokenRequest);\r\n\r\n try {\r\n const isIdTokenValid = await this.tokenValidator.validateIdToken(tokenResponse.idToken);\r\n\r\n if (isIdTokenValid) {\r\n // assign session variables\r\n req.session.account = tokenResponse.account;\r\n req.session.isAuthenticated = true;\r\n\r\n res.redirect(state.path);\r\n } else {\r\n Logger.logError(ErrorMessages.INVALID_TOKEN);\r\n res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.CANNOT_VALIDATE_TOKEN);\r\n next(error)\r\n }\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.TOKEN_ACQUISITION_FAILED);\r\n next(error)\r\n }\r\n break;\r\n }\r\n\r\n case AppStages.ACQUIRE_TOKEN: {\r\n // get the name of the resource associated with scope\r\n const resourceName = this.getResourceNameFromScopes(req.session.tokenRequest.scopes);\r\n\r\n req.session.tokenRequest.code = req.query.code as string\r\n\r\n try {\r\n const tokenResponse = await this.msalClient.acquireTokenByCode(req.session.tokenRequest);\r\n req.session.remoteResources[resourceName].accessToken = tokenResponse.accessToken;\r\n res.redirect(state.path);\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.TOKEN_ACQUISITION_FAILED);\r\n next(error);\r\n }\r\n break;\r\n }\r\n\r\n default:\r\n Logger.logError(ErrorMessages.CANNOT_DETERMINE_APP_STAGE);\r\n res.redirect(this.appSettings.authRoutes.error);\r\n break;\r\n }\r\n } else {\r\n Logger.logError(ErrorMessages.NONCE_MISMATCH);\r\n res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n } else {\r\n Logger.logError(ErrorMessages.STATE_NOT_FOUND)\r\n res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n }\r\n };\r\n\r\n // ========== MIDDLEWARE ===========\r\n\r\n /**\r\n * Middleware that gets tokens via acquireToken*\r\n * @param {TokenRequestOptions} options: options to modify this middleware\r\n * @returns {RequestHandler}\r\n */\r\n getToken = (options: TokenRequestOptions): RequestHandler => {\r\n return async (req: Request, res: Response, next: NextFunction): Promise => {\r\n // get scopes for token request\r\n const scopes = options.resource.scopes;\r\n\r\n const resourceName = this.getResourceNameFromScopes(scopes)\r\n\r\n if (!req.session.remoteResources) {\r\n req.session.remoteResources = {};\r\n }\r\n\r\n req.session.remoteResources = {\r\n [resourceName]: {\r\n ...this.appSettings.remoteResources[resourceName],\r\n accessToken: null,\r\n } as Resource\r\n };\r\n\r\n try {\r\n const silentRequest: SilentFlowRequest = {\r\n account: req.session.account,\r\n scopes: scopes,\r\n };\r\n\r\n // acquire token silently to be used in resource call\r\n const tokenResponse = await this.msalClient.acquireTokenSilent(silentRequest);\r\n\r\n // In B2C scenarios, sometimes an access token is returned empty.\r\n // In that case, we will acquire token interactively instead.\r\n if (StringUtils.isEmpty(tokenResponse.accessToken)) {\r\n Logger.logError(ErrorMessages.TOKEN_NOT_FOUND);\r\n throw new InteractionRequiredAuthError(ErrorMessages.INTERACTION_REQUIRED);\r\n }\r\n\r\n req.session.remoteResources[resourceName].accessToken = tokenResponse.accessToken;\r\n next();\r\n } catch (error) {\r\n // in case there are no cached tokens, initiate an interactive call\r\n if (error instanceof InteractionRequiredAuthError) {\r\n const state = this.cryptoProvider.base64Encode(\r\n JSON.stringify({\r\n stage: AppStages.ACQUIRE_TOKEN,\r\n path: req.originalUrl,\r\n nonce: req.session.nonce,\r\n })\r\n );\r\n\r\n const params: AuthCodeParams = {\r\n authority: this.msalConfig.auth.authority,\r\n scopes: scopes,\r\n state: state,\r\n redirect: UrlUtils.ensureAbsoluteUrl(req, this.appSettings.authRoutes.redirect),\r\n account: req.session.account,\r\n };\r\n\r\n // initiate the first leg of auth code grant to get token\r\n return this.getAuthCode(req, res, next, params);\r\n } else {\r\n next(error);\r\n }\r\n }\r\n }\r\n };\r\n\r\n /**\r\n * Middleware that gets tokens via OBO flow. Used in web API scenarios\r\n * @param {TokenRequestOptions} options: options to modify this middleware\r\n * @returns {RequestHandler}\r\n */\r\n getTokenOnBehalf = (options: TokenRequestOptions): RequestHandler => {\r\n return async (req: Request, res: Response, next: NextFunction): Promise => {\r\n const authHeader = req.headers.authorization;\r\n\r\n // get scopes for token request\r\n const scopes = options.resource.scopes;\r\n const resourceName = this.getResourceNameFromScopes(scopes);\r\n\r\n const oboRequest: OnBehalfOfRequest = {\r\n oboAssertion: authHeader.split(\" \")[1],\r\n scopes: scopes,\r\n }\r\n\r\n try {\r\n const tokenResponse = await this.msalClient.acquireTokenOnBehalfOf(oboRequest);\r\n\r\n // as OBO is commonly used in middle-tier web APIs without sessions, attach AT to req\r\n req[\"locals\"] = {\r\n [resourceName]: {\r\n accessToken: tokenResponse.accessToken\r\n }\r\n }\r\n\r\n next();\r\n } catch (error) {\r\n next(error);\r\n }\r\n }\r\n }\r\n\r\n // ============== GUARDS ===============\r\n\r\n /**\r\n * Check if authenticated in session\r\n * @param {GuardOptions} options: options to modify this middleware\r\n * @returns {RequestHandler}\r\n */\r\n isAuthenticated = (options?: GuardOptions): RequestHandler => {\r\n return (req: Request, res: Response, next: NextFunction): void => {\r\n if (req.session) {\r\n if (!req.session.isAuthenticated) {\r\n Logger.logError(ErrorMessages.NOT_PERMITTED);\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n\r\n next();\r\n } else {\r\n Logger.logError(ErrorMessages.SESSION_NOT_FOUND);\r\n res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n }\r\n };\r\n\r\n /**\r\n * Receives access token in req authorization header\r\n * and validates it using the jwt.verify\r\n * @param {GuardOptions} options: options to modify this middleware\r\n * @returns {RequestHandler}\r\n */\r\n isAuthorized = (options?: GuardOptions): RequestHandler => {\r\n return async (req: Request, res: Response, next: NextFunction): Promise => {\r\n const accessToken = req.headers.authorization.split(\" \")[1];\r\n\r\n if (req.headers.authorization) {\r\n if (!(await this.tokenValidator.verifyAccessTokenSignature(accessToken, `${req.baseUrl}${req.path}`))) {\r\n Logger.logError(ErrorMessages.INVALID_TOKEN);\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n\r\n next();\r\n } else {\r\n Logger.logError(ErrorMessages.TOKEN_NOT_FOUND);\r\n res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n }\r\n };\r\n\r\n /**\r\n * Checks if the user has access for this route, defined in access matrix\r\n * @param {GuardOptions} options: options to modify this middleware\r\n * @returns {RequestHandler}\r\n */\r\n hasAccess = (options?: GuardOptions): RequestHandler => {\r\n return async (req: Request, res: Response, next: NextFunction): Promise => {\r\n if (req.session && this.appSettings.accessMatrix) {\r\n\r\n const checkFor = options.accessRule.hasOwnProperty(AccessConstants.GROUPS) ? AccessConstants.GROUPS : AccessConstants.ROLES;\r\n\r\n switch (checkFor) {\r\n case AccessConstants.GROUPS:\r\n\r\n if (req.session.account.idTokenClaims[AccessConstants.GROUPS] === undefined) {\r\n if (req.session.account.idTokenClaims[AccessConstants.CLAIM_NAMES] || req.session.account.idTokenClaims[AccessConstants.CLAIM_SOURCES]) {\r\n Logger.logWarning(InfoMessages.OVERAGE_OCCURRED)\r\n return await this.handleOverage(req, res, next, options.accessRule);\r\n } else {\r\n Logger.logError(ErrorMessages.USER_HAS_NO_GROUP);\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n } else {\r\n const groups = req.session.account.idTokenClaims[AccessConstants.GROUPS];\r\n\r\n if (!this.checkAccessRule(req.method, options.accessRule, groups, AccessConstants.GROUPS)) {\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n }\r\n\r\n next();\r\n break;\r\n\r\n case AccessConstants.ROLES:\r\n if (req.session.account.idTokenClaims[AccessConstants.ROLES] === undefined) {\r\n Logger.logError(ErrorMessages.USER_HAS_NO_ROLE);\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n } else {\r\n const roles = req.session.account.idTokenClaims[AccessConstants.ROLES];\r\n\r\n if (!this.checkAccessRule(req.method, options.accessRule, roles, AccessConstants.ROLES)) {\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n }\r\n\r\n next();\r\n break;\r\n\r\n default:\r\n break;\r\n }\r\n } else {\r\n res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n }\r\n }\r\n\r\n // ============== UTILS ===============\r\n\r\n /**\r\n * This method is used to generate an auth code url request\r\n * @param {Request} req: express request object\r\n * @param {Response} res: express response object\r\n * @param {NextFunction} next: express next function\r\n * @param {AuthCodeParams} params: modifies auth code url request\r\n * @returns {Promise}\r\n */\r\n private async getAuthCode(req: Request, res: Response, next: NextFunction, params: AuthCodeParams): Promise {\r\n // prepare the request\r\n req.session.authCodeRequest.authority = params.authority;\r\n req.session.authCodeRequest.scopes = params.scopes;\r\n req.session.authCodeRequest.state = params.state;\r\n req.session.authCodeRequest.redirectUri = params.redirect;\r\n req.session.authCodeRequest.prompt = params.prompt;\r\n req.session.authCodeRequest.account = params.account;\r\n\r\n req.session.tokenRequest.authority = params.authority;\r\n req.session.tokenRequest.scopes = params.scopes;\r\n req.session.tokenRequest.redirectUri = params.redirect;\r\n\r\n // request an authorization code to exchange for tokens\r\n try {\r\n const response = await this.msalClient.getAuthCodeUrl(req.session.authCodeRequest);\r\n res.redirect(response);\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.AUTH_CODE_NOT_OBTAINED);\r\n next(error);\r\n }\r\n };\r\n\r\n /**\r\n * Handles group overage claims by querying MS Graph /memberOf endpoint\r\n * @param {Request} req: express request object\r\n * @param {Response} res: express response object\r\n * @param {NextFunction} next: express next function\r\n * @param {AccessRule} rule: a given access rule\r\n * @returns {Promise}\r\n */\r\n private async handleOverage(req: Request, res: Response, next: NextFunction, rule: AccessRule): Promise {\r\n const { _claim_names, _claim_sources, ...newIdTokenClaims } = req.session.account.idTokenClaims;\r\n\r\n const silentRequest: SilentFlowRequest = {\r\n account: req.session.account,\r\n scopes: AccessConstants.GRAPH_MEMBER_SCOPES.split(\" \"),\r\n };\r\n\r\n try {\r\n // acquire token silently to be used in resource call\r\n const tokenResponse = await this.msalClient.acquireTokenSilent(silentRequest);\r\n try {\r\n const graphResponse = await FetchManager.callApiEndpoint(AccessConstants.GRAPH_MEMBERS_ENDPOINT, tokenResponse.accessToken);\r\n\r\n /**\r\n * Some queries against Microsoft Graph return multiple pages of data either due to server-side paging \r\n * or due to the use of the $top query parameter to specifically limit the page size in a request. \r\n * When a result set spans multiple pages, Microsoft Graph returns an @odata.nextLink property in \r\n * the response that contains a URL to the next page of results. Learn more at https://docs.microsoft.com/graph/paging\r\n */\r\n if (graphResponse[AccessConstants.PAGINATION_LINK]) {\r\n try {\r\n const userGroups = await FetchManager.handlePagination(tokenResponse.accessToken, graphResponse[AccessConstants.PAGINATION_LINK]);\r\n\r\n req.session.account.idTokenClaims = {\r\n ...newIdTokenClaims,\r\n groups: userGroups\r\n }\r\n\r\n if (!this.checkAccessRule(req.method, rule, req.session.account.idTokenClaims[AccessConstants.GROUPS], AccessConstants.GROUPS)) {\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n } else {\r\n return next();\r\n }\r\n } catch (error) {\r\n next(error);\r\n }\r\n } else {\r\n req.session.account.idTokenClaims = {\r\n ...newIdTokenClaims,\r\n groups: graphResponse[\"value\"].map((v) => v.id)\r\n }\r\n\r\n if (!this.checkAccessRule(req.method, rule, req.session.account.idTokenClaims[AccessConstants.GROUPS], AccessConstants.GROUPS)) {\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n } else {\r\n return next();\r\n }\r\n }\r\n } catch (error) {\r\n next(error);\r\n }\r\n } catch (error) {\r\n next(error);\r\n }\r\n }\r\n\r\n /**\r\n * Checks if the request passes a given access rule\r\n * @param {string} method: HTTP method for this route\r\n * @param {AccessRule} rule: access rule for this route\r\n * @param {Array} creds: user's credentials i.e. roles or groups\r\n * @param {string} credType: roles or groups\r\n * @returns {boolean}\r\n */\r\n private checkAccessRule(method: string, rule: AccessRule, creds: string[], credType: string): boolean {\r\n if (rule.methods.includes(method)) {\r\n switch (credType) {\r\n case AccessConstants.GROUPS:\r\n if (rule.groups.filter(elem => creds.includes(elem)).length < 1) {\r\n Logger.logError(ErrorMessages.USER_NOT_IN_GROUP);\r\n return false;\r\n }\r\n break;\r\n\r\n case AccessConstants.ROLES:\r\n if (rule.roles.filter(elem => creds.includes(elem)).length < 1) {\r\n Logger.logError(ErrorMessages.USER_NOT_IN_ROLE);\r\n return false;\r\n }\r\n break;\r\n\r\n default:\r\n break;\r\n }\r\n } else {\r\n Logger.logError(ErrorMessages.METHOD_NOT_ALLOWED);\r\n return false;\r\n }\r\n\r\n return true;\r\n }\r\n\r\n /**\r\n * Util method to get the resource name for a given scope(s)\r\n * @param {Array} scopes: an array of scopes that the resource is associated with\r\n * @returns {string}\r\n */\r\n private getResourceNameFromScopes(scopes: string[]): string {\r\n // TODO: deep check equality here \r\n\r\n const index = Object.values({ ...this.appSettings.remoteResources, ...this.appSettings.ownedResources })\r\n .findIndex((resource: Resource) => JSON.stringify(resource.scopes) === JSON.stringify(scopes));\r\n\r\n const resourceName = Object.keys({ ...this.appSettings.remoteResources, ...this.appSettings.ownedResources })[index];\r\n return resourceName;\r\n };\r\n}\r\n"],"names":["runtime","exports","Op","Object","prototype","hasOwn","hasOwnProperty","$Symbol","Symbol","iteratorSymbol","iterator","asyncIteratorSymbol","asyncIterator","toStringTagSymbol","toStringTag","define","obj","key","value","defineProperty","enumerable","configurable","writable","err","wrap","innerFn","outerFn","self","tryLocsList","generator","create","Generator","context","Context","_invoke","state","method","arg","Error","undefined","done","delegate","delegateResult","maybeInvokeDelegate","ContinueSentinel","sent","_sent","dispatchException","abrupt","record","tryCatch","type","makeInvokeMethod","fn","call","GeneratorFunction","GeneratorFunctionPrototype","IteratorPrototype","this","getProto","getPrototypeOf","NativeIteratorPrototype","values","Gp","defineIteratorMethods","forEach","AsyncIterator","PromiseImpl","previousPromise","callInvokeWithMethodAndArg","resolve","reject","invoke","result","__await","then","unwrapped","error","TypeError","info","resultName","next","nextLoc","pushTryEntry","locs","entry","tryLoc","catchLoc","finallyLoc","afterLoc","tryEntries","push","resetTryEntry","completion","reset","iterable","iteratorMethod","isNaN","length","i","doneResult","constructor","displayName","isGeneratorFunction","genFun","ctor","name","mark","setPrototypeOf","__proto__","awrap","async","Promise","iter","toString","keys","object","reverse","pop","skipTempReset","prev","charAt","slice","stop","rootRecord","rval","exception","handle","loc","caught","hasCatch","hasFinally","finallyEntry","complete","finish","catch","thrown","delegateYield","module","regeneratorRuntime","accidentalStrictMode","Function","AppStages","SIGN_IN","SIGN_OUT","ACQUIRE_TOKEN","AADAuthorityConstants","COMMON","ORGANIZATIONS","CONSUMERS","KeyVaultCredentialTypes","SECRET","CERTIFICATE","AccessConstants","GROUPS","ROLES","CLAIM_NAMES","CLAIM_SOURCES","PAGINATION_LINK","GRAPH_MEMBERS_ENDPOINT","GRAPH_MEMBER_SCOPES","InfoMessages","REQUEST_FOR_RESOURCE","OVERAGE_OCCURRED","ErrorMessages","NOT_PERMITTED","INVALID_TOKEN","CANNOT_DETERMINE_APP_STAGE","CANNOT_VALIDATE_TOKEN","NONCE_MISMATCH","INTERACTION_REQUIRED","TOKEN_ACQUISITION_FAILED","AUTH_CODE_NOT_OBTAINED","TOKEN_NOT_FOUND","TOKEN_NOT_DECODED","TOKEN_NOT_VERIFIED","KEYS_NOT_OBTAINED","STATE_NOT_FOUND","USER_HAS_NO_ROLE","USER_NOT_IN_ROLE","USER_HAS_NO_GROUP","USER_NOT_IN_GROUP","METHOD_NOT_ALLOWED","RULE_NOT_FOUND","SESSION_NOT_FOUND","KEY_VAULT_CONFIG_NOT_FOUND","ConfigurationErrorMessages","NO_CLIENT_ID","INVALID_CLIENT_ID","NO_TENANT_INFO","INVALID_TENANT_INFO","NO_CLIENT_CREDENTIAL","NO_REDIRECT_URI","NO_ERROR_ROUTE","NO_UNAUTHORIZED_ROUTE","ConfigurationUtils","validateAppSettings","config","StringUtils","isEmpty","appCredentials","clientId","isGuid","tenantId","includes","clientSecret","clientCertificate","authRoutes","redirect","unauthorized","getMsalConfiguration","cachePlugin","auth","authority","b2cPolicies","entries","Constants","DEFAULT_AUTHORITY_HOST","knownAuthorities","UrlString","getDomainFromUrl","cache","system","loggerOptions","loggerCallback","logLevel","message","containsPii","LogLevel","console","Info","Verbose","debug","Warning","warn","piiLoggingEnabled","guid","test","Logger","logError","log","logMessage","logWarning","logInfo","Date","toUTCString","logHeader","TokenValidator","appSettings","msalConfig","verifyTokenSignature","authToken","decodedToken","jwt","decode","getSigningKeys","header","payload","tid","verifiedToken","verify","validateIdToken","idToken","validateIdTokenClaims","idTokenClaims","now","Math","round","getTime","iss","aud","iat","exp","verifyAccessTokenSignature","accessToken","protectedRoute","validateAccessTokenClaims","checkIssuer","checkTimestamp","checkAudience","checkScopes","ownedResources","find","resource","endpoint","scopes","every","scp","client","jwksClient","jwksUri","getSigningKeyAsync","kid","getPublicKey","KeyVaultManager","getCredentialFromKeyVault","credential","DefaultAzureCredential","keyVaultCredential","credentialType","getSecretCredential","getCertificateCredential","certificateResponse","secretResponse","thumbprint","properties","x509Thumbprint","privateKey","split","secretClient","CertificateClient","keyVaultUrl","getCertificate","credentialName","SecretClient","getSecret","FetchManager","options","headers","Authorization","axios","get","data","nextPage","callApiEndpoint","graphResponse","map","v","id","handlePagination","UrlUtils","req","url","urlComponents","getUrlComponents","Protocol","HostNameAndPort","protocol","PathSegments","join","AuthProvider","appRouter","express","Router","getPathFromUrl","_this","handleRedirect","frontChannelLogout","res","session","destroy","sendStatus","authCodeRequest","redirectUri","tokenRequest","code","account","homeAccountId","environment","username","nonce","cryptoProvider","createNewGuid","base64Encode","JSON","stringify","stage","path","successRedirect","params","OIDC_DEFAULT_SCOPES","ensureAbsoluteUrl","prompt","PromptValue","SELECT_ACCOUNT","getAuthCode","postLogoutRedirectUri","logoutURI","isAuthenticated","query","parse","base64Decode","msalClient","acquireTokenByCode","tokenResponse","tokenValidator","resourceName","getResourceNameFromScopes","remoteResources","silentRequest","acquireTokenSilent","InteractionRequiredAuthError","_context2","originalUrl","authHeader","authorization","oboRequest","oboAssertion","acquireTokenOnBehalfOf","baseUrl","accessMatrix","checkFor","accessRule","handleOverage","checkAccessRule","ConfidentialClientApplication","CryptoProvider","buildAsync","keyVault","authProvider","getAuthCodeUrl","rule","_claim_names","newIdTokenClaims","groups","creds","credType","methods","filter","elem","roles","index","findIndex"],"mappings":"gkCAOA,IAAIA,EAAW,SAAUC,GAGvB,IAAIC,EAAKC,OAAOC,UACZC,EAASH,EAAGI,eAEZC,EAA4B,mBAAXC,OAAwBA,OAAS,GAClDC,EAAiBF,EAAQG,UAAY,aACrCC,EAAsBJ,EAAQK,eAAiB,kBAC/CC,EAAoBN,EAAQO,aAAe,gBAE/C,SAASC,EAAOC,EAAKC,EAAKC,GAOxB,OANAf,OAAOgB,eAAeH,EAAKC,EAAK,CAC9BC,MAAOA,EACPE,YAAY,EACZC,cAAc,EACdC,UAAU,IAELN,EAAIC,GAEb,IAEEF,EAAO,GAAI,IACX,MAAOQ,GACPR,EAAS,SAASC,EAAKC,EAAKC,GAC1B,OAAOF,EAAIC,GAAOC,GAItB,SAASM,EAAKC,EAASC,EAASC,EAAMC,GAEpC,IACIC,EAAY1B,OAAO2B,QADFJ,GAAWA,EAAQtB,qBAAqB2B,EAAYL,EAAUK,GACtC3B,WACzC4B,EAAU,IAAIC,EAAQL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apper.esm.js +++ b/dist/msal-express-wrapper.esm.js @@ -1739,6 +1739,17 @@ UrlUtils.ensureAbsoluteUrl = function (req, url) { return url; } }; +/** + * Gets the path segment from a given URL + * @param {string} url: a given URL + * @returns {string} + */ + + +UrlUtils.getPathFromUrl = function (url) { + var urlComponents = new UrlString(url).getUrlComponents(); + return "/" + urlComponents.PathSegments.join("/"); +}; var _excluded = ["_claim_names", "_claim_sources"]; /** @@ -1766,7 +1777,7 @@ var AuthProvider = /*#__PURE__*/function () { // TODO: initialize app defaults var appRouter = express.Router(); // handle redirect - appRouter.get(_this.appSettings.authRoutes.redirect, _this.handleRedirect()); + appRouter.get(UrlUtils.getPathFromUrl(_this.appSettings.authRoutes.redirect), _this.handleRedirect()); if (_this.appSettings.authRoutes.frontChannelLogout) { /** diff --git a/dist/msal-express-wrapper.esm.js.map b/dist/msal-express-wrapper.esm.js.map index 58a8c56..2f893fa 100644 --- a/dist/msal-express-wrapper.esm.js.map +++ b/dist/msal-express-wrapper.esm.js.map @@ -1 +1 @@ -{"version":3,"file":"msal-express-wrapper.esm.js","sources":["../node_modules/regenerator-runtime/runtime.js","../src/Constants.ts","../src/ConfigurationUtils.ts","../src/Logger.ts","../src/TokenValidator.ts","../src/KeyVaultManager.ts","../src/FetchManager.ts","../src/UrlUtils.ts","../src/AuthProvider.ts"],"sourcesContent":["/**\n * Copyright (c) 2014-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nvar runtime = (function (exports) {\n \"use strict\";\n\n var Op = Object.prototype;\n var hasOwn = Op.hasOwnProperty;\n var undefined; // More compressible than void 0.\n var $Symbol = typeof Symbol === \"function\" ? Symbol : {};\n var iteratorSymbol = $Symbol.iterator || \"@@iterator\";\n var asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\";\n var toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n\n function define(obj, key, value) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n return obj[key];\n }\n try {\n // IE 8 has a broken Object.defineProperty that only works on DOM objects.\n define({}, \"\");\n } catch (err) {\n define = function(obj, key, value) {\n return obj[key] = value;\n };\n }\n\n function wrap(innerFn, outerFn, self, tryLocsList) {\n // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.\n var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;\n var generator = Object.create(protoGenerator.prototype);\n var context = new Context(tryLocsList || []);\n\n // The ._invoke method unifies the implementations of the .next,\n // .throw, and .return methods.\n generator._invoke = makeInvokeMethod(innerFn, self, context);\n\n return generator;\n }\n exports.wrap = wrap;\n\n // Try/catch helper to minimize deoptimizations. Returns a completion\n // record like context.tryEntries[i].completion. This interface could\n // have been (and was previously) designed to take a closure to be\n // invoked without arguments, but in all the cases we care about we\n // already have an existing method we want to call, so there's no need\n // to create a new function object. We can even get away with assuming\n // the method takes exactly one argument, since that happens to be true\n // in every case, so we don't have to touch the arguments object. The\n // only additional allocation required is the completion record, which\n // has a stable shape and so hopefully should be cheap to allocate.\n function tryCatch(fn, obj, arg) {\n try {\n return { type: \"normal\", arg: fn.call(obj, arg) };\n } catch (err) {\n return { type: \"throw\", arg: err };\n }\n }\n\n var GenStateSuspendedStart = \"suspendedStart\";\n var GenStateSuspendedYield = \"suspendedYield\";\n var GenStateExecuting = \"executing\";\n var GenStateCompleted = \"completed\";\n\n // Returning this object from the innerFn has the same effect as\n // breaking out of the dispatch switch statement.\n var ContinueSentinel = {};\n\n // Dummy constructor functions that we use as the .constructor and\n // .constructor.prototype properties for functions that return Generator\n // objects. For full spec compliance, you may wish to configure your\n // minifier not to mangle the names of these two functions.\n function Generator() {}\n function GeneratorFunction() {}\n function GeneratorFunctionPrototype() {}\n\n // This is a polyfill for %IteratorPrototype% for environments that\n // don't natively support it.\n var IteratorPrototype = {};\n IteratorPrototype[iteratorSymbol] = function () {\n return this;\n };\n\n var getProto = Object.getPrototypeOf;\n var NativeIteratorPrototype = getProto && getProto(getProto(values([])));\n if (NativeIteratorPrototype &&\n NativeIteratorPrototype !== Op &&\n hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {\n // This environment has a native %IteratorPrototype%; use it instead\n // of the polyfill.\n IteratorPrototype = NativeIteratorPrototype;\n }\n\n var Gp = GeneratorFunctionPrototype.prototype =\n Generator.prototype = Object.create(IteratorPrototype);\n GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;\n GeneratorFunctionPrototype.constructor = GeneratorFunction;\n GeneratorFunction.displayName = define(\n GeneratorFunctionPrototype,\n toStringTagSymbol,\n \"GeneratorFunction\"\n );\n\n // Helper for defining the .next, .throw, and .return methods of the\n // Iterator interface in terms of a single ._invoke method.\n function defineIteratorMethods(prototype) {\n [\"next\", \"throw\", \"return\"].forEach(function(method) {\n define(prototype, method, function(arg) {\n return this._invoke(method, arg);\n });\n });\n }\n\n exports.isGeneratorFunction = function(genFun) {\n var ctor = typeof genFun === \"function\" && genFun.constructor;\n return ctor\n ? ctor === GeneratorFunction ||\n // For the native GeneratorFunction constructor, the best we can\n // do is to check its .name property.\n (ctor.displayName || ctor.name) === \"GeneratorFunction\"\n : false;\n };\n\n exports.mark = function(genFun) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);\n } else {\n genFun.__proto__ = GeneratorFunctionPrototype;\n define(genFun, toStringTagSymbol, \"GeneratorFunction\");\n }\n genFun.prototype = Object.create(Gp);\n return genFun;\n };\n\n // Within the body of any async function, `await x` is transformed to\n // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test\n // `hasOwn.call(value, \"__await\")` to determine if the yielded value is\n // meant to be awaited.\n exports.awrap = function(arg) {\n return { __await: arg };\n };\n\n function AsyncIterator(generator, PromiseImpl) {\n function invoke(method, arg, resolve, reject) {\n var record = tryCatch(generator[method], generator, arg);\n if (record.type === \"throw\") {\n reject(record.arg);\n } else {\n var result = record.arg;\n var value = result.value;\n if (value &&\n typeof value === \"object\" &&\n hasOwn.call(value, \"__await\")) {\n return PromiseImpl.resolve(value.__await).then(function(value) {\n invoke(\"next\", value, resolve, reject);\n }, function(err) {\n invoke(\"throw\", err, resolve, reject);\n });\n }\n\n return PromiseImpl.resolve(value).then(function(unwrapped) {\n // When a yielded Promise is resolved, its final value becomes\n // the .value of the Promise<{value,done}> result for the\n // current iteration.\n result.value = unwrapped;\n resolve(result);\n }, function(error) {\n // If a rejected Promise was yielded, throw the rejection back\n // into the async generator function so it can be handled there.\n return invoke(\"throw\", error, resolve, reject);\n });\n }\n }\n\n var previousPromise;\n\n function enqueue(method, arg) {\n function callInvokeWithMethodAndArg() {\n return new PromiseImpl(function(resolve, reject) {\n invoke(method, arg, resolve, reject);\n });\n }\n\n return previousPromise =\n // If enqueue has been called before, then we want to wait until\n // all previous Promises have been resolved before calling invoke,\n // so that results are always delivered in the correct order. If\n // enqueue has not been called before, then it is important to\n // call invoke immediately, without waiting on a callback to fire,\n // so that the async generator function has the opportunity to do\n // any necessary setup in a predictable way. This predictability\n // is why the Promise constructor synchronously invokes its\n // executor callback, and why async functions synchronously\n // execute code before the first await. Since we implement simple\n // async functions in terms of async generators, it is especially\n // important to get this right, even though it requires care.\n previousPromise ? previousPromise.then(\n callInvokeWithMethodAndArg,\n // Avoid propagating failures to Promises returned by later\n // invocations of the iterator.\n callInvokeWithMethodAndArg\n ) : callInvokeWithMethodAndArg();\n }\n\n // Define the unified helper method that is used to implement .next,\n // .throw, and .return (see defineIteratorMethods).\n this._invoke = enqueue;\n }\n\n defineIteratorMethods(AsyncIterator.prototype);\n AsyncIterator.prototype[asyncIteratorSymbol] = function () {\n return this;\n };\n exports.AsyncIterator = AsyncIterator;\n\n // Note that simple async functions are implemented on top of\n // AsyncIterator objects; they just return a Promise for the value of\n // the final result produced by the iterator.\n exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {\n if (PromiseImpl === void 0) PromiseImpl = Promise;\n\n var iter = new AsyncIterator(\n wrap(innerFn, outerFn, self, tryLocsList),\n PromiseImpl\n );\n\n return exports.isGeneratorFunction(outerFn)\n ? iter // If outerFn is a generator, return the full iterator.\n : iter.next().then(function(result) {\n return result.done ? result.value : iter.next();\n });\n };\n\n function makeInvokeMethod(innerFn, self, context) {\n var state = GenStateSuspendedStart;\n\n return function invoke(method, arg) {\n if (state === GenStateExecuting) {\n throw new Error(\"Generator is already running\");\n }\n\n if (state === GenStateCompleted) {\n if (method === \"throw\") {\n throw arg;\n }\n\n // Be forgiving, per 25.3.3.3.3 of the spec:\n // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume\n return doneResult();\n }\n\n context.method = method;\n context.arg = arg;\n\n while (true) {\n var delegate = context.delegate;\n if (delegate) {\n var delegateResult = maybeInvokeDelegate(delegate, context);\n if (delegateResult) {\n if (delegateResult === ContinueSentinel) continue;\n return delegateResult;\n }\n }\n\n if (context.method === \"next\") {\n // Setting context._sent for legacy support of Babel's\n // function.sent implementation.\n context.sent = context._sent = context.arg;\n\n } else if (context.method === \"throw\") {\n if (state === GenStateSuspendedStart) {\n state = GenStateCompleted;\n throw context.arg;\n }\n\n context.dispatchException(context.arg);\n\n } else if (context.method === \"return\") {\n context.abrupt(\"return\", context.arg);\n }\n\n state = GenStateExecuting;\n\n var record = tryCatch(innerFn, self, context);\n if (record.type === \"normal\") {\n // If an exception is thrown from innerFn, we leave state ===\n // GenStateExecuting and loop back for another invocation.\n state = context.done\n ? GenStateCompleted\n : GenStateSuspendedYield;\n\n if (record.arg === ContinueSentinel) {\n continue;\n }\n\n return {\n value: record.arg,\n done: context.done\n };\n\n } else if (record.type === \"throw\") {\n state = GenStateCompleted;\n // Dispatch the exception by looping back around to the\n // context.dispatchException(context.arg) call above.\n context.method = \"throw\";\n context.arg = record.arg;\n }\n }\n };\n }\n\n // Call delegate.iterator[context.method](context.arg) and handle the\n // result, either by returning a { value, done } result from the\n // delegate iterator, or by modifying context.method and context.arg,\n // setting context.delegate to null, and returning the ContinueSentinel.\n function maybeInvokeDelegate(delegate, context) {\n var method = delegate.iterator[context.method];\n if (method === undefined) {\n // A .throw or .return when the delegate iterator has no .throw\n // method always terminates the yield* loop.\n context.delegate = null;\n\n if (context.method === \"throw\") {\n // Note: [\"return\"] must be used for ES3 parsing compatibility.\n if (delegate.iterator[\"return\"]) {\n // If the delegate iterator has a return method, give it a\n // chance to clean up.\n context.method = \"return\";\n context.arg = undefined;\n maybeInvokeDelegate(delegate, context);\n\n if (context.method === \"throw\") {\n // If maybeInvokeDelegate(context) changed context.method from\n // \"return\" to \"throw\", let that override the TypeError below.\n return ContinueSentinel;\n }\n }\n\n context.method = \"throw\";\n context.arg = new TypeError(\n \"The iterator does not provide a 'throw' method\");\n }\n\n return ContinueSentinel;\n }\n\n var record = tryCatch(method, delegate.iterator, context.arg);\n\n if (record.type === \"throw\") {\n context.method = \"throw\";\n context.arg = record.arg;\n context.delegate = null;\n return ContinueSentinel;\n }\n\n var info = record.arg;\n\n if (! info) {\n context.method = \"throw\";\n context.arg = new TypeError(\"iterator result is not an object\");\n context.delegate = null;\n return ContinueSentinel;\n }\n\n if (info.done) {\n // Assign the result of the finished delegate to the temporary\n // variable specified by delegate.resultName (see delegateYield).\n context[delegate.resultName] = info.value;\n\n // Resume execution at the desired location (see delegateYield).\n context.next = delegate.nextLoc;\n\n // If context.method was \"throw\" but the delegate handled the\n // exception, let the outer generator proceed normally. If\n // context.method was \"next\", forget context.arg since it has been\n // \"consumed\" by the delegate iterator. If context.method was\n // \"return\", allow the original .return call to continue in the\n // outer generator.\n if (context.method !== \"return\") {\n context.method = \"next\";\n context.arg = undefined;\n }\n\n } else {\n // Re-yield the result returned by the delegate method.\n return info;\n }\n\n // The delegate iterator is finished, so forget it and continue with\n // the outer generator.\n context.delegate = null;\n return ContinueSentinel;\n }\n\n // Define Generator.prototype.{next,throw,return} in terms of the\n // unified ._invoke helper method.\n defineIteratorMethods(Gp);\n\n define(Gp, toStringTagSymbol, \"Generator\");\n\n // A Generator should always return itself as the iterator object when the\n // @@iterator function is called on it. Some browsers' implementations of the\n // iterator prototype chain incorrectly implement this, causing the Generator\n // object to not be returned from this call. This ensures that doesn't happen.\n // See https://github.com/facebook/regenerator/issues/274 for more details.\n Gp[iteratorSymbol] = function() {\n return this;\n };\n\n Gp.toString = function() {\n return \"[object Generator]\";\n };\n\n function pushTryEntry(locs) {\n var entry = { tryLoc: locs[0] };\n\n if (1 in locs) {\n entry.catchLoc = locs[1];\n }\n\n if (2 in locs) {\n entry.finallyLoc = locs[2];\n entry.afterLoc = locs[3];\n }\n\n this.tryEntries.push(entry);\n }\n\n function resetTryEntry(entry) {\n var record = entry.completion || {};\n record.type = \"normal\";\n delete record.arg;\n entry.completion = record;\n }\n\n function Context(tryLocsList) {\n // The root entry object (effectively a try statement without a catch\n // or a finally block) gives us a place to store values thrown from\n // locations where there is no enclosing try statement.\n this.tryEntries = [{ tryLoc: \"root\" }];\n tryLocsList.forEach(pushTryEntry, this);\n this.reset(true);\n }\n\n exports.keys = function(object) {\n var keys = [];\n for (var key in object) {\n keys.push(key);\n }\n keys.reverse();\n\n // Rather than returning an object with a next method, we keep\n // things simple and return the next function itself.\n return function next() {\n while (keys.length) {\n var key = keys.pop();\n if (key in object) {\n next.value = key;\n next.done = false;\n return next;\n }\n }\n\n // To avoid creating an additional object, we just hang the .value\n // and .done properties off the next function object itself. This\n // also ensures that the minifier will not anonymize the function.\n next.done = true;\n return next;\n };\n };\n\n function values(iterable) {\n if (iterable) {\n var iteratorMethod = iterable[iteratorSymbol];\n if (iteratorMethod) {\n return iteratorMethod.call(iterable);\n }\n\n if (typeof iterable.next === \"function\") {\n return iterable;\n }\n\n if (!isNaN(iterable.length)) {\n var i = -1, next = function next() {\n while (++i < iterable.length) {\n if (hasOwn.call(iterable, i)) {\n next.value = iterable[i];\n next.done = false;\n return next;\n }\n }\n\n next.value = undefined;\n next.done = true;\n\n return next;\n };\n\n return next.next = next;\n }\n }\n\n // Return an iterator with no values.\n return { next: doneResult };\n }\n exports.values = values;\n\n function doneResult() {\n return { value: undefined, done: true };\n }\n\n Context.prototype = {\n constructor: Context,\n\n reset: function(skipTempReset) {\n this.prev = 0;\n this.next = 0;\n // Resetting context._sent for legacy support of Babel's\n // function.sent implementation.\n this.sent = this._sent = undefined;\n this.done = false;\n this.delegate = null;\n\n this.method = \"next\";\n this.arg = undefined;\n\n this.tryEntries.forEach(resetTryEntry);\n\n if (!skipTempReset) {\n for (var name in this) {\n // Not sure about the optimal order of these conditions:\n if (name.charAt(0) === \"t\" &&\n hasOwn.call(this, name) &&\n !isNaN(+name.slice(1))) {\n this[name] = undefined;\n }\n }\n }\n },\n\n stop: function() {\n this.done = true;\n\n var rootEntry = this.tryEntries[0];\n var rootRecord = rootEntry.completion;\n if (rootRecord.type === \"throw\") {\n throw rootRecord.arg;\n }\n\n return this.rval;\n },\n\n dispatchException: function(exception) {\n if (this.done) {\n throw exception;\n }\n\n var context = this;\n function handle(loc, caught) {\n record.type = \"throw\";\n record.arg = exception;\n context.next = loc;\n\n if (caught) {\n // If the dispatched exception was caught by a catch block,\n // then let that catch block handle the exception normally.\n context.method = \"next\";\n context.arg = undefined;\n }\n\n return !! caught;\n }\n\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n var record = entry.completion;\n\n if (entry.tryLoc === \"root\") {\n // Exception thrown outside of any try block that could handle\n // it, so set the completion value of the entire function to\n // throw the exception.\n return handle(\"end\");\n }\n\n if (entry.tryLoc <= this.prev) {\n var hasCatch = hasOwn.call(entry, \"catchLoc\");\n var hasFinally = hasOwn.call(entry, \"finallyLoc\");\n\n if (hasCatch && hasFinally) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n } else if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else if (hasCatch) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n }\n\n } else if (hasFinally) {\n if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else {\n throw new Error(\"try statement without catch or finally\");\n }\n }\n }\n },\n\n abrupt: function(type, arg) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc <= this.prev &&\n hasOwn.call(entry, \"finallyLoc\") &&\n this.prev < entry.finallyLoc) {\n var finallyEntry = entry;\n break;\n }\n }\n\n if (finallyEntry &&\n (type === \"break\" ||\n type === \"continue\") &&\n finallyEntry.tryLoc <= arg &&\n arg <= finallyEntry.finallyLoc) {\n // Ignore the finally entry if control is not jumping to a\n // location outside the try/catch block.\n finallyEntry = null;\n }\n\n var record = finallyEntry ? finallyEntry.completion : {};\n record.type = type;\n record.arg = arg;\n\n if (finallyEntry) {\n this.method = \"next\";\n this.next = finallyEntry.finallyLoc;\n return ContinueSentinel;\n }\n\n return this.complete(record);\n },\n\n complete: function(record, afterLoc) {\n if (record.type === \"throw\") {\n throw record.arg;\n }\n\n if (record.type === \"break\" ||\n record.type === \"continue\") {\n this.next = record.arg;\n } else if (record.type === \"return\") {\n this.rval = this.arg = record.arg;\n this.method = \"return\";\n this.next = \"end\";\n } else if (record.type === \"normal\" && afterLoc) {\n this.next = afterLoc;\n }\n\n return ContinueSentinel;\n },\n\n finish: function(finallyLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.finallyLoc === finallyLoc) {\n this.complete(entry.completion, entry.afterLoc);\n resetTryEntry(entry);\n return ContinueSentinel;\n }\n }\n },\n\n \"catch\": function(tryLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc === tryLoc) {\n var record = entry.completion;\n if (record.type === \"throw\") {\n var thrown = record.arg;\n resetTryEntry(entry);\n }\n return thrown;\n }\n }\n\n // The context.catch method must only be called with a location\n // argument that corresponds to a known catch block.\n throw new Error(\"illegal catch attempt\");\n },\n\n delegateYield: function(iterable, resultName, nextLoc) {\n this.delegate = {\n iterator: values(iterable),\n resultName: resultName,\n nextLoc: nextLoc\n };\n\n if (this.method === \"next\") {\n // Deliberately forget the last sent value so that we don't\n // accidentally pass it on to the delegate.\n this.arg = undefined;\n }\n\n return ContinueSentinel;\n }\n };\n\n // Regardless of whether this script is executing as a CommonJS module\n // or not, return the runtime object so that we can declare the variable\n // regeneratorRuntime in the outer scope, which allows this module to be\n // injected easily by `bin/regenerator --include-runtime script.js`.\n return exports;\n\n}(\n // If this script is executing as a CommonJS module, use module.exports\n // as the regeneratorRuntime namespace. Otherwise create a new empty\n // object. Either way, the resulting object will be used to initialize\n // the regeneratorRuntime variable at the top of this file.\n typeof module === \"object\" ? module.exports : {}\n));\n\ntry {\n regeneratorRuntime = runtime;\n} catch (accidentalStrictMode) {\n // This module should not be running in strict mode, so the above\n // assignment should always work unless something is misconfigured. Just\n // in case runtime.js accidentally runs in strict mode, we can escape\n // strict mode using a global Function call. This could conceivably fail\n // if a Content Security Policy forbids using Function, but in that case\n // the proper solution is to fix the accidental strict mode problem. If\n // you've misconfigured your bundler to force strict mode and applied a\n // CSP to forbid Function, and you're not willing to fix either of those\n // problems, please detail your unique predicament in a GitHub issue.\n Function(\"r\", \"regeneratorRuntime = r\")(runtime);\n}\n","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\n/**\r\n * Basic authentication stages used to determine\r\n * appropriate action after redirect occurs\r\n */\r\nexport const AppStages = {\r\n SIGN_IN: \"sign_in\",\r\n SIGN_OUT: \"sign_out\",\r\n ACQUIRE_TOKEN: \"acquire_token\",\r\n};\r\n\r\n/**\r\n * String constants related to AAD Authority\r\n */\r\nexport const AADAuthorityConstants = {\r\n COMMON: \"common\",\r\n ORGANIZATIONS: \"organizations\",\r\n CONSUMERS: \"consumers\"\r\n}\r\n\r\n/**\r\n * String constants related to AAD Authority\r\n */\r\nexport const KeyVaultCredentialTypes = {\r\n SECRET: \"secret\",\r\n CERTIFICATE: \"certificate\",\r\n}\r\n\r\n/**\r\n * Constants used in access control scenarios\r\n */\r\nexport const AccessConstants = {\r\n GROUPS: \"groups\",\r\n ROLES: \"roles\",\r\n CLAIM_NAMES: \"_claim_name\",\r\n CLAIM_SOURCES: \"_claim_sources\",\r\n PAGINATION_LINK: \"@odata.nextLink\",\r\n GRAPH_MEMBERS_ENDPOINT: \"https://graph.microsoft.com/v1.0/me/memberOf\",\r\n GRAPH_MEMBER_SCOPES: \"User.Read GroupMember.Read.All\"\r\n};\r\n\r\nexport const InfoMessages = {\r\n REQUEST_FOR_RESOURCE: \"Request made to web API\",\r\n OVERAGE_OCCURRED: \"User has too many groups. Groups overage claim occurred\"\r\n}\r\n\r\n/**\r\n * Various error constants\r\n */\r\nexport const ErrorMessages = {\r\n NOT_PERMITTED: \"Not permitted\",\r\n INVALID_TOKEN: \"Invalid token\",\r\n CANNOT_DETERMINE_APP_STAGE: \"Cannot determine application stage\",\r\n CANNOT_VALIDATE_TOKEN: \"Cannot validate token\",\r\n NONCE_MISMATCH: \"Nonce does not match\",\r\n INTERACTION_REQUIRED: \"interaction_required\",\r\n TOKEN_ACQUISITION_FAILED: \"Token acquisition failed\",\r\n AUTH_CODE_NOT_OBTAINED: \"Authorization code cannot be obtained\",\r\n TOKEN_NOT_FOUND: \"No token found\",\r\n TOKEN_NOT_DECODED: \"Token cannot be decoded\",\r\n TOKEN_NOT_VERIFIED: \"Token cannot be verified\",\r\n KEYS_NOT_OBTAINED: \"Signing keys cannot be obtained\",\r\n STATE_NOT_FOUND: \"State not found\",\r\n USER_HAS_NO_ROLE: \"User does not have any roles\",\r\n USER_NOT_IN_ROLE: \"User does not have this role\",\r\n USER_HAS_NO_GROUP: \"User does not have any groups\",\r\n USER_NOT_IN_GROUP: \"User does not have this group\",\r\n METHOD_NOT_ALLOWED: \"Method not allowed for this route\",\r\n RULE_NOT_FOUND: \"No rule found for this route\",\r\n SESSION_NOT_FOUND: \"No session found for this request\",\r\n KEY_VAULT_CONFIG_NOT_FOUND: \"No coordinates found for Key Vault\"\r\n};\r\n\r\nexport const ConfigurationErrorMessages = {\r\n NO_CLIENT_ID: \"No clientId provided!\",\r\n INVALID_CLIENT_ID: \"Invalid clientId!\",\r\n NO_TENANT_INFO: \"No tenant info provided!\",\r\n INVALID_TENANT_INFO: \"Invalid tenant info!\",\r\n NO_CLIENT_CREDENTIAL: \"No client credential provided!\",\r\n NO_REDIRECT_URI: \"No redirect URI provided!\",\r\n NO_ERROR_ROUTE: \"No error route provided!\",\r\n NO_UNAUTHORIZED_ROUTE: \"No unauthorized route provided!\"\r\n}\r\n\r\n/**\r\n * For more information, visit: https://login.microsoftonline.com/error\r\n */\r\nexport const ErrorCodes = {\r\n 65001: \"AADSTS65001\", // consent required\r\n};","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { \r\n UrlString, \r\n StringUtils,\r\n Constants, \r\n} from \"@azure/msal-common\";\r\n\r\nimport { \r\n ICachePlugin,\r\n Configuration,\r\n LogLevel \r\n} from \"@azure/msal-node\";\r\n\r\nimport { AppSettings } from \"./Types\";\r\n\r\nimport { \r\n AADAuthorityConstants, \r\n ConfigurationErrorMessages \r\n} from \"./Constants\";\r\n\r\nexport class ConfigurationUtils {\r\n\r\n /**\r\n * Validates the fields in the configuration file\r\n * @param {AppSettings} config: configuration object\r\n * @returns {void}\r\n */\r\n static validateAppSettings(config: AppSettings): void {\r\n if (StringUtils.isEmpty(config.appCredentials.clientId)) {\r\n throw new Error(ConfigurationErrorMessages.NO_CLIENT_ID);\r\n } else if (!ConfigurationUtils.isGuid(config.appCredentials.clientId)) {\r\n throw new Error(ConfigurationErrorMessages.INVALID_CLIENT_ID);\r\n }\r\n\r\n if (StringUtils.isEmpty(config.appCredentials.tenantId)) {\r\n throw new Error(ConfigurationErrorMessages.NO_TENANT_INFO);\r\n } else if (!ConfigurationUtils.isGuid(config.appCredentials.tenantId) && !Object.values(AADAuthorityConstants).includes(config.appCredentials.tenantId)) {\r\n throw new Error(ConfigurationErrorMessages.INVALID_TENANT_INFO);\r\n }\r\n\r\n if (StringUtils.isEmpty(config.appCredentials.clientSecret) && !config.appCredentials.clientCertificate) {\r\n throw new Error(ConfigurationErrorMessages.NO_CLIENT_CREDENTIAL);\r\n }\r\n\r\n if (StringUtils.isEmpty(config.authRoutes.redirect)) {\r\n throw new Error(ConfigurationErrorMessages.NO_REDIRECT_URI);\r\n }\r\n\r\n if (StringUtils.isEmpty(config.authRoutes.error)) {\r\n throw new Error(ConfigurationErrorMessages.NO_ERROR_ROUTE);\r\n }\r\n\r\n if (StringUtils.isEmpty(config.authRoutes.unauthorized)) {\r\n throw new Error(ConfigurationErrorMessages.NO_UNAUTHORIZED_ROUTE);\r\n }\r\n };\r\n\r\n\r\n /**\r\n * Maps the custom configuration object to configuration\r\n * object expected by MSAL Node ConfidentialClientApplication class\r\n * @param {AppSettings} config: configuration object\r\n * @param {ICachePlugin} cachePlugin: persistent cache implementation\r\n * @returns {Configuration}\r\n */\r\n static getMsalConfiguration(config: AppSettings, cachePlugin: ICachePlugin = null): Configuration {\r\n return {\r\n auth: {\r\n clientId: config.appCredentials.clientId,\r\n authority: config.b2cPolicies ?\r\n Object.entries(config.b2cPolicies)[0][1][\"authority\"]\r\n :\r\n `https://${Constants.DEFAULT_AUTHORITY_HOST}/${config.appCredentials.tenantId}`,\r\n ...(config.appCredentials.hasOwnProperty(\"clientSecret\")) && { clientSecret: config.appCredentials.clientSecret },\r\n ...(config.appCredentials.hasOwnProperty(\"clientCertificate\")) && { clientCertificate: config.appCredentials.clientCertificate },\r\n knownAuthorities: config.b2cPolicies ?\r\n [UrlString.getDomainFromUrl(Object.entries(config.b2cPolicies)[0][1][\"authority\"])] // in B2C scenarios\r\n :\r\n [],\r\n },\r\n cache: {\r\n cachePlugin,\r\n },\r\n system: {\r\n loggerOptions: {\r\n loggerCallback: (logLevel, message, containsPii) => {\r\n if (containsPii) {\r\n return;\r\n }\r\n switch (logLevel) {\r\n case LogLevel.Error:\r\n console.error(message);\r\n return;\r\n case LogLevel.Info:\r\n console.info(message);\r\n return;\r\n case LogLevel.Verbose:\r\n console.debug(message);\r\n return;\r\n case LogLevel.Warning:\r\n console.warn(message);\r\n return;\r\n }\r\n },\r\n piiLoggingEnabled: false,\r\n logLevel: LogLevel.Verbose,\r\n },\r\n },\r\n };\r\n };\r\n\r\n /**\r\n * verifies if a string is GUID\r\n * @param guid\r\n */\r\n static isGuid(guid: string): boolean {\r\n const regexGuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\r\n return regexGuid.test(guid);\r\n }\r\n}\r\n","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { LogLevel } from \"@azure/msal-common\"\r\n\r\nexport class Logger {\r\n\r\n /**\r\n * Log an error\r\n * @param {string} log\r\n * @returns {void}\r\n */\r\n static logError(log: string): void {\r\n console.error(this.logMessage(log));\r\n }\r\n\r\n /**\r\n * Log a warning\r\n * @param {string} log\r\n * @returns {void}\r\n */\r\n static logWarning(log: string): void {\r\n console.warn(this.logMessage(log));\r\n }\r\n\r\n /**\r\n * Log anything\r\n * @param {string} log\r\n * @returns {void}\r\n */\r\n static logInfo(log: string): void {\r\n console.info(this.logMessage(log));\r\n }\r\n\r\n /**\r\n * Log message with required options.\r\n * @param {string} logMessage \r\n * @returns {string}\r\n */\r\n private static logMessage(logMessage: string): string {\r\n const timestamp = new Date().toUTCString();\r\n\r\n let logHeader: string = `[${timestamp}]`;\r\n\r\n const log = `${logHeader} : @azure-samples/msal-express-wrapper@0.1.0 : ${LogLevel[LogLevel.Verbose]} - ${logMessage}`;\r\n return log;\r\n }\r\n\r\n}","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport jwt from \"jsonwebtoken\";\r\nimport jwksClient from \"jwks-rsa\";\r\n\r\nimport { \r\n StringUtils, \r\n Constants, \r\n TokenClaims \r\n} from \"@azure/msal-common\";\r\n\r\nimport { Configuration } from \"@azure/msal-node\";\r\n\r\nimport { Logger } from \"./Logger\";\r\n\r\nimport { \r\n AppSettings,\r\n Resource, \r\n IdTokenClaims, \r\n AccessTokenClaims \r\n} from \"./Types\";\r\n\r\nimport { \r\n ErrorMessages, \r\n AADAuthorityConstants \r\n} from \"./Constants\";\r\n\r\nexport class TokenValidator {\r\n private appSettings: AppSettings;\r\n private msalConfig: Configuration;\r\n\r\n /**\r\n * @param {AppSettings} appSettings \r\n * @param {Configuration} msalConfig\r\n * @constructor\r\n */\r\n constructor(appSettings: AppSettings, msalConfig: Configuration) {\r\n this.appSettings = appSettings;\r\n this.msalConfig = msalConfig;\r\n }\r\n\r\n /**\r\n * Verifies a given token's signature using jwks-rsa\r\n * @param {string} authToken \r\n * @returns {Promise}\r\n */\r\n async verifyTokenSignature(authToken: string): Promise {\r\n if (StringUtils.isEmpty(authToken)) {\r\n Logger.logError(ErrorMessages.TOKEN_NOT_FOUND);\r\n return false;\r\n }\r\n\r\n // we will first decode to get kid parameter in header\r\n let decodedToken;\r\n\r\n try {\r\n decodedToken = jwt.decode(authToken, { complete: true });\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.TOKEN_NOT_DECODED);\r\n console.log(error);\r\n return false;\r\n }\r\n\r\n // obtains signing keys from discovery endpoint\r\n let keys;\r\n\r\n try {\r\n keys = await this.getSigningKeys(decodedToken.header, decodedToken.payload.tid);\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.KEYS_NOT_OBTAINED);\r\n console.log(error);\r\n return false;\r\n }\r\n\r\n // verify the signature at header section using keys\r\n let verifiedToken: TokenClaims;\r\n\r\n try {\r\n verifiedToken = jwt.verify(authToken, keys);\r\n\r\n /**\r\n * if a multiplexer was used in place of tenantId i.e. if the app\r\n * is multi-tenant, the tenantId should be obtained from the user\"s\r\n * token\"s tid claim for verification purposes\r\n */\r\n if (\r\n this.appSettings.appCredentials.tenantId === AADAuthorityConstants.COMMON ||\r\n this.appSettings.appCredentials.tenantId === AADAuthorityConstants.ORGANIZATIONS ||\r\n this.appSettings.appCredentials.tenantId === AADAuthorityConstants.CONSUMERS\r\n ) {\r\n this.appSettings.appCredentials.tenantId = decodedToken.payload.tid;\r\n }\r\n\r\n return verifiedToken;\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.TOKEN_NOT_VERIFIED);\r\n console.log(error);\r\n return false;\r\n }\r\n };\r\n\r\n /**\r\n * Verifies the access token for signature\r\n * @param {string} idToken: raw Id token\r\n * @returns {Promise}\r\n */\r\n async validateIdToken(idToken: string): Promise {\r\n try {\r\n const verifiedToken = await this.verifyTokenSignature(idToken);\r\n\r\n if (verifiedToken) {\r\n return this.validateIdTokenClaims(verifiedToken as IdTokenClaims);\r\n } else {\r\n return false;\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n return false;\r\n }\r\n };\r\n\r\n /**\r\n * Validates the id token for a set of claims\r\n * @param {IdTokenClaims} idTokenClaims: decoded id token claims\r\n * @returns {boolean}\r\n */\r\n validateIdTokenClaims(idTokenClaims: IdTokenClaims): boolean {\r\n const now = Math.round(new Date().getTime() / 1000); // in UNIX format\r\n\r\n /**\r\n * At the very least, check for issuer, audience, issue and expiry dates.\r\n * For more information on validating id tokens, visit:\r\n * https://docs.microsoft.com/azure/active-directory/develop/id-tokens#validating-an-id_token\r\n */\r\n const checkIssuer = idTokenClaims.iss.includes(this.appSettings.appCredentials.tenantId) ? true : false;\r\n const checkAudience = idTokenClaims.aud === this.msalConfig.auth.clientId ? true : false;\r\n const checkTimestamp = idTokenClaims.iat <= now && idTokenClaims.exp >= now ? true : false;\r\n\r\n return checkIssuer && checkAudience && checkTimestamp;\r\n };\r\n\r\n /**\r\n * Verifies the access token for signature\r\n * @param {string} accessToken: raw JWT token\r\n * @param {string} protectedRoute: used for checking scope\r\n * @returns {Promise}\r\n */\r\n async verifyAccessTokenSignature(accessToken: string, protectedRoute: string): Promise {\r\n try {\r\n const verifiedToken = await this.verifyTokenSignature(accessToken);\r\n\r\n if (verifiedToken) {\r\n return this.validateAccessTokenClaims(verifiedToken as AccessTokenClaims, protectedRoute);\r\n } else {\r\n return false;\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n return false;\r\n }\r\n };\r\n\r\n /**\r\n * Validates the access token for a set of claims\r\n * @param {TokenClaims} verifiedToken: token with a verified signature\r\n * @param {string} protectedRoute: route where this token is required to access\r\n * @returns {boolean}\r\n */\r\n validateAccessTokenClaims(verifiedToken: AccessTokenClaims, protectedRoute: string): boolean {\r\n const now = Math.round(new Date().getTime() / 1000); // in UNIX format\r\n\r\n /**\r\n * At the very least, validate the token with respect to issuer, audience, scope\r\n * and timestamp, though implementation and extent vary. For more information, visit:\r\n * https://docs.microsoft.com/azure/active-directory/develop/access-tokens#validating-tokens\r\n */\r\n const checkIssuer = verifiedToken.iss.includes(this.appSettings.appCredentials.tenantId) ? true : false;\r\n const checkTimestamp = verifiedToken.iat <= now && verifiedToken.iat >= now ? true : false;\r\n\r\n const checkAudience = verifiedToken.aud === this.appSettings.appCredentials.clientId ||\r\n verifiedToken.aud === \"api://\" + this.appSettings.appCredentials.clientId ? true : false;\r\n\r\n const checkScopes = Object.values(this.appSettings.ownedResources).find((resource: Resource) => resource.endpoint === protectedRoute)\r\n .scopes.every(scp => verifiedToken.scp.includes(scp));\r\n\r\n return checkAudience && checkIssuer && checkTimestamp && checkScopes;\r\n };\r\n\r\n /**\r\n * Fetches signing keys of an access token\r\n * from the authority discovery endpoint\r\n * @param {Object} header: token header\r\n * @param {string} tid: tenant id\r\n * @returns {Promise}\r\n */\r\n private async getSigningKeys(header, tid: string): Promise {\r\n let jwksUri;\r\n\r\n // Check if a B2C application i.e. app has b2cPolicies\r\n if (this.appSettings.b2cPolicies) {\r\n jwksUri = `${this.msalConfig.auth.authority}/discovery/v2.0/keys`;\r\n } else {\r\n jwksUri = `https://${Constants.DEFAULT_AUTHORITY_HOST}/${tid}/discovery/v2.0/keys`;\r\n }\r\n\r\n const client = jwksClient({\r\n jwksUri: jwksUri,\r\n });\r\n\r\n return (await client.getSigningKeyAsync(header.kid)).getPublicKey();\r\n };\r\n}\r\n","import { CertificateClient, KeyVaultCertificate } from \"@azure/keyvault-certificates\";\r\nimport { DefaultAzureCredential } from \"@azure/identity\";\r\nimport { KeyVaultSecret, SecretClient } from \"@azure/keyvault-secrets\";\r\n\r\nimport { AppSettings } from \"./Types\";\r\nimport { KeyVaultCredentialTypes } from \"./Constants\";\r\n\r\nexport class KeyVaultManager {\r\n\r\n /**\r\n * Fetches credentials from Key Vault and updates appSettings\r\n * @param {AppSettings} config \r\n * @returns {Promise}\r\n */\r\n async getCredentialFromKeyVault(config: AppSettings): Promise {\r\n\r\n const credential = new DefaultAzureCredential();\r\n\r\n if (!config.appCredentials.keyVaultCredential) {\r\n return config\r\n }\r\n\r\n switch (config.appCredentials.keyVaultCredential.credentialType) {\r\n case KeyVaultCredentialTypes.SECRET: {\r\n try {\r\n const secretResponse = await this.getSecretCredential(config, credential);\r\n config.appCredentials.clientSecret = secretResponse.value;\r\n return config;\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n break;\r\n }\r\n\r\n case KeyVaultCredentialTypes.CERTIFICATE: {\r\n try {\r\n const certificateResponse = await this.getCertificateCredential(config, credential);\r\n const secretResponse = await this.getSecretCredential(config, credential);\r\n\r\n config.appCredentials.clientCertificate = {\r\n thumbprint: certificateResponse.properties.x509Thumbprint.toString(),\r\n privateKey: secretResponse.value.split('-----BEGIN CERTIFICATE-----\\n')[0]\r\n }\r\n return config;\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n break;\r\n }\r\n\r\n default:\r\n break;\r\n }\r\n };\r\n\r\n /**\r\n * Gets a certificate credential from Key Vault\r\n * @param {AppSettings} config \r\n * @param {DefaultAzureCredential} credential \r\n * @returns {Promise}\r\n */\r\n async getCertificateCredential(config: AppSettings, credential: DefaultAzureCredential): Promise {\r\n\r\n // Initialize secretClient with credentials\r\n const secretClient = new CertificateClient(config.appCredentials.keyVaultCredential.keyVaultUrl, credential);\r\n\r\n try {\r\n const keyVaultCertificate = await secretClient.getCertificate(config.appCredentials.keyVaultCredential.credentialName);\r\n return keyVaultCertificate;\r\n } catch (error) {\r\n console.log(error);\r\n return error;\r\n }\r\n }\r\n\r\n /**\r\n * Gets a secret credential from Key Vault\r\n * @param {AppSettings} config \r\n * @param {DefaultAzureCredential} credential \r\n * @returns {Promise}\r\n */\r\n async getSecretCredential(config: AppSettings, credential: DefaultAzureCredential): Promise {\r\n\r\n // Initialize secretClient with credentials\r\n const secretClient = new SecretClient(config.appCredentials.keyVaultCredential.keyVaultUrl, credential);\r\n\r\n try {\r\n const keyVaultSecret = await secretClient.getSecret(config.appCredentials.keyVaultCredential.credentialName);\r\n return keyVaultSecret;\r\n } catch (error) {\r\n console.log(error);\r\n return error;\r\n }\r\n }\r\n}","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport axios, { AxiosResponse, AxiosRequestConfig } from \"axios\";\r\nimport { StringUtils } from \"@azure/msal-common\";\r\n\r\nimport { \r\n AccessConstants, \r\n InfoMessages, \r\n ErrorMessages \r\n} from \"./Constants\";\r\n\r\nimport { Logger } from \"./Logger\";\r\n\r\nexport class FetchManager {\r\n\r\n /**\r\n * Calls a resource endpoint with a raw access token\r\n * using the authorization bearer token scheme\r\n * @param {string} endpoint \r\n * @param {string} accessToken \r\n * @returns {Promise}\r\n */\r\n static callApiEndpoint = async (endpoint: string, accessToken: string): Promise => {\r\n\r\n if (StringUtils.isEmpty(accessToken)) {\r\n throw new Error(ErrorMessages.TOKEN_NOT_FOUND)\r\n }\r\n\r\n const options: AxiosRequestConfig = {\r\n headers: {\r\n Authorization: `Bearer ${accessToken}`\r\n }\r\n };\r\n\r\n try {\r\n Logger.logInfo(InfoMessages.REQUEST_FOR_RESOURCE);\r\n const response: AxiosResponse = await axios.get(endpoint, options);\r\n return response.data;\r\n } catch (error) {\r\n console.log(error)\r\n return error;\r\n }\r\n }\r\n\r\n /**\r\n * Handles queries against Microsoft Graph that return multiple pages of data \r\n * @param {string} accessToken: access token required by endpoint \r\n * @param {string} nextPage: next page link\r\n * @param {Array} data: stores data from each page\r\n * @returns {Promise}\r\n */\r\n static handlePagination = async (accessToken: string, nextPage: string, data: string[] = []): Promise => {\r\n\r\n try {\r\n const graphResponse = await FetchManager.callApiEndpoint(nextPage, accessToken);\r\n graphResponse[\"value\"].map((v) => data.push(v.id));\r\n \r\n if (graphResponse[AccessConstants.PAGINATION_LINK]) {\r\n return await FetchManager.handlePagination(accessToken, graphResponse[AccessConstants.PAGINATION_LINK], data)\r\n } else {\r\n return data;\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n return error;\r\n }\r\n \r\n }\r\n\r\n}\r\n","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { Request } from \"express\";\r\nimport { IUri, UrlString } from \"@azure/msal-common\";\r\n\r\nexport class UrlUtils {\r\n /**\r\n * Gets the absolute URL from a given request and path string\r\n * @param {Request} req: express request object \r\n * @param {string} url: a given URL\r\n * @returns {string}\r\n */\r\n static ensureAbsoluteUrl = (req: Request, url: string): string => {\r\n const urlComponents: IUri = new UrlString(url).getUrlComponents();\r\n\r\n if (!urlComponents.Protocol) {\r\n if (!urlComponents.HostNameAndPort) {\r\n return req.protocol + \"://\" + req.get(\"host\") + url;\r\n }\r\n return req.protocol + \"://\" + url;\r\n } else {\r\n return url;\r\n }\r\n };\r\n}\r\n","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\nimport express from \"express\";\r\n\r\nimport {\r\n RequestHandler,\r\n Request,\r\n Response,\r\n NextFunction,\r\n Router\r\n} from \"express\";\r\n\r\nimport {\r\n InteractionRequiredAuthError,\r\n OIDC_DEFAULT_SCOPES,\r\n PromptValue,\r\n StringUtils,\r\n} from \"@azure/msal-common\";\r\n\r\nimport {\r\n ConfidentialClientApplication,\r\n Configuration,\r\n AccountInfo,\r\n ICachePlugin,\r\n CryptoProvider,\r\n AuthorizationUrlRequest,\r\n AuthorizationCodeRequest,\r\n SilentFlowRequest,\r\n OnBehalfOfRequest,\r\n} from \"@azure/msal-node\";\r\n\r\nimport { ConfigurationUtils } from \"./ConfigurationUtils\";\r\nimport { TokenValidator } from \"./TokenValidator\";\r\nimport { KeyVaultManager } from \"./KeyVaultManager\";\r\nimport { FetchManager } from \"./FetchManager\";\r\nimport { UrlUtils } from \"./UrlUtils\";\r\nimport { Logger } from \"./Logger\";\r\n\r\nimport {\r\n Resource,\r\n AppSettings,\r\n AuthCodeParams,\r\n InitializationOptions,\r\n TokenRequestOptions,\r\n GuardOptions,\r\n AccessRule,\r\n SignInOptions,\r\n SignOutOptions,\r\n HandleRedirectOptions\r\n} from \"./Types\";\r\n\r\nimport {\r\n AppStages,\r\n ErrorMessages,\r\n AccessConstants,\r\n InfoMessages\r\n} from \"./Constants\";\r\n\r\n/**\r\n * A simple wrapper around MSAL Node ConfidentialClientApplication object.\r\n * It offers a collection of middleware and utility methods that automate\r\n * basic authentication and authorization tasks in Express MVC web apps and\r\n * RESTful APIs (coming soon).\r\n */\r\nexport class AuthProvider {\r\n appSettings: AppSettings;\r\n private msalConfig: Configuration;\r\n private cryptoProvider: CryptoProvider;\r\n private tokenValidator: TokenValidator;\r\n private msalClient: ConfidentialClientApplication;\r\n\r\n /**\r\n * @param {AppSettings} appSettings\r\n * @param {ICachePlugin} cache: cachePlugin\r\n * @constructor\r\n */\r\n constructor(appSettings: AppSettings, cache?: ICachePlugin) {\r\n ConfigurationUtils.validateAppSettings(appSettings);\r\n this.appSettings = appSettings;\r\n\r\n this.msalConfig = ConfigurationUtils.getMsalConfiguration(appSettings, cache);\r\n this.msalClient = new ConfidentialClientApplication(this.msalConfig);\r\n\r\n this.tokenValidator = new TokenValidator(this.appSettings, this.msalConfig);\r\n this.cryptoProvider = new CryptoProvider();\r\n }\r\n\r\n /**\r\n * Asynchronously builds authProvider object with credentials fetched from Key Vault\r\n * @param {AppSettings} appSettings\r\n * @param {ICachePlugin} cache: cachePlugin\r\n * @returns \r\n */\r\n static async buildAsync(appSettings: AppSettings, cache?: ICachePlugin): Promise {\r\n try {\r\n const keyVault = new KeyVaultManager();\r\n const appSettingsWithKeyVaultCredentials = await keyVault.getCredentialFromKeyVault(appSettings);\r\n const authProvider = new AuthProvider(appSettingsWithKeyVaultCredentials, cache);\r\n return authProvider;\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n }\r\n\r\n /**\r\n * Initialize AuthProvider and set default routes and handlers\r\n * @param {InitializationOptions} options\r\n * @returns {Router}\r\n */\r\n initialize = (options?: InitializationOptions): Router => {\r\n\r\n // TODO: initialize app defaults\r\n\r\n const appRouter = express.Router();\r\n\r\n // handle redirect\r\n appRouter.get(this.appSettings.authRoutes.redirect, this.handleRedirect());\r\n\r\n if (this.appSettings.authRoutes.frontChannelLogout) {\r\n /**\r\n * Expose front-channel logout route. For more information, visit: \r\n * https://docs.microsoft.com/azure/active-directory/develop/v2-protocols-oidc#single-sign-out\r\n */\r\n appRouter.get(this.appSettings.authRoutes.frontChannelLogout, (req, res, next) => {\r\n req.session.destroy(() => {\r\n res.sendStatus(200);\r\n });\r\n });\r\n }\r\n\r\n return appRouter;\r\n }\r\n\r\n // ========== ROUTE HANDLERS ===========\r\n\r\n /**\r\n * Initiates sign in flow\r\n * @param {SignInOptions} options: options to modify login request\r\n * @returns {RequestHandler}\r\n */\r\n signIn = (options?: SignInOptions): RequestHandler => {\r\n return (req: Request, res: Response, next: NextFunction): Promise => {\r\n /**\r\n * Request Configuration\r\n * We manipulate these three request objects below\r\n * to acquire a token with the appropriate claims\r\n */\r\n if (!req.session[\"authCodeRequest\"]) {\r\n req.session.authCodeRequest = {\r\n authority: \"\",\r\n scopes: [],\r\n state: {},\r\n redirectUri: \"\",\r\n } as AuthorizationUrlRequest;\r\n }\r\n\r\n if (!req.session[\"tokenRequest\"]) {\r\n req.session.tokenRequest = {\r\n authority: \"\",\r\n scopes: [],\r\n redirectUri: \"\",\r\n code: \"\",\r\n } as AuthorizationCodeRequest;\r\n }\r\n\r\n // signed-in user's account\r\n if (!req.session[\"account\"]) {\r\n req.session.account = {\r\n homeAccountId: \"\",\r\n environment: \"\",\r\n tenantId: \"\",\r\n username: \"\",\r\n idTokenClaims: {},\r\n } as AccountInfo;\r\n }\r\n\r\n // random GUID for csrf protection\r\n req.session.nonce = this.cryptoProvider.createNewGuid();\r\n \r\n // TODO: encrypt state parameter \r\n const state = this.cryptoProvider.base64Encode(\r\n JSON.stringify({\r\n stage: AppStages.SIGN_IN,\r\n path: options.successRedirect,\r\n nonce: req.session.nonce,\r\n })\r\n );\r\n\r\n const params: AuthCodeParams = {\r\n authority: this.msalConfig.auth.authority,\r\n scopes: OIDC_DEFAULT_SCOPES,\r\n state: state,\r\n redirect: UrlUtils.ensureAbsoluteUrl(req, this.appSettings.authRoutes.redirect),\r\n prompt: PromptValue.SELECT_ACCOUNT,\r\n };\r\n\r\n // get url to sign user in\r\n return this.getAuthCode(req, res, next, params);\r\n }\r\n };\r\n\r\n /**\r\n * Initiate sign out and destroy the session\r\n * @param options: options to modify logout request \r\n * @returns {RequestHandler}\r\n */\r\n signOut = (options?: SignOutOptions): RequestHandler => {\r\n return (req: Request, res: Response, next: NextFunction): void => {\r\n const postLogoutRedirectUri = UrlUtils.ensureAbsoluteUrl(req, options.successRedirect);\r\n\r\n /**\r\n * Construct a logout URI and redirect the user to end the\r\n * session with Azure AD/B2C. For more information, visit:\r\n * (AAD) https://docs.microsoft.com/azure/active-directory/develop/v2-protocols-oidc#send-a-sign-out-request\r\n * (B2C) https://docs.microsoft.com/azure/active-directory-b2c/openid-connect#send-a-sign-out-request\r\n */\r\n const logoutURI = `${this.msalConfig.auth.authority}/oauth2/v2.0/logout?post_logout_redirect_uri=${postLogoutRedirectUri}`;\r\n\r\n req.session.isAuthenticated = false;\r\n\r\n req.session.destroy(() => {\r\n res.redirect(logoutURI);\r\n });\r\n }\r\n };\r\n\r\n /**\r\n * Middleware that handles redirect depending on request state\r\n * There are basically 2 stages: sign-in and acquire token\r\n * @param {HandleRedirectOptions} options: options to modify this middleware\r\n * @returns {RequestHandler}\r\n */\r\n private handleRedirect = (options?: HandleRedirectOptions): RequestHandler => {\r\n return async (req: Request, res: Response, next: NextFunction): Promise => {\r\n if (req.query.state) {\r\n const state = JSON.parse(this.cryptoProvider.base64Decode(req.query.state as string));\r\n\r\n // check if nonce matches\r\n if (state.nonce === req.session.nonce) {\r\n switch (state.stage) {\r\n case AppStages.SIGN_IN: {\r\n // token request should have auth code\r\n req.session.tokenRequest.code = req.query.code as string;\r\n\r\n try {\r\n // exchange auth code for tokens\r\n const tokenResponse = await this.msalClient.acquireTokenByCode(req.session.tokenRequest);\r\n\r\n try {\r\n const isIdTokenValid = await this.tokenValidator.validateIdToken(tokenResponse.idToken);\r\n\r\n if (isIdTokenValid) {\r\n // assign session variables\r\n req.session.account = tokenResponse.account;\r\n req.session.isAuthenticated = true;\r\n\r\n res.redirect(state.path);\r\n } else {\r\n Logger.logError(ErrorMessages.INVALID_TOKEN);\r\n res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.CANNOT_VALIDATE_TOKEN);\r\n next(error)\r\n }\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.TOKEN_ACQUISITION_FAILED);\r\n next(error)\r\n }\r\n break;\r\n }\r\n\r\n case AppStages.ACQUIRE_TOKEN: {\r\n // get the name of the resource associated with scope\r\n const resourceName = this.getResourceNameFromScopes(req.session.tokenRequest.scopes);\r\n\r\n req.session.tokenRequest.code = req.query.code as string\r\n\r\n try {\r\n const tokenResponse = await this.msalClient.acquireTokenByCode(req.session.tokenRequest);\r\n req.session.remoteResources[resourceName].accessToken = tokenResponse.accessToken;\r\n res.redirect(state.path);\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.TOKEN_ACQUISITION_FAILED);\r\n next(error);\r\n }\r\n break;\r\n }\r\n\r\n default:\r\n Logger.logError(ErrorMessages.CANNOT_DETERMINE_APP_STAGE);\r\n res.redirect(this.appSettings.authRoutes.error);\r\n break;\r\n }\r\n } else {\r\n Logger.logError(ErrorMessages.NONCE_MISMATCH);\r\n res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n } else {\r\n Logger.logError(ErrorMessages.STATE_NOT_FOUND)\r\n res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n }\r\n };\r\n\r\n // ========== MIDDLEWARE ===========\r\n\r\n /**\r\n * Middleware that gets tokens via acquireToken*\r\n * @param {TokenRequestOptions} options: options to modify this middleware\r\n * @returns {RequestHandler}\r\n */\r\n getToken = (options: TokenRequestOptions): RequestHandler => {\r\n return async (req: Request, res: Response, next: NextFunction): Promise => {\r\n // get scopes for token request\r\n const scopes = options.resource.scopes;\r\n\r\n const resourceName = this.getResourceNameFromScopes(scopes)\r\n\r\n if (!req.session.remoteResources) {\r\n req.session.remoteResources = {};\r\n }\r\n\r\n req.session.remoteResources = {\r\n [resourceName]: {\r\n ...this.appSettings.remoteResources[resourceName],\r\n accessToken: null,\r\n } as Resource\r\n };\r\n\r\n try {\r\n const silentRequest: SilentFlowRequest = {\r\n account: req.session.account,\r\n scopes: scopes,\r\n };\r\n\r\n // acquire token silently to be used in resource call\r\n const tokenResponse = await this.msalClient.acquireTokenSilent(silentRequest);\r\n\r\n // In B2C scenarios, sometimes an access token is returned empty.\r\n // In that case, we will acquire token interactively instead.\r\n if (StringUtils.isEmpty(tokenResponse.accessToken)) {\r\n Logger.logError(ErrorMessages.TOKEN_NOT_FOUND);\r\n throw new InteractionRequiredAuthError(ErrorMessages.INTERACTION_REQUIRED);\r\n }\r\n\r\n req.session.remoteResources[resourceName].accessToken = tokenResponse.accessToken;\r\n next();\r\n } catch (error) {\r\n // in case there are no cached tokens, initiate an interactive call\r\n if (error instanceof InteractionRequiredAuthError) {\r\n const state = this.cryptoProvider.base64Encode(\r\n JSON.stringify({\r\n stage: AppStages.ACQUIRE_TOKEN,\r\n path: req.originalUrl,\r\n nonce: req.session.nonce,\r\n })\r\n );\r\n\r\n const params: AuthCodeParams = {\r\n authority: this.msalConfig.auth.authority,\r\n scopes: scopes,\r\n state: state,\r\n redirect: UrlUtils.ensureAbsoluteUrl(req, this.appSettings.authRoutes.redirect),\r\n account: req.session.account,\r\n };\r\n\r\n // initiate the first leg of auth code grant to get token\r\n return this.getAuthCode(req, res, next, params);\r\n } else {\r\n next(error);\r\n }\r\n }\r\n }\r\n };\r\n\r\n /**\r\n * Middleware that gets tokens via OBO flow. Used in web API scenarios\r\n * @param {TokenRequestOptions} options: options to modify this middleware\r\n * @returns {RequestHandler}\r\n */\r\n getTokenOnBehalf = (options: TokenRequestOptions): RequestHandler => {\r\n return async (req: Request, res: Response, next: NextFunction): Promise => {\r\n const authHeader = req.headers.authorization;\r\n\r\n // get scopes for token request\r\n const scopes = options.resource.scopes;\r\n const resourceName = this.getResourceNameFromScopes(scopes);\r\n\r\n const oboRequest: OnBehalfOfRequest = {\r\n oboAssertion: authHeader.split(\" \")[1],\r\n scopes: scopes,\r\n }\r\n\r\n try {\r\n const tokenResponse = await this.msalClient.acquireTokenOnBehalfOf(oboRequest);\r\n\r\n // as OBO is commonly used in middle-tier web APIs without sessions, attach AT to req\r\n req[\"locals\"] = {\r\n [resourceName]: {\r\n accessToken: tokenResponse.accessToken\r\n }\r\n }\r\n\r\n next();\r\n } catch (error) {\r\n next(error);\r\n }\r\n }\r\n }\r\n\r\n // ============== GUARDS ===============\r\n\r\n /**\r\n * Check if authenticated in session\r\n * @param {GuardOptions} options: options to modify this middleware\r\n * @returns {RequestHandler}\r\n */\r\n isAuthenticated = (options?: GuardOptions): RequestHandler => {\r\n return (req: Request, res: Response, next: NextFunction): void => {\r\n if (req.session) {\r\n if (!req.session.isAuthenticated) {\r\n Logger.logError(ErrorMessages.NOT_PERMITTED);\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n\r\n next();\r\n } else {\r\n Logger.logError(ErrorMessages.SESSION_NOT_FOUND);\r\n res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n }\r\n };\r\n\r\n /**\r\n * Receives access token in req authorization header\r\n * and validates it using the jwt.verify\r\n * @param {GuardOptions} options: options to modify this middleware\r\n * @returns {RequestHandler}\r\n */\r\n isAuthorized = (options?: GuardOptions): RequestHandler => {\r\n return async (req: Request, res: Response, next: NextFunction): Promise => {\r\n const accessToken = req.headers.authorization.split(\" \")[1];\r\n\r\n if (req.headers.authorization) {\r\n if (!(await this.tokenValidator.verifyAccessTokenSignature(accessToken, `${req.baseUrl}${req.path}`))) {\r\n Logger.logError(ErrorMessages.INVALID_TOKEN);\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n\r\n next();\r\n } else {\r\n Logger.logError(ErrorMessages.TOKEN_NOT_FOUND);\r\n res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n }\r\n };\r\n\r\n /**\r\n * Checks if the user has access for this route, defined in access matrix\r\n * @param {GuardOptions} options: options to modify this middleware\r\n * @returns {RequestHandler}\r\n */\r\n hasAccess = (options?: GuardOptions): RequestHandler => {\r\n return async (req: Request, res: Response, next: NextFunction): Promise => {\r\n if (req.session && this.appSettings.accessMatrix) {\r\n\r\n const checkFor = options.accessRule.hasOwnProperty(AccessConstants.GROUPS) ? AccessConstants.GROUPS : AccessConstants.ROLES;\r\n\r\n switch (checkFor) {\r\n case AccessConstants.GROUPS:\r\n\r\n if (req.session.account.idTokenClaims[AccessConstants.GROUPS] === undefined) {\r\n if (req.session.account.idTokenClaims[AccessConstants.CLAIM_NAMES] || req.session.account.idTokenClaims[AccessConstants.CLAIM_SOURCES]) {\r\n Logger.logWarning(InfoMessages.OVERAGE_OCCURRED)\r\n return await this.handleOverage(req, res, next, options.accessRule);\r\n } else {\r\n Logger.logError(ErrorMessages.USER_HAS_NO_GROUP);\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n } else {\r\n const groups = req.session.account.idTokenClaims[AccessConstants.GROUPS];\r\n\r\n if (!this.checkAccessRule(req.method, options.accessRule, groups, AccessConstants.GROUPS)) {\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n }\r\n\r\n next();\r\n break;\r\n\r\n case AccessConstants.ROLES:\r\n if (req.session.account.idTokenClaims[AccessConstants.ROLES] === undefined) {\r\n Logger.logError(ErrorMessages.USER_HAS_NO_ROLE);\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n } else {\r\n const roles = req.session.account.idTokenClaims[AccessConstants.ROLES];\r\n\r\n if (!this.checkAccessRule(req.method, options.accessRule, roles, AccessConstants.ROLES)) {\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n }\r\n\r\n next();\r\n break;\r\n\r\n default:\r\n break;\r\n }\r\n } else {\r\n res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n }\r\n }\r\n\r\n // ============== UTILS ===============\r\n\r\n /**\r\n * This method is used to generate an auth code url request\r\n * @param {Request} req: express request object\r\n * @param {Response} res: express response object\r\n * @param {NextFunction} next: express next function\r\n * @param {AuthCodeParams} params: modifies auth code url request\r\n * @returns {Promise}\r\n */\r\n private async getAuthCode(req: Request, res: Response, next: NextFunction, params: AuthCodeParams): Promise {\r\n // prepare the request\r\n req.session.authCodeRequest.authority = params.authority;\r\n req.session.authCodeRequest.scopes = params.scopes;\r\n req.session.authCodeRequest.state = params.state;\r\n req.session.authCodeRequest.redirectUri = params.redirect;\r\n req.session.authCodeRequest.prompt = params.prompt;\r\n req.session.authCodeRequest.account = params.account;\r\n\r\n req.session.tokenRequest.authority = params.authority;\r\n req.session.tokenRequest.scopes = params.scopes;\r\n req.session.tokenRequest.redirectUri = params.redirect;\r\n\r\n // request an authorization code to exchange for tokens\r\n try {\r\n const response = await this.msalClient.getAuthCodeUrl(req.session.authCodeRequest);\r\n res.redirect(response);\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.AUTH_CODE_NOT_OBTAINED);\r\n next(error);\r\n }\r\n };\r\n\r\n /**\r\n * Handles group overage claims by querying MS Graph /memberOf endpoint\r\n * @param {Request} req: express request object\r\n * @param {Response} res: express response object\r\n * @param {NextFunction} next: express next function\r\n * @param {AccessRule} rule: a given access rule\r\n * @returns {Promise}\r\n */\r\n private async handleOverage(req: Request, res: Response, next: NextFunction, rule: AccessRule): Promise {\r\n const { _claim_names, _claim_sources, ...newIdTokenClaims } = req.session.account.idTokenClaims;\r\n\r\n const silentRequest: SilentFlowRequest = {\r\n account: req.session.account,\r\n scopes: AccessConstants.GRAPH_MEMBER_SCOPES.split(\" \"),\r\n };\r\n\r\n try {\r\n // acquire token silently to be used in resource call\r\n const tokenResponse = await this.msalClient.acquireTokenSilent(silentRequest);\r\n try {\r\n const graphResponse = await FetchManager.callApiEndpoint(AccessConstants.GRAPH_MEMBERS_ENDPOINT, tokenResponse.accessToken);\r\n\r\n /**\r\n * Some queries against Microsoft Graph return multiple pages of data either due to server-side paging \r\n * or due to the use of the $top query parameter to specifically limit the page size in a request. \r\n * When a result set spans multiple pages, Microsoft Graph returns an @odata.nextLink property in \r\n * the response that contains a URL to the next page of results. Learn more at https://docs.microsoft.com/graph/paging\r\n */\r\n if (graphResponse[AccessConstants.PAGINATION_LINK]) {\r\n try {\r\n const userGroups = await FetchManager.handlePagination(tokenResponse.accessToken, graphResponse[AccessConstants.PAGINATION_LINK]);\r\n\r\n req.session.account.idTokenClaims = {\r\n ...newIdTokenClaims,\r\n groups: userGroups\r\n }\r\n\r\n if (!this.checkAccessRule(req.method, rule, req.session.account.idTokenClaims[AccessConstants.GROUPS], AccessConstants.GROUPS)) {\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n } else {\r\n return next();\r\n }\r\n } catch (error) {\r\n next(error);\r\n }\r\n } else {\r\n req.session.account.idTokenClaims = {\r\n ...newIdTokenClaims,\r\n groups: graphResponse[\"value\"].map((v) => v.id)\r\n }\r\n\r\n if (!this.checkAccessRule(req.method, rule, req.session.account.idTokenClaims[AccessConstants.GROUPS], AccessConstants.GROUPS)) {\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n } else {\r\n return next();\r\n }\r\n }\r\n } catch (error) {\r\n next(error);\r\n }\r\n } catch (error) {\r\n next(error);\r\n }\r\n }\r\n\r\n /**\r\n * Checks if the request passes a given access rule\r\n * @param {string} method: HTTP method for this route\r\n * @param {AccessRule} rule: access rule for this route\r\n * @param {Array} creds: user's credentials i.e. roles or groups\r\n * @param {string} credType: roles or groups\r\n * @returns {boolean}\r\n */\r\n private checkAccessRule(method: string, rule: AccessRule, creds: string[], credType: string): boolean {\r\n if (rule.methods.includes(method)) {\r\n switch (credType) {\r\n case AccessConstants.GROUPS:\r\n if (rule.groups.filter(elem => creds.includes(elem)).length < 1) {\r\n Logger.logError(ErrorMessages.USER_NOT_IN_GROUP);\r\n return false;\r\n }\r\n break;\r\n\r\n case AccessConstants.ROLES:\r\n if (rule.roles.filter(elem => creds.includes(elem)).length < 1) {\r\n Logger.logError(ErrorMessages.USER_NOT_IN_ROLE);\r\n return false;\r\n }\r\n break;\r\n\r\n default:\r\n break;\r\n }\r\n } else {\r\n Logger.logError(ErrorMessages.METHOD_NOT_ALLOWED);\r\n return false;\r\n }\r\n\r\n return true;\r\n }\r\n\r\n /**\r\n * Util method to get the resource name for a given scope(s)\r\n * @param {Array} scopes: an array of scopes that the resource is associated with\r\n * @returns {string}\r\n */\r\n private getResourceNameFromScopes(scopes: string[]): string {\r\n // TODO: deep check equality here \r\n\r\n const index = Object.values({ ...this.appSettings.remoteResources, ...this.appSettings.ownedResources })\r\n .findIndex((resource: Resource) => JSON.stringify(resource.scopes) === JSON.stringify(scopes));\r\n\r\n const resourceName = Object.keys({ ...this.appSettings.remoteResources, ...this.appSettings.ownedResources })[index];\r\n return resourceName;\r\n };\r\n}\r\n"],"names":["undefined","AppStages","SIGN_IN","SIGN_OUT","ACQUIRE_TOKEN","AADAuthorityConstants","COMMON","ORGANIZATIONS","CONSUMERS","KeyVaultCredentialTypes","SECRET","CERTIFICATE","AccessConstants","GROUPS","ROLES","CLAIM_NAMES","CLAIM_SOURCES","PAGINATION_LINK","GRAPH_MEMBERS_ENDPOINT","GRAPH_MEMBER_SCOPES","InfoMessages","REQUEST_FOR_RESOURCE","OVERAGE_OCCURRED","ErrorMessages","NOT_PERMITTED","INVALID_TOKEN","CANNOT_DETERMINE_APP_STAGE","CANNOT_VALIDATE_TOKEN","NONCE_MISMATCH","INTERACTION_REQUIRED","TOKEN_ACQUISITION_FAILED","AUTH_CODE_NOT_OBTAINED","TOKEN_NOT_FOUND","TOKEN_NOT_DECODED","TOKEN_NOT_VERIFIED","KEYS_NOT_OBTAINED","STATE_NOT_FOUND","USER_HAS_NO_ROLE","USER_NOT_IN_ROLE","USER_HAS_NO_GROUP","USER_NOT_IN_GROUP","METHOD_NOT_ALLOWED","RULE_NOT_FOUND","SESSION_NOT_FOUND","KEY_VAULT_CONFIG_NOT_FOUND","ConfigurationErrorMessages","NO_CLIENT_ID","INVALID_CLIENT_ID","NO_TENANT_INFO","INVALID_TENANT_INFO","NO_CLIENT_CREDENTIAL","NO_REDIRECT_URI","NO_ERROR_ROUTE","NO_UNAUTHORIZED_ROUTE","ErrorCodes","ConfigurationUtils","validateAppSettings","config","StringUtils","isEmpty","appCredentials","clientId","Error","isGuid","tenantId","Object","values","includes","clientSecret","clientCertificate","authRoutes","redirect","error","unauthorized","getMsalConfiguration","cachePlugin","auth","authority","b2cPolicies","entries","Constants","DEFAULT_AUTHORITY_HOST","hasOwnProperty","knownAuthorities","UrlString","getDomainFromUrl","cache","system","loggerOptions","loggerCallback","logLevel","message","containsPii","LogLevel","console","Info","info","Verbose","debug","Warning","warn","piiLoggingEnabled","guid","regexGuid","test","Logger","logError","log","logMessage","logWarning","logInfo","timestamp","Date","toUTCString","logHeader","TokenValidator","appSettings","msalConfig","verifyTokenSignature","authToken","decodedToken","jwt","decode","complete","getSigningKeys","header","payload","tid","keys","verifiedToken","verify","validateIdToken","idToken","validateIdTokenClaims","idTokenClaims","now","Math","round","getTime","checkIssuer","iss","checkAudience","aud","checkTimestamp","iat","exp","verifyAccessTokenSignature","accessToken","protectedRoute","validateAccessTokenClaims","checkScopes","ownedResources","find","resource","endpoint","scopes","every","scp","jwksUri","client","jwksClient","getSigningKeyAsync","kid","getPublicKey","KeyVaultManager","getCredentialFromKeyVault","credential","DefaultAzureCredential","keyVaultCredential","credentialType","getSecretCredential","secretResponse","value","getCertificateCredential","certificateResponse","thumbprint","properties","x509Thumbprint","toString","privateKey","split","secretClient","CertificateClient","keyVaultUrl","getCertificate","credentialName","keyVaultCertificate","SecretClient","getSecret","keyVaultSecret","FetchManager","options","headers","Authorization","axios","get","response","data","nextPage","callApiEndpoint","graphResponse","map","v","push","id","handlePagination","UrlUtils","req","url","urlComponents","getUrlComponents","Protocol","HostNameAndPort","protocol","AuthProvider","appRouter","express","Router","handleRedirect","frontChannelLogout","res","next","session","destroy","sendStatus","authCodeRequest","state","redirectUri","tokenRequest","code","account","homeAccountId","environment","username","nonce","cryptoProvider","createNewGuid","base64Encode","JSON","stringify","stage","path","successRedirect","params","OIDC_DEFAULT_SCOPES","ensureAbsoluteUrl","prompt","PromptValue","SELECT_ACCOUNT","getAuthCode","postLogoutRedirectUri","logoutURI","isAuthenticated","query","parse","base64Decode","msalClient","acquireTokenByCode","tokenResponse","tokenValidator","isIdTokenValid","resourceName","getResourceNameFromScopes","remoteResources","silentRequest","acquireTokenSilent","InteractionRequiredAuthError","originalUrl","authHeader","authorization","oboRequest","oboAssertion","acquireTokenOnBehalfOf","baseUrl","accessMatrix","checkFor","accessRule","handleOverage","groups","checkAccessRule","method","roles","ConfidentialClientApplication","CryptoProvider","buildAsync","keyVault","appSettingsWithKeyVaultCredentials","authProvider","getAuthCodeUrl","rule","_claim_names","newIdTokenClaims","userGroups","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AgBnF,aAAa,CAACkB,kBAA9B;AACA,aAAO,KAAP;AACH;;AAED,WAAO,IAAP;AACH;AAED;;;;;AAzkBJ;;AAAA,SA8kBY6N,yBA9kBZ,GA8kBY,mCAA0B3G,MAA1B;AACJ;AAEA,QAAMgJ,KAAK,GAAG1O,MAAM,CAACC,MAAP,cAAmB,KAAKkD,WAAL,CAAiBmJ,eAApC,EAAwD,KAAKnJ,WAAL,CAAiBmC,cAAzE,GACTqJ,SADS,CACC,UAACnJ,QAAD;AAAA,aAAwBqF,IAAI,CAACC,SAAL,CAAetF,QAAQ,CAACE,MAAxB,MAAoCmF,IAAI,CAACC,SAAL,CAAepF,MAAf,CAA5D;AAAA,KADD,CAAd;AAGA,QAAM0G,YAAY,GAAGpM,MAAM,CAAC+D,IAAP,cAAiB,KAAKZ,WAAL,CAAiBmJ,eAAlC,EAAsD,KAAKnJ,WAAL,CAAiBmC,cAAvE,GAAyFoJ,KAAzF,CAArB;AACA,WAAOtC,YAAP;AACH,GAtlBL;;AAAA;AAAA;;;;"} \ No newline at end of file +{"version":3,"file":"msal-express-wrapper.esm.js","sources":["../node_modules/regenerator-runtime/runtime.js","../src/Constants.ts","../src/ConfigurationUtils.ts","../src/Logger.ts","../src/TokenValidator.ts","../src/KeyVaultManager.ts","../src/FetchManager.ts","../src/UrlUtils.ts","../src/AuthProvider.ts"],"sourcesContent":["/**\n * Copyright (c) 2014-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nvar runtime = (function (exports) {\n \"use strict\";\n\n var Op = Object.prototype;\n var hasOwn = Op.hasOwnProperty;\n var undefined; // More compressible than void 0.\n var $Symbol = typeof Symbol === \"function\" ? Symbol : {};\n var iteratorSymbol = $Symbol.iterator || \"@@iterator\";\n var asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\";\n var toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n\n function define(obj, key, value) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n return obj[key];\n }\n try {\n // IE 8 has a broken Object.defineProperty that only works on DOM objects.\n define({}, \"\");\n } catch (err) {\n define = function(obj, key, value) {\n return obj[key] = value;\n };\n }\n\n function wrap(innerFn, outerFn, self, tryLocsList) {\n // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.\n var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;\n var generator = Object.create(protoGenerator.prototype);\n var context = new Context(tryLocsList || []);\n\n // The ._invoke method unifies the implementations of the .next,\n // .throw, and .return methods.\n generator._invoke = makeInvokeMethod(innerFn, self, context);\n\n return generator;\n }\n exports.wrap = wrap;\n\n // Try/catch helper to minimize deoptimizations. Returns a completion\n // record like context.tryEntries[i].completion. This interface could\n // have been (and was previously) designed to take a closure to be\n // invoked without arguments, but in all the cases we care about we\n // already have an existing method we want to call, so there's no need\n // to create a new function object. We can even get away with assuming\n // the method takes exactly one argument, since that happens to be true\n // in every case, so we don't have to touch the arguments object. The\n // only additional allocation required is the completion record, which\n // has a stable shape and so hopefully should be cheap to allocate.\n function tryCatch(fn, obj, arg) {\n try {\n return { type: \"normal\", arg: fn.call(obj, arg) };\n } catch (err) {\n return { type: \"throw\", arg: err };\n }\n }\n\n var GenStateSuspendedStart = \"suspendedStart\";\n var GenStateSuspendedYield = \"suspendedYield\";\n var GenStateExecuting = \"executing\";\n var GenStateCompleted = \"completed\";\n\n // Returning this object from the innerFn has the same effect as\n // breaking out of the dispatch switch statement.\n var ContinueSentinel = {};\n\n // Dummy constructor functions that we use as the .constructor and\n // .constructor.prototype properties for functions that return Generator\n // objects. For full spec compliance, you may wish to configure your\n // minifier not to mangle the names of these two functions.\n function Generator() {}\n function GeneratorFunction() {}\n function GeneratorFunctionPrototype() {}\n\n // This is a polyfill for %IteratorPrototype% for environments that\n // don't natively support it.\n var IteratorPrototype = {};\n IteratorPrototype[iteratorSymbol] = function () {\n return this;\n };\n\n var getProto = Object.getPrototypeOf;\n var NativeIteratorPrototype = getProto && getProto(getProto(values([])));\n if (NativeIteratorPrototype &&\n NativeIteratorPrototype !== Op &&\n hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {\n // This environment has a native %IteratorPrototype%; use it instead\n // of the polyfill.\n IteratorPrototype = NativeIteratorPrototype;\n }\n\n var Gp = GeneratorFunctionPrototype.prototype =\n Generator.prototype = Object.create(IteratorPrototype);\n GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;\n GeneratorFunctionPrototype.constructor = GeneratorFunction;\n GeneratorFunction.displayName = define(\n GeneratorFunctionPrototype,\n toStringTagSymbol,\n \"GeneratorFunction\"\n );\n\n // Helper for defining the .next, .throw, and .return methods of the\n // Iterator interface in terms of a single ._invoke method.\n function defineIteratorMethods(prototype) {\n [\"next\", \"throw\", \"return\"].forEach(function(method) {\n define(prototype, method, function(arg) {\n return this._invoke(method, arg);\n });\n });\n }\n\n exports.isGeneratorFunction = function(genFun) {\n var ctor = typeof genFun === \"function\" && genFun.constructor;\n return ctor\n ? ctor === GeneratorFunction ||\n // For the native GeneratorFunction constructor, the best we can\n // do is to check its .name property.\n (ctor.displayName || ctor.name) === \"GeneratorFunction\"\n : false;\n };\n\n exports.mark = function(genFun) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);\n } else {\n genFun.__proto__ = GeneratorFunctionPrototype;\n define(genFun, toStringTagSymbol, \"GeneratorFunction\");\n }\n genFun.prototype = Object.create(Gp);\n return genFun;\n };\n\n // Within the body of any async function, `await x` is transformed to\n // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test\n // `hasOwn.call(value, \"__await\")` to determine if the yielded value is\n // meant to be awaited.\n exports.awrap = function(arg) {\n return { __await: arg };\n };\n\n function AsyncIterator(generator, PromiseImpl) {\n function invoke(method, arg, resolve, reject) {\n var record = tryCatch(generator[method], generator, arg);\n if (record.type === \"throw\") {\n reject(record.arg);\n } else {\n var result = record.arg;\n var value = result.value;\n if (value &&\n typeof value === \"object\" &&\n hasOwn.call(value, \"__await\")) {\n return PromiseImpl.resolve(value.__await).then(function(value) {\n invoke(\"next\", value, resolve, reject);\n }, function(err) {\n invoke(\"throw\", err, resolve, reject);\n });\n }\n\n return PromiseImpl.resolve(value).then(function(unwrapped) {\n // When a yielded Promise is resolved, its final value becomes\n // the .value of the Promise<{value,done}> result for the\n // current iteration.\n result.value = unwrapped;\n resolve(result);\n }, function(error) {\n // If a rejected Promise was yielded, throw the rejection back\n // into the async generator function so it can be handled there.\n return invoke(\"throw\", error, resolve, reject);\n });\n }\n }\n\n var previousPromise;\n\n function enqueue(method, arg) {\n function callInvokeWithMethodAndArg() {\n return new PromiseImpl(function(resolve, reject) {\n invoke(method, arg, resolve, reject);\n });\n }\n\n return previousPromise =\n // If enqueue has been called before, then we want to wait until\n // all previous Promises have been resolved before calling invoke,\n // so that results are always delivered in the correct order. If\n // enqueue has not been called before, then it is important to\n // call invoke immediately, without waiting on a callback to fire,\n // so that the async generator function has the opportunity to do\n // any necessary setup in a predictable way. This predictability\n // is why the Promise constructor synchronously invokes its\n // executor callback, and why async functions synchronously\n // execute code before the first await. Since we implement simple\n // async functions in terms of async generators, it is especially\n // important to get this right, even though it requires care.\n previousPromise ? previousPromise.then(\n callInvokeWithMethodAndArg,\n // Avoid propagating failures to Promises returned by later\n // invocations of the iterator.\n callInvokeWithMethodAndArg\n ) : callInvokeWithMethodAndArg();\n }\n\n // Define the unified helper method that is used to implement .next,\n // .throw, and .return (see defineIteratorMethods).\n this._invoke = enqueue;\n }\n\n defineIteratorMethods(AsyncIterator.prototype);\n AsyncIterator.prototype[asyncIteratorSymbol] = function () {\n return this;\n };\n exports.AsyncIterator = AsyncIterator;\n\n // Note that simple async functions are implemented on top of\n // AsyncIterator objects; they just return a Promise for the value of\n // the final result produced by the iterator.\n exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {\n if (PromiseImpl === void 0) PromiseImpl = Promise;\n\n var iter = new AsyncIterator(\n wrap(innerFn, outerFn, self, tryLocsList),\n PromiseImpl\n );\n\n return exports.isGeneratorFunction(outerFn)\n ? iter // If outerFn is a generator, return the full iterator.\n : iter.next().then(function(result) {\n return result.done ? result.value : iter.next();\n });\n };\n\n function makeInvokeMethod(innerFn, self, context) {\n var state = GenStateSuspendedStart;\n\n return function invoke(method, arg) {\n if (state === GenStateExecuting) {\n throw new Error(\"Generator is already running\");\n }\n\n if (state === GenStateCompleted) {\n if (method === \"throw\") {\n throw arg;\n }\n\n // Be forgiving, per 25.3.3.3.3 of the spec:\n // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume\n return doneResult();\n }\n\n context.method = method;\n context.arg = arg;\n\n while (true) {\n var delegate = context.delegate;\n if (delegate) {\n var delegateResult = maybeInvokeDelegate(delegate, context);\n if (delegateResult) {\n if (delegateResult === ContinueSentinel) continue;\n return delegateResult;\n }\n }\n\n if (context.method === \"next\") {\n // Setting context._sent for legacy support of Babel's\n // function.sent implementation.\n context.sent = context._sent = context.arg;\n\n } else if (context.method === \"throw\") {\n if (state === GenStateSuspendedStart) {\n state = GenStateCompleted;\n throw context.arg;\n }\n\n context.dispatchException(context.arg);\n\n } else if (context.method === \"return\") {\n context.abrupt(\"return\", context.arg);\n }\n\n state = GenStateExecuting;\n\n var record = tryCatch(innerFn, self, context);\n if (record.type === \"normal\") {\n // If an exception is thrown from innerFn, we leave state ===\n // GenStateExecuting and loop back for another invocation.\n state = context.done\n ? GenStateCompleted\n : GenStateSuspendedYield;\n\n if (record.arg === ContinueSentinel) {\n continue;\n }\n\n return {\n value: record.arg,\n done: context.done\n };\n\n } else if (record.type === \"throw\") {\n state = GenStateCompleted;\n // Dispatch the exception by looping back around to the\n // context.dispatchException(context.arg) call above.\n context.method = \"throw\";\n context.arg = record.arg;\n }\n }\n };\n }\n\n // Call delegate.iterator[context.method](context.arg) and handle the\n // result, either by returning a { value, done } result from the\n // delegate iterator, or by modifying context.method and context.arg,\n // setting context.delegate to null, and returning the ContinueSentinel.\n function maybeInvokeDelegate(delegate, context) {\n var method = delegate.iterator[context.method];\n if (method === undefined) {\n // A .throw or .return when the delegate iterator has no .throw\n // method always terminates the yield* loop.\n context.delegate = null;\n\n if (context.method === \"throw\") {\n // Note: [\"return\"] must be used for ES3 parsing compatibility.\n if (delegate.iterator[\"return\"]) {\n // If the delegate iterator has a return method, give it a\n // chance to clean up.\n context.method = \"return\";\n context.arg = undefined;\n maybeInvokeDelegate(delegate, context);\n\n if (context.method === \"throw\") {\n // If maybeInvokeDelegate(context) changed context.method from\n // \"return\" to \"throw\", let that override the TypeError below.\n return ContinueSentinel;\n }\n }\n\n context.method = \"throw\";\n context.arg = new TypeError(\n \"The iterator does not provide a 'throw' method\");\n }\n\n return ContinueSentinel;\n }\n\n var record = tryCatch(method, delegate.iterator, context.arg);\n\n if (record.type === \"throw\") {\n context.method = \"throw\";\n context.arg = record.arg;\n context.delegate = null;\n return ContinueSentinel;\n }\n\n var info = record.arg;\n\n if (! info) {\n context.method = \"throw\";\n context.arg = new TypeError(\"iterator result is not an object\");\n context.delegate = null;\n return ContinueSentinel;\n }\n\n if (info.done) {\n // Assign the result of the finished delegate to the temporary\n // variable specified by delegate.resultName (see delegateYield).\n context[delegate.resultName] = info.value;\n\n // Resume execution at the desired location (see delegateYield).\n context.next = delegate.nextLoc;\n\n // If context.method was \"throw\" but the delegate handled the\n // exception, let the outer generator proceed normally. If\n // context.method was \"next\", forget context.arg since it has been\n // \"consumed\" by the delegate iterator. If context.method was\n // \"return\", allow the original .return call to continue in the\n // outer generator.\n if (context.method !== \"return\") {\n context.method = \"next\";\n context.arg = undefined;\n }\n\n } else {\n // Re-yield the result returned by the delegate method.\n return info;\n }\n\n // The delegate iterator is finished, so forget it and continue with\n // the outer generator.\n context.delegate = null;\n return ContinueSentinel;\n }\n\n // Define Generator.prototype.{next,throw,return} in terms of the\n // unified ._invoke helper method.\n defineIteratorMethods(Gp);\n\n define(Gp, toStringTagSymbol, \"Generator\");\n\n // A Generator should always return itself as the iterator object when the\n // @@iterator function is called on it. Some browsers' implementations of the\n // iterator prototype chain incorrectly implement this, causing the Generator\n // object to not be returned from this call. This ensures that doesn't happen.\n // See https://github.com/facebook/regenerator/issues/274 for more details.\n Gp[iteratorSymbol] = function() {\n return this;\n };\n\n Gp.toString = function() {\n return \"[object Generator]\";\n };\n\n function pushTryEntry(locs) {\n var entry = { tryLoc: locs[0] };\n\n if (1 in locs) {\n entry.catchLoc = locs[1];\n }\n\n if (2 in locs) {\n entry.finallyLoc = locs[2];\n entry.afterLoc = locs[3];\n }\n\n this.tryEntries.push(entry);\n }\n\n function resetTryEntry(entry) {\n var record = entry.completion || {};\n record.type = \"normal\";\n delete record.arg;\n entry.completion = record;\n }\n\n function Context(tryLocsList) {\n // The root entry object (effectively a try statement without a catch\n // or a finally block) gives us a place to store values thrown from\n // locations where there is no enclosing try statement.\n this.tryEntries = [{ tryLoc: \"root\" }];\n tryLocsList.forEach(pushTryEntry, this);\n this.reset(true);\n }\n\n exports.keys = function(object) {\n var keys = [];\n for (var key in object) {\n keys.push(key);\n }\n keys.reverse();\n\n // Rather than returning an object with a next method, we keep\n // things simple and return the next function itself.\n return function next() {\n while (keys.length) {\n var key = keys.pop();\n if (key in object) {\n next.value = key;\n next.done = false;\n return next;\n }\n }\n\n // To avoid creating an additional object, we just hang the .value\n // and .done properties off the next function object itself. This\n // also ensures that the minifier will not anonymize the function.\n next.done = true;\n return next;\n };\n };\n\n function values(iterable) {\n if (iterable) {\n var iteratorMethod = iterable[iteratorSymbol];\n if (iteratorMethod) {\n return iteratorMethod.call(iterable);\n }\n\n if (typeof iterable.next === \"function\") {\n return iterable;\n }\n\n if (!isNaN(iterable.length)) {\n var i = -1, next = function next() {\n while (++i < iterable.length) {\n if (hasOwn.call(iterable, i)) {\n next.value = iterable[i];\n next.done = false;\n return next;\n }\n }\n\n next.value = undefined;\n next.done = true;\n\n return next;\n };\n\n return next.next = next;\n }\n }\n\n // Return an iterator with no values.\n return { next: doneResult };\n }\n exports.values = values;\n\n function doneResult() {\n return { value: undefined, done: true };\n }\n\n Context.prototype = {\n constructor: Context,\n\n reset: function(skipTempReset) {\n this.prev = 0;\n this.next = 0;\n // Resetting context._sent for legacy support of Babel's\n // function.sent implementation.\n this.sent = this._sent = undefined;\n this.done = false;\n this.delegate = null;\n\n this.method = \"next\";\n this.arg = undefined;\n\n this.tryEntries.forEach(resetTryEntry);\n\n if (!skipTempReset) {\n for (var name in this) {\n // Not sure about the optimal order of these conditions:\n if (name.charAt(0) === \"t\" &&\n hasOwn.call(this, name) &&\n !isNaN(+name.slice(1))) {\n this[name] = undefined;\n }\n }\n }\n },\n\n stop: function() {\n this.done = true;\n\n var rootEntry = this.tryEntries[0];\n var rootRecord = rootEntry.completion;\n if (rootRecord.type === \"throw\") {\n throw rootRecord.arg;\n }\n\n return this.rval;\n },\n\n dispatchException: function(exception) {\n if (this.done) {\n throw exception;\n }\n\n var context = this;\n function handle(loc, caught) {\n record.type = \"throw\";\n record.arg = exception;\n context.next = loc;\n\n if (caught) {\n // If the dispatched exception was caught by a catch block,\n // then let that catch block handle the exception normally.\n context.method = \"next\";\n context.arg = undefined;\n }\n\n return !! caught;\n }\n\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n var record = entry.completion;\n\n if (entry.tryLoc === \"root\") {\n // Exception thrown outside of any try block that could handle\n // it, so set the completion value of the entire function to\n // throw the exception.\n return handle(\"end\");\n }\n\n if (entry.tryLoc <= this.prev) {\n var hasCatch = hasOwn.call(entry, \"catchLoc\");\n var hasFinally = hasOwn.call(entry, \"finallyLoc\");\n\n if (hasCatch && hasFinally) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n } else if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else if (hasCatch) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n }\n\n } else if (hasFinally) {\n if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else {\n throw new Error(\"try statement without catch or finally\");\n }\n }\n }\n },\n\n abrupt: function(type, arg) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc <= this.prev &&\n hasOwn.call(entry, \"finallyLoc\") &&\n this.prev < entry.finallyLoc) {\n var finallyEntry = entry;\n break;\n }\n }\n\n if (finallyEntry &&\n (type === \"break\" ||\n type === \"continue\") &&\n finallyEntry.tryLoc <= arg &&\n arg <= finallyEntry.finallyLoc) {\n // Ignore the finally entry if control is not jumping to a\n // location outside the try/catch block.\n finallyEntry = null;\n }\n\n var record = finallyEntry ? finallyEntry.completion : {};\n record.type = type;\n record.arg = arg;\n\n if (finallyEntry) {\n this.method = \"next\";\n this.next = finallyEntry.finallyLoc;\n return ContinueSentinel;\n }\n\n return this.complete(record);\n },\n\n complete: function(record, afterLoc) {\n if (record.type === \"throw\") {\n throw record.arg;\n }\n\n if (record.type === \"break\" ||\n record.type === \"continue\") {\n this.next = record.arg;\n } else if (record.type === \"return\") {\n this.rval = this.arg = record.arg;\n this.method = \"return\";\n this.next = \"end\";\n } else if (record.type === \"normal\" && afterLoc) {\n this.next = afterLoc;\n }\n\n return ContinueSentinel;\n },\n\n finish: function(finallyLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.finallyLoc === finallyLoc) {\n this.complete(entry.completion, entry.afterLoc);\n resetTryEntry(entry);\n return ContinueSentinel;\n }\n }\n },\n\n \"catch\": function(tryLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc === tryLoc) {\n var record = entry.completion;\n if (record.type === \"throw\") {\n var thrown = record.arg;\n resetTryEntry(entry);\n }\n return thrown;\n }\n }\n\n // The context.catch method must only be called with a location\n // argument that corresponds to a known catch block.\n throw new Error(\"illegal catch attempt\");\n },\n\n delegateYield: function(iterable, resultName, nextLoc) {\n this.delegate = {\n iterator: values(iterable),\n resultName: resultName,\n nextLoc: nextLoc\n };\n\n if (this.method === \"next\") {\n // Deliberately forget the last sent value so that we don't\n // accidentally pass it on to the delegate.\n this.arg = undefined;\n }\n\n return ContinueSentinel;\n }\n };\n\n // Regardless of whether this script is executing as a CommonJS module\n // or not, return the runtime object so that we can declare the variable\n // regeneratorRuntime in the outer scope, which allows this module to be\n // injected easily by `bin/regenerator --include-runtime script.js`.\n return exports;\n\n}(\n // If this script is executing as a CommonJS module, use module.exports\n // as the regeneratorRuntime namespace. Otherwise create a new empty\n // object. Either way, the resulting object will be used to initialize\n // the regeneratorRuntime variable at the top of this file.\n typeof module === \"object\" ? module.exports : {}\n));\n\ntry {\n regeneratorRuntime = runtime;\n} catch (accidentalStrictMode) {\n // This module should not be running in strict mode, so the above\n // assignment should always work unless something is misconfigured. Just\n // in case runtime.js accidentally runs in strict mode, we can escape\n // strict mode using a global Function call. This could conceivably fail\n // if a Content Security Policy forbids using Function, but in that case\n // the proper solution is to fix the accidental strict mode problem. If\n // you've misconfigured your bundler to force strict mode and applied a\n // CSP to forbid Function, and you're not willing to fix either of those\n // problems, please detail your unique predicament in a GitHub issue.\n Function(\"r\", \"regeneratorRuntime = r\")(runtime);\n}\n","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\n/**\r\n * Basic authentication stages used to determine\r\n * appropriate action after redirect occurs\r\n */\r\nexport const AppStages = {\r\n SIGN_IN: \"sign_in\",\r\n SIGN_OUT: \"sign_out\",\r\n ACQUIRE_TOKEN: \"acquire_token\",\r\n};\r\n\r\n/**\r\n * String constants related to AAD Authority\r\n */\r\nexport const AADAuthorityConstants = {\r\n COMMON: \"common\",\r\n ORGANIZATIONS: \"organizations\",\r\n CONSUMERS: \"consumers\"\r\n}\r\n\r\n/**\r\n * String constants related to AAD Authority\r\n */\r\nexport const KeyVaultCredentialTypes = {\r\n SECRET: \"secret\",\r\n CERTIFICATE: \"certificate\",\r\n}\r\n\r\n/**\r\n * Constants used in access control scenarios\r\n */\r\nexport const AccessConstants = {\r\n GROUPS: \"groups\",\r\n ROLES: \"roles\",\r\n CLAIM_NAMES: \"_claim_name\",\r\n CLAIM_SOURCES: \"_claim_sources\",\r\n PAGINATION_LINK: \"@odata.nextLink\",\r\n GRAPH_MEMBERS_ENDPOINT: \"https://graph.microsoft.com/v1.0/me/memberOf\",\r\n GRAPH_MEMBER_SCOPES: \"User.Read GroupMember.Read.All\"\r\n};\r\n\r\nexport const InfoMessages = {\r\n REQUEST_FOR_RESOURCE: \"Request made to web API\",\r\n OVERAGE_OCCURRED: \"User has too many groups. Groups overage claim occurred\"\r\n}\r\n\r\n/**\r\n * Various error constants\r\n */\r\nexport const ErrorMessages = {\r\n NOT_PERMITTED: \"Not permitted\",\r\n INVALID_TOKEN: \"Invalid token\",\r\n CANNOT_DETERMINE_APP_STAGE: \"Cannot determine application stage\",\r\n CANNOT_VALIDATE_TOKEN: \"Cannot validate token\",\r\n NONCE_MISMATCH: \"Nonce does not match\",\r\n INTERACTION_REQUIRED: \"interaction_required\",\r\n TOKEN_ACQUISITION_FAILED: \"Token acquisition failed\",\r\n AUTH_CODE_NOT_OBTAINED: \"Authorization code cannot be obtained\",\r\n TOKEN_NOT_FOUND: \"No token found\",\r\n TOKEN_NOT_DECODED: \"Token cannot be decoded\",\r\n TOKEN_NOT_VERIFIED: \"Token cannot be verified\",\r\n KEYS_NOT_OBTAINED: \"Signing keys cannot be obtained\",\r\n STATE_NOT_FOUND: \"State not found\",\r\n USER_HAS_NO_ROLE: \"User does not have any roles\",\r\n USER_NOT_IN_ROLE: \"User does not have this role\",\r\n USER_HAS_NO_GROUP: \"User does not have any groups\",\r\n USER_NOT_IN_GROUP: \"User does not have this group\",\r\n METHOD_NOT_ALLOWED: \"Method not allowed for this route\",\r\n RULE_NOT_FOUND: \"No rule found for this route\",\r\n SESSION_NOT_FOUND: \"No session found for this request\",\r\n KEY_VAULT_CONFIG_NOT_FOUND: \"No coordinates found for Key Vault\"\r\n};\r\n\r\nexport const ConfigurationErrorMessages = {\r\n NO_CLIENT_ID: \"No clientId provided!\",\r\n INVALID_CLIENT_ID: \"Invalid clientId!\",\r\n NO_TENANT_INFO: \"No tenant info provided!\",\r\n INVALID_TENANT_INFO: \"Invalid tenant info!\",\r\n NO_CLIENT_CREDENTIAL: \"No client credential provided!\",\r\n NO_REDIRECT_URI: \"No redirect URI provided!\",\r\n NO_ERROR_ROUTE: \"No error route provided!\",\r\n NO_UNAUTHORIZED_ROUTE: \"No unauthorized route provided!\"\r\n}\r\n\r\n/**\r\n * For more information, visit: https://login.microsoftonline.com/error\r\n */\r\nexport const ErrorCodes = {\r\n 65001: \"AADSTS65001\", // consent required\r\n};","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { \r\n UrlString, \r\n StringUtils,\r\n Constants, \r\n} from \"@azure/msal-common\";\r\n\r\nimport { \r\n ICachePlugin,\r\n Configuration,\r\n LogLevel \r\n} from \"@azure/msal-node\";\r\n\r\nimport { AppSettings } from \"./Types\";\r\n\r\nimport { \r\n AADAuthorityConstants, \r\n ConfigurationErrorMessages \r\n} from \"./Constants\";\r\n\r\nexport class ConfigurationUtils {\r\n\r\n /**\r\n * Validates the fields in the configuration file\r\n * @param {AppSettings} config: configuration object\r\n * @returns {void}\r\n */\r\n static validateAppSettings(config: AppSettings): void {\r\n if (StringUtils.isEmpty(config.appCredentials.clientId)) {\r\n throw new Error(ConfigurationErrorMessages.NO_CLIENT_ID);\r\n } else if (!ConfigurationUtils.isGuid(config.appCredentials.clientId)) {\r\n throw new Error(ConfigurationErrorMessages.INVALID_CLIENT_ID);\r\n }\r\n\r\n if (StringUtils.isEmpty(config.appCredentials.tenantId)) {\r\n throw new Error(ConfigurationErrorMessages.NO_TENANT_INFO);\r\n } else if (!ConfigurationUtils.isGuid(config.appCredentials.tenantId) && !Object.values(AADAuthorityConstants).includes(config.appCredentials.tenantId)) {\r\n throw new Error(ConfigurationErrorMessages.INVALID_TENANT_INFO);\r\n }\r\n\r\n if (StringUtils.isEmpty(config.appCredentials.clientSecret) && !config.appCredentials.clientCertificate) {\r\n throw new Error(ConfigurationErrorMessages.NO_CLIENT_CREDENTIAL);\r\n }\r\n\r\n if (StringUtils.isEmpty(config.authRoutes.redirect)) {\r\n throw new Error(ConfigurationErrorMessages.NO_REDIRECT_URI);\r\n }\r\n\r\n if (StringUtils.isEmpty(config.authRoutes.error)) {\r\n throw new Error(ConfigurationErrorMessages.NO_ERROR_ROUTE);\r\n }\r\n\r\n if (StringUtils.isEmpty(config.authRoutes.unauthorized)) {\r\n throw new Error(ConfigurationErrorMessages.NO_UNAUTHORIZED_ROUTE);\r\n }\r\n };\r\n\r\n\r\n /**\r\n * Maps the custom configuration object to configuration\r\n * object expected by MSAL Node ConfidentialClientApplication class\r\n * @param {AppSettings} config: configuration object\r\n * @param {ICachePlugin} cachePlugin: persistent cache implementation\r\n * @returns {Configuration}\r\n */\r\n static getMsalConfiguration(config: AppSettings, cachePlugin: ICachePlugin = null): Configuration {\r\n return {\r\n auth: {\r\n clientId: config.appCredentials.clientId,\r\n authority: config.b2cPolicies ?\r\n Object.entries(config.b2cPolicies)[0][1][\"authority\"]\r\n :\r\n `https://${Constants.DEFAULT_AUTHORITY_HOST}/${config.appCredentials.tenantId}`,\r\n ...(config.appCredentials.hasOwnProperty(\"clientSecret\")) && { clientSecret: config.appCredentials.clientSecret },\r\n ...(config.appCredentials.hasOwnProperty(\"clientCertificate\")) && { clientCertificate: config.appCredentials.clientCertificate },\r\n knownAuthorities: config.b2cPolicies ?\r\n [UrlString.getDomainFromUrl(Object.entries(config.b2cPolicies)[0][1][\"authority\"])] // in B2C scenarios\r\n :\r\n [],\r\n },\r\n cache: {\r\n cachePlugin,\r\n },\r\n system: {\r\n loggerOptions: {\r\n loggerCallback: (logLevel, message, containsPii) => {\r\n if (containsPii) {\r\n return;\r\n }\r\n switch (logLevel) {\r\n case LogLevel.Error:\r\n console.error(message);\r\n return;\r\n case LogLevel.Info:\r\n console.info(message);\r\n return;\r\n case LogLevel.Verbose:\r\n console.debug(message);\r\n return;\r\n case LogLevel.Warning:\r\n console.warn(message);\r\n return;\r\n }\r\n },\r\n piiLoggingEnabled: false,\r\n logLevel: LogLevel.Verbose,\r\n },\r\n },\r\n };\r\n };\r\n\r\n /**\r\n * verifies if a string is GUID\r\n * @param guid\r\n */\r\n static isGuid(guid: string): boolean {\r\n const regexGuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\r\n return regexGuid.test(guid);\r\n }\r\n}\r\n","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { LogLevel } from \"@azure/msal-common\"\r\n\r\nexport class Logger {\r\n\r\n /**\r\n * Log an error\r\n * @param {string} log\r\n * @returns {void}\r\n */\r\n static logError(log: string): void {\r\n console.error(this.logMessage(log));\r\n }\r\n\r\n /**\r\n * Log a warning\r\n * @param {string} log\r\n * @returns {void}\r\n */\r\n static logWarning(log: string): void {\r\n console.warn(this.logMessage(log));\r\n }\r\n\r\n /**\r\n * Log anything\r\n * @param {string} log\r\n * @returns {void}\r\n */\r\n static logInfo(log: string): void {\r\n console.info(this.logMessage(log));\r\n }\r\n\r\n /**\r\n * Log message with required options.\r\n * @param {string} logMessage \r\n * @returns {string}\r\n */\r\n private static logMessage(logMessage: string): string {\r\n const timestamp = new Date().toUTCString();\r\n\r\n let logHeader: string = `[${timestamp}]`;\r\n\r\n const log = `${logHeader} : @azure-samples/msal-express-wrapper@0.1.0 : ${LogLevel[LogLevel.Verbose]} - ${logMessage}`;\r\n return log;\r\n }\r\n\r\n}","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport jwt from \"jsonwebtoken\";\r\nimport jwksClient from \"jwks-rsa\";\r\n\r\nimport { \r\n StringUtils, \r\n Constants, \r\n TokenClaims \r\n} from \"@azure/msal-common\";\r\n\r\nimport { Configuration } from \"@azure/msal-node\";\r\n\r\nimport { Logger } from \"./Logger\";\r\n\r\nimport { \r\n AppSettings,\r\n Resource, \r\n IdTokenClaims, \r\n AccessTokenClaims \r\n} from \"./Types\";\r\n\r\nimport { \r\n ErrorMessages, \r\n AADAuthorityConstants \r\n} from \"./Constants\";\r\n\r\nexport class TokenValidator {\r\n private appSettings: AppSettings;\r\n private msalConfig: Configuration;\r\n\r\n /**\r\n * @param {AppSettings} appSettings \r\n * @param {Configuration} msalConfig\r\n * @constructor\r\n */\r\n constructor(appSettings: AppSettings, msalConfig: Configuration) {\r\n this.appSettings = appSettings;\r\n this.msalConfig = msalConfig;\r\n }\r\n\r\n /**\r\n * Verifies a given token's signature using jwks-rsa\r\n * @param {string} authToken \r\n * @returns {Promise}\r\n */\r\n async verifyTokenSignature(authToken: string): Promise {\r\n if (StringUtils.isEmpty(authToken)) {\r\n Logger.logError(ErrorMessages.TOKEN_NOT_FOUND);\r\n return false;\r\n }\r\n\r\n // we will first decode to get kid parameter in header\r\n let decodedToken;\r\n\r\n try {\r\n decodedToken = jwt.decode(authToken, { complete: true });\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.TOKEN_NOT_DECODED);\r\n console.log(error);\r\n return false;\r\n }\r\n\r\n // obtains signing keys from discovery endpoint\r\n let keys;\r\n\r\n try {\r\n keys = await this.getSigningKeys(decodedToken.header, decodedToken.payload.tid);\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.KEYS_NOT_OBTAINED);\r\n console.log(error);\r\n return false;\r\n }\r\n\r\n // verify the signature at header section using keys\r\n let verifiedToken: TokenClaims;\r\n\r\n try {\r\n verifiedToken = jwt.verify(authToken, keys);\r\n\r\n /**\r\n * if a multiplexer was used in place of tenantId i.e. if the app\r\n * is multi-tenant, the tenantId should be obtained from the user\"s\r\n * token\"s tid claim for verification purposes\r\n */\r\n if (\r\n this.appSettings.appCredentials.tenantId === AADAuthorityConstants.COMMON ||\r\n this.appSettings.appCredentials.tenantId === AADAuthorityConstants.ORGANIZATIONS ||\r\n this.appSettings.appCredentials.tenantId === AADAuthorityConstants.CONSUMERS\r\n ) {\r\n this.appSettings.appCredentials.tenantId = decodedToken.payload.tid;\r\n }\r\n\r\n return verifiedToken;\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.TOKEN_NOT_VERIFIED);\r\n console.log(error);\r\n return false;\r\n }\r\n };\r\n\r\n /**\r\n * Verifies the access token for signature\r\n * @param {string} idToken: raw Id token\r\n * @returns {Promise}\r\n */\r\n async validateIdToken(idToken: string): Promise {\r\n try {\r\n const verifiedToken = await this.verifyTokenSignature(idToken);\r\n\r\n if (verifiedToken) {\r\n return this.validateIdTokenClaims(verifiedToken as IdTokenClaims);\r\n } else {\r\n return false;\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n return false;\r\n }\r\n };\r\n\r\n /**\r\n * Validates the id token for a set of claims\r\n * @param {IdTokenClaims} idTokenClaims: decoded id token claims\r\n * @returns {boolean}\r\n */\r\n validateIdTokenClaims(idTokenClaims: IdTokenClaims): boolean {\r\n const now = Math.round(new Date().getTime() / 1000); // in UNIX format\r\n\r\n /**\r\n * At the very least, check for issuer, audience, issue and expiry dates.\r\n * For more information on validating id tokens, visit:\r\n * https://docs.microsoft.com/azure/active-directory/develop/id-tokens#validating-an-id_token\r\n */\r\n const checkIssuer = idTokenClaims.iss.includes(this.appSettings.appCredentials.tenantId) ? true : false;\r\n const checkAudience = idTokenClaims.aud === this.msalConfig.auth.clientId ? true : false;\r\n const checkTimestamp = idTokenClaims.iat <= now && idTokenClaims.exp >= now ? true : false;\r\n\r\n return checkIssuer && checkAudience && checkTimestamp;\r\n };\r\n\r\n /**\r\n * Verifies the access token for signature\r\n * @param {string} accessToken: raw JWT token\r\n * @param {string} protectedRoute: used for checking scope\r\n * @returns {Promise}\r\n */\r\n async verifyAccessTokenSignature(accessToken: string, protectedRoute: string): Promise {\r\n try {\r\n const verifiedToken = await this.verifyTokenSignature(accessToken);\r\n\r\n if (verifiedToken) {\r\n return this.validateAccessTokenClaims(verifiedToken as AccessTokenClaims, protectedRoute);\r\n } else {\r\n return false;\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n return false;\r\n }\r\n };\r\n\r\n /**\r\n * Validates the access token for a set of claims\r\n * @param {TokenClaims} verifiedToken: token with a verified signature\r\n * @param {string} protectedRoute: route where this token is required to access\r\n * @returns {boolean}\r\n */\r\n validateAccessTokenClaims(verifiedToken: AccessTokenClaims, protectedRoute: string): boolean {\r\n const now = Math.round(new Date().getTime() / 1000); // in UNIX format\r\n\r\n /**\r\n * At the very least, validate the token with respect to issuer, audience, scope\r\n * and timestamp, though implementation and extent vary. For more information, visit:\r\n * https://docs.microsoft.com/azure/active-directory/develop/access-tokens#validating-tokens\r\n */\r\n const checkIssuer = verifiedToken.iss.includes(this.appSettings.appCredentials.tenantId) ? true : false;\r\n const checkTimestamp = verifiedToken.iat <= now && verifiedToken.iat >= now ? true : false;\r\n\r\n const checkAudience = verifiedToken.aud === this.appSettings.appCredentials.clientId ||\r\n verifiedToken.aud === \"api://\" + this.appSettings.appCredentials.clientId ? true : false;\r\n\r\n const checkScopes = Object.values(this.appSettings.ownedResources).find((resource: Resource) => resource.endpoint === protectedRoute)\r\n .scopes.every(scp => verifiedToken.scp.includes(scp));\r\n\r\n return checkAudience && checkIssuer && checkTimestamp && checkScopes;\r\n };\r\n\r\n /**\r\n * Fetches signing keys of an access token\r\n * from the authority discovery endpoint\r\n * @param {Object} header: token header\r\n * @param {string} tid: tenant id\r\n * @returns {Promise}\r\n */\r\n private async getSigningKeys(header, tid: string): Promise {\r\n let jwksUri;\r\n\r\n // Check if a B2C application i.e. app has b2cPolicies\r\n if (this.appSettings.b2cPolicies) {\r\n jwksUri = `${this.msalConfig.auth.authority}/discovery/v2.0/keys`;\r\n } else {\r\n jwksUri = `https://${Constants.DEFAULT_AUTHORITY_HOST}/${tid}/discovery/v2.0/keys`;\r\n }\r\n\r\n const client = jwksClient({\r\n jwksUri: jwksUri,\r\n });\r\n\r\n return (await client.getSigningKeyAsync(header.kid)).getPublicKey();\r\n };\r\n}\r\n","import { CertificateClient, KeyVaultCertificate } from \"@azure/keyvault-certificates\";\r\nimport { DefaultAzureCredential } from \"@azure/identity\";\r\nimport { KeyVaultSecret, SecretClient } from \"@azure/keyvault-secrets\";\r\n\r\nimport { AppSettings } from \"./Types\";\r\nimport { KeyVaultCredentialTypes } from \"./Constants\";\r\n\r\nexport class KeyVaultManager {\r\n\r\n /**\r\n * Fetches credentials from Key Vault and updates appSettings\r\n * @param {AppSettings} config \r\n * @returns {Promise}\r\n */\r\n async getCredentialFromKeyVault(config: AppSettings): Promise {\r\n\r\n const credential = new DefaultAzureCredential();\r\n\r\n if (!config.appCredentials.keyVaultCredential) {\r\n return config\r\n }\r\n\r\n switch (config.appCredentials.keyVaultCredential.credentialType) {\r\n case KeyVaultCredentialTypes.SECRET: {\r\n try {\r\n const secretResponse = await this.getSecretCredential(config, credential);\r\n config.appCredentials.clientSecret = secretResponse.value;\r\n return config;\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n break;\r\n }\r\n\r\n case KeyVaultCredentialTypes.CERTIFICATE: {\r\n try {\r\n const certificateResponse = await this.getCertificateCredential(config, credential);\r\n const secretResponse = await this.getSecretCredential(config, credential);\r\n\r\n config.appCredentials.clientCertificate = {\r\n thumbprint: certificateResponse.properties.x509Thumbprint.toString(),\r\n privateKey: secretResponse.value.split('-----BEGIN CERTIFICATE-----\\n')[0]\r\n }\r\n return config;\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n break;\r\n }\r\n\r\n default:\r\n break;\r\n }\r\n };\r\n\r\n /**\r\n * Gets a certificate credential from Key Vault\r\n * @param {AppSettings} config \r\n * @param {DefaultAzureCredential} credential \r\n * @returns {Promise}\r\n */\r\n async getCertificateCredential(config: AppSettings, credential: DefaultAzureCredential): Promise {\r\n\r\n // Initialize secretClient with credentials\r\n const secretClient = new CertificateClient(config.appCredentials.keyVaultCredential.keyVaultUrl, credential);\r\n\r\n try {\r\n const keyVaultCertificate = await secretClient.getCertificate(config.appCredentials.keyVaultCredential.credentialName);\r\n return keyVaultCertificate;\r\n } catch (error) {\r\n console.log(error);\r\n return error;\r\n }\r\n }\r\n\r\n /**\r\n * Gets a secret credential from Key Vault\r\n * @param {AppSettings} config \r\n * @param {DefaultAzureCredential} credential \r\n * @returns {Promise}\r\n */\r\n async getSecretCredential(config: AppSettings, credential: DefaultAzureCredential): Promise {\r\n\r\n // Initialize secretClient with credentials\r\n const secretClient = new SecretClient(config.appCredentials.keyVaultCredential.keyVaultUrl, credential);\r\n\r\n try {\r\n const keyVaultSecret = await secretClient.getSecret(config.appCredentials.keyVaultCredential.credentialName);\r\n return keyVaultSecret;\r\n } catch (error) {\r\n console.log(error);\r\n return error;\r\n }\r\n }\r\n}","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport axios, { AxiosResponse, AxiosRequestConfig } from \"axios\";\r\nimport { StringUtils } from \"@azure/msal-common\";\r\n\r\nimport { \r\n AccessConstants, \r\n InfoMessages, \r\n ErrorMessages \r\n} from \"./Constants\";\r\n\r\nimport { Logger } from \"./Logger\";\r\n\r\nexport class FetchManager {\r\n\r\n /**\r\n * Calls a resource endpoint with a raw access token\r\n * using the authorization bearer token scheme\r\n * @param {string} endpoint \r\n * @param {string} accessToken \r\n * @returns {Promise}\r\n */\r\n static callApiEndpoint = async (endpoint: string, accessToken: string): Promise => {\r\n\r\n if (StringUtils.isEmpty(accessToken)) {\r\n throw new Error(ErrorMessages.TOKEN_NOT_FOUND)\r\n }\r\n\r\n const options: AxiosRequestConfig = {\r\n headers: {\r\n Authorization: `Bearer ${accessToken}`\r\n }\r\n };\r\n\r\n try {\r\n Logger.logInfo(InfoMessages.REQUEST_FOR_RESOURCE);\r\n const response: AxiosResponse = await axios.get(endpoint, options);\r\n return response.data;\r\n } catch (error) {\r\n console.log(error)\r\n return error;\r\n }\r\n }\r\n\r\n /**\r\n * Handles queries against Microsoft Graph that return multiple pages of data \r\n * @param {string} accessToken: access token required by endpoint \r\n * @param {string} nextPage: next page link\r\n * @param {Array} data: stores data from each page\r\n * @returns {Promise}\r\n */\r\n static handlePagination = async (accessToken: string, nextPage: string, data: string[] = []): Promise => {\r\n\r\n try {\r\n const graphResponse = await FetchManager.callApiEndpoint(nextPage, accessToken);\r\n graphResponse[\"value\"].map((v) => data.push(v.id));\r\n \r\n if (graphResponse[AccessConstants.PAGINATION_LINK]) {\r\n return await FetchManager.handlePagination(accessToken, graphResponse[AccessConstants.PAGINATION_LINK], data)\r\n } else {\r\n return data;\r\n }\r\n } catch (error) {\r\n console.log(error);\r\n return error;\r\n }\r\n \r\n }\r\n\r\n}\r\n","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { Request } from \"express\";\r\nimport { IUri, UrlString } from \"@azure/msal-common\";\r\n\r\nexport class UrlUtils {\r\n /**\r\n * Gets the absolute URL from a given request and path string\r\n * @param {Request} req: express request object \r\n * @param {string} url: a given URL\r\n * @returns {string}\r\n */\r\n static ensureAbsoluteUrl = (req: Request, url: string): string => {\r\n const urlComponents: IUri = new UrlString(url).getUrlComponents();\r\n\r\n if (!urlComponents.Protocol) {\r\n if (!urlComponents.HostNameAndPort) {\r\n return req.protocol + \"://\" + req.get(\"host\") + url;\r\n }\r\n return req.protocol + \"://\" + url;\r\n } else {\r\n return url;\r\n }\r\n };\r\n\r\n /**\r\n * Gets the path segment from a given URL\r\n * @param {string} url: a given URL\r\n * @returns {string}\r\n */\r\n static getPathFromUrl = (url: string): string => {\r\n const urlComponents: IUri = new UrlString(url).getUrlComponents();\r\n return `/${urlComponents.PathSegments.join(\"/\")}`;\r\n };\r\n}\r\n","/*\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\nimport express from \"express\";\r\n\r\nimport {\r\n RequestHandler,\r\n Request,\r\n Response,\r\n NextFunction,\r\n Router\r\n} from \"express\";\r\n\r\nimport {\r\n InteractionRequiredAuthError,\r\n OIDC_DEFAULT_SCOPES,\r\n PromptValue,\r\n StringUtils,\r\n} from \"@azure/msal-common\";\r\n\r\nimport {\r\n ConfidentialClientApplication,\r\n Configuration,\r\n AccountInfo,\r\n ICachePlugin,\r\n CryptoProvider,\r\n AuthorizationUrlRequest,\r\n AuthorizationCodeRequest,\r\n SilentFlowRequest,\r\n OnBehalfOfRequest,\r\n} from \"@azure/msal-node\";\r\n\r\nimport { ConfigurationUtils } from \"./ConfigurationUtils\";\r\nimport { TokenValidator } from \"./TokenValidator\";\r\nimport { KeyVaultManager } from \"./KeyVaultManager\";\r\nimport { FetchManager } from \"./FetchManager\";\r\nimport { UrlUtils } from \"./UrlUtils\";\r\nimport { Logger } from \"./Logger\";\r\n\r\nimport {\r\n Resource,\r\n AppSettings,\r\n AuthCodeParams,\r\n InitializationOptions,\r\n TokenRequestOptions,\r\n GuardOptions,\r\n AccessRule,\r\n SignInOptions,\r\n SignOutOptions,\r\n HandleRedirectOptions\r\n} from \"./Types\";\r\n\r\nimport {\r\n AppStages,\r\n ErrorMessages,\r\n AccessConstants,\r\n InfoMessages\r\n} from \"./Constants\";\r\n\r\n/**\r\n * A simple wrapper around MSAL Node ConfidentialClientApplication object.\r\n * It offers a collection of middleware and utility methods that automate\r\n * basic authentication and authorization tasks in Express MVC web apps and\r\n * RESTful APIs (coming soon).\r\n */\r\nexport class AuthProvider {\r\n appSettings: AppSettings;\r\n private msalConfig: Configuration;\r\n private cryptoProvider: CryptoProvider;\r\n private tokenValidator: TokenValidator;\r\n private msalClient: ConfidentialClientApplication;\r\n\r\n /**\r\n * @param {AppSettings} appSettings\r\n * @param {ICachePlugin} cache: cachePlugin\r\n * @constructor\r\n */\r\n constructor(appSettings: AppSettings, cache?: ICachePlugin) {\r\n ConfigurationUtils.validateAppSettings(appSettings);\r\n this.appSettings = appSettings;\r\n\r\n this.msalConfig = ConfigurationUtils.getMsalConfiguration(appSettings, cache);\r\n this.msalClient = new ConfidentialClientApplication(this.msalConfig);\r\n\r\n this.tokenValidator = new TokenValidator(this.appSettings, this.msalConfig);\r\n this.cryptoProvider = new CryptoProvider();\r\n }\r\n\r\n /**\r\n * Asynchronously builds authProvider object with credentials fetched from Key Vault\r\n * @param {AppSettings} appSettings\r\n * @param {ICachePlugin} cache: cachePlugin\r\n * @returns \r\n */\r\n static async buildAsync(appSettings: AppSettings, cache?: ICachePlugin): Promise {\r\n try {\r\n const keyVault = new KeyVaultManager();\r\n const appSettingsWithKeyVaultCredentials = await keyVault.getCredentialFromKeyVault(appSettings);\r\n const authProvider = new AuthProvider(appSettingsWithKeyVaultCredentials, cache);\r\n return authProvider;\r\n } catch (error) {\r\n console.log(error);\r\n }\r\n }\r\n\r\n /**\r\n * Initialize AuthProvider and set default routes and handlers\r\n * @param {InitializationOptions} options\r\n * @returns {Router}\r\n */\r\n initialize = (options?: InitializationOptions): Router => {\r\n\r\n // TODO: initialize app defaults\r\n\r\n const appRouter = express.Router();\r\n\r\n // handle redirect\r\n appRouter.get(UrlUtils.getPathFromUrl(this.appSettings.authRoutes.redirect), this.handleRedirect());\r\n\r\n if (this.appSettings.authRoutes.frontChannelLogout) {\r\n /**\r\n * Expose front-channel logout route. For more information, visit: \r\n * https://docs.microsoft.com/azure/active-directory/develop/v2-protocols-oidc#single-sign-out\r\n */\r\n appRouter.get(this.appSettings.authRoutes.frontChannelLogout, (req, res, next) => {\r\n req.session.destroy(() => {\r\n res.sendStatus(200);\r\n });\r\n });\r\n }\r\n\r\n return appRouter;\r\n }\r\n\r\n // ========== ROUTE HANDLERS ===========\r\n\r\n /**\r\n * Initiates sign in flow\r\n * @param {SignInOptions} options: options to modify login request\r\n * @returns {RequestHandler}\r\n */\r\n signIn = (options?: SignInOptions): RequestHandler => {\r\n return (req: Request, res: Response, next: NextFunction): Promise => {\r\n /**\r\n * Request Configuration\r\n * We manipulate these three request objects below\r\n * to acquire a token with the appropriate claims\r\n */\r\n if (!req.session[\"authCodeRequest\"]) {\r\n req.session.authCodeRequest = {\r\n authority: \"\",\r\n scopes: [],\r\n state: {},\r\n redirectUri: \"\",\r\n } as AuthorizationUrlRequest;\r\n }\r\n\r\n if (!req.session[\"tokenRequest\"]) {\r\n req.session.tokenRequest = {\r\n authority: \"\",\r\n scopes: [],\r\n redirectUri: \"\",\r\n code: \"\",\r\n } as AuthorizationCodeRequest;\r\n }\r\n\r\n // signed-in user's account\r\n if (!req.session[\"account\"]) {\r\n req.session.account = {\r\n homeAccountId: \"\",\r\n environment: \"\",\r\n tenantId: \"\",\r\n username: \"\",\r\n idTokenClaims: {},\r\n } as AccountInfo;\r\n }\r\n\r\n // random GUID for csrf protection\r\n req.session.nonce = this.cryptoProvider.createNewGuid();\r\n \r\n // TODO: encrypt state parameter \r\n const state = this.cryptoProvider.base64Encode(\r\n JSON.stringify({\r\n stage: AppStages.SIGN_IN,\r\n path: options.successRedirect,\r\n nonce: req.session.nonce,\r\n })\r\n );\r\n\r\n const params: AuthCodeParams = {\r\n authority: this.msalConfig.auth.authority,\r\n scopes: OIDC_DEFAULT_SCOPES,\r\n state: state,\r\n redirect: UrlUtils.ensureAbsoluteUrl(req, this.appSettings.authRoutes.redirect),\r\n prompt: PromptValue.SELECT_ACCOUNT,\r\n };\r\n\r\n // get url to sign user in\r\n return this.getAuthCode(req, res, next, params);\r\n }\r\n };\r\n\r\n /**\r\n * Initiate sign out and destroy the session\r\n * @param options: options to modify logout request \r\n * @returns {RequestHandler}\r\n */\r\n signOut = (options?: SignOutOptions): RequestHandler => {\r\n return (req: Request, res: Response, next: NextFunction): void => {\r\n const postLogoutRedirectUri = UrlUtils.ensureAbsoluteUrl(req, options.successRedirect);\r\n\r\n /**\r\n * Construct a logout URI and redirect the user to end the\r\n * session with Azure AD/B2C. For more information, visit:\r\n * (AAD) https://docs.microsoft.com/azure/active-directory/develop/v2-protocols-oidc#send-a-sign-out-request\r\n * (B2C) https://docs.microsoft.com/azure/active-directory-b2c/openid-connect#send-a-sign-out-request\r\n */\r\n const logoutURI = `${this.msalConfig.auth.authority}/oauth2/v2.0/logout?post_logout_redirect_uri=${postLogoutRedirectUri}`;\r\n\r\n req.session.isAuthenticated = false;\r\n\r\n req.session.destroy(() => {\r\n res.redirect(logoutURI);\r\n });\r\n }\r\n };\r\n\r\n /**\r\n * Middleware that handles redirect depending on request state\r\n * There are basically 2 stages: sign-in and acquire token\r\n * @param {HandleRedirectOptions} options: options to modify this middleware\r\n * @returns {RequestHandler}\r\n */\r\n private handleRedirect = (options?: HandleRedirectOptions): RequestHandler => {\r\n return async (req: Request, res: Response, next: NextFunction): Promise => {\r\n if (req.query.state) {\r\n const state = JSON.parse(this.cryptoProvider.base64Decode(req.query.state as string));\r\n\r\n // check if nonce matches\r\n if (state.nonce === req.session.nonce) {\r\n switch (state.stage) {\r\n case AppStages.SIGN_IN: {\r\n // token request should have auth code\r\n req.session.tokenRequest.code = req.query.code as string;\r\n\r\n try {\r\n // exchange auth code for tokens\r\n const tokenResponse = await this.msalClient.acquireTokenByCode(req.session.tokenRequest);\r\n\r\n try {\r\n const isIdTokenValid = await this.tokenValidator.validateIdToken(tokenResponse.idToken);\r\n\r\n if (isIdTokenValid) {\r\n // assign session variables\r\n req.session.account = tokenResponse.account;\r\n req.session.isAuthenticated = true;\r\n\r\n res.redirect(state.path);\r\n } else {\r\n Logger.logError(ErrorMessages.INVALID_TOKEN);\r\n res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.CANNOT_VALIDATE_TOKEN);\r\n next(error)\r\n }\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.TOKEN_ACQUISITION_FAILED);\r\n next(error)\r\n }\r\n break;\r\n }\r\n\r\n case AppStages.ACQUIRE_TOKEN: {\r\n // get the name of the resource associated with scope\r\n const resourceName = this.getResourceNameFromScopes(req.session.tokenRequest.scopes);\r\n\r\n req.session.tokenRequest.code = req.query.code as string\r\n\r\n try {\r\n const tokenResponse = await this.msalClient.acquireTokenByCode(req.session.tokenRequest);\r\n req.session.remoteResources[resourceName].accessToken = tokenResponse.accessToken;\r\n res.redirect(state.path);\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.TOKEN_ACQUISITION_FAILED);\r\n next(error);\r\n }\r\n break;\r\n }\r\n\r\n default:\r\n Logger.logError(ErrorMessages.CANNOT_DETERMINE_APP_STAGE);\r\n res.redirect(this.appSettings.authRoutes.error);\r\n break;\r\n }\r\n } else {\r\n Logger.logError(ErrorMessages.NONCE_MISMATCH);\r\n res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n } else {\r\n Logger.logError(ErrorMessages.STATE_NOT_FOUND)\r\n res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n }\r\n };\r\n\r\n // ========== MIDDLEWARE ===========\r\n\r\n /**\r\n * Middleware that gets tokens via acquireToken*\r\n * @param {TokenRequestOptions} options: options to modify this middleware\r\n * @returns {RequestHandler}\r\n */\r\n getToken = (options: TokenRequestOptions): RequestHandler => {\r\n return async (req: Request, res: Response, next: NextFunction): Promise => {\r\n // get scopes for token request\r\n const scopes = options.resource.scopes;\r\n\r\n const resourceName = this.getResourceNameFromScopes(scopes)\r\n\r\n if (!req.session.remoteResources) {\r\n req.session.remoteResources = {};\r\n }\r\n\r\n req.session.remoteResources = {\r\n [resourceName]: {\r\n ...this.appSettings.remoteResources[resourceName],\r\n accessToken: null,\r\n } as Resource\r\n };\r\n\r\n try {\r\n const silentRequest: SilentFlowRequest = {\r\n account: req.session.account,\r\n scopes: scopes,\r\n };\r\n\r\n // acquire token silently to be used in resource call\r\n const tokenResponse = await this.msalClient.acquireTokenSilent(silentRequest);\r\n\r\n // In B2C scenarios, sometimes an access token is returned empty.\r\n // In that case, we will acquire token interactively instead.\r\n if (StringUtils.isEmpty(tokenResponse.accessToken)) {\r\n Logger.logError(ErrorMessages.TOKEN_NOT_FOUND);\r\n throw new InteractionRequiredAuthError(ErrorMessages.INTERACTION_REQUIRED);\r\n }\r\n\r\n req.session.remoteResources[resourceName].accessToken = tokenResponse.accessToken;\r\n next();\r\n } catch (error) {\r\n // in case there are no cached tokens, initiate an interactive call\r\n if (error instanceof InteractionRequiredAuthError) {\r\n const state = this.cryptoProvider.base64Encode(\r\n JSON.stringify({\r\n stage: AppStages.ACQUIRE_TOKEN,\r\n path: req.originalUrl,\r\n nonce: req.session.nonce,\r\n })\r\n );\r\n\r\n const params: AuthCodeParams = {\r\n authority: this.msalConfig.auth.authority,\r\n scopes: scopes,\r\n state: state,\r\n redirect: UrlUtils.ensureAbsoluteUrl(req, this.appSettings.authRoutes.redirect),\r\n account: req.session.account,\r\n };\r\n\r\n // initiate the first leg of auth code grant to get token\r\n return this.getAuthCode(req, res, next, params);\r\n } else {\r\n next(error);\r\n }\r\n }\r\n }\r\n };\r\n\r\n /**\r\n * Middleware that gets tokens via OBO flow. Used in web API scenarios\r\n * @param {TokenRequestOptions} options: options to modify this middleware\r\n * @returns {RequestHandler}\r\n */\r\n getTokenOnBehalf = (options: TokenRequestOptions): RequestHandler => {\r\n return async (req: Request, res: Response, next: NextFunction): Promise => {\r\n const authHeader = req.headers.authorization;\r\n\r\n // get scopes for token request\r\n const scopes = options.resource.scopes;\r\n const resourceName = this.getResourceNameFromScopes(scopes);\r\n\r\n const oboRequest: OnBehalfOfRequest = {\r\n oboAssertion: authHeader.split(\" \")[1],\r\n scopes: scopes,\r\n }\r\n\r\n try {\r\n const tokenResponse = await this.msalClient.acquireTokenOnBehalfOf(oboRequest);\r\n\r\n // as OBO is commonly used in middle-tier web APIs without sessions, attach AT to req\r\n req[\"locals\"] = {\r\n [resourceName]: {\r\n accessToken: tokenResponse.accessToken\r\n }\r\n }\r\n\r\n next();\r\n } catch (error) {\r\n next(error);\r\n }\r\n }\r\n }\r\n\r\n // ============== GUARDS ===============\r\n\r\n /**\r\n * Check if authenticated in session\r\n * @param {GuardOptions} options: options to modify this middleware\r\n * @returns {RequestHandler}\r\n */\r\n isAuthenticated = (options?: GuardOptions): RequestHandler => {\r\n return (req: Request, res: Response, next: NextFunction): void => {\r\n if (req.session) {\r\n if (!req.session.isAuthenticated) {\r\n Logger.logError(ErrorMessages.NOT_PERMITTED);\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n\r\n next();\r\n } else {\r\n Logger.logError(ErrorMessages.SESSION_NOT_FOUND);\r\n res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n }\r\n };\r\n\r\n /**\r\n * Receives access token in req authorization header\r\n * and validates it using the jwt.verify\r\n * @param {GuardOptions} options: options to modify this middleware\r\n * @returns {RequestHandler}\r\n */\r\n isAuthorized = (options?: GuardOptions): RequestHandler => {\r\n return async (req: Request, res: Response, next: NextFunction): Promise => {\r\n const accessToken = req.headers.authorization.split(\" \")[1];\r\n\r\n if (req.headers.authorization) {\r\n if (!(await this.tokenValidator.verifyAccessTokenSignature(accessToken, `${req.baseUrl}${req.path}`))) {\r\n Logger.logError(ErrorMessages.INVALID_TOKEN);\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n\r\n next();\r\n } else {\r\n Logger.logError(ErrorMessages.TOKEN_NOT_FOUND);\r\n res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n }\r\n };\r\n\r\n /**\r\n * Checks if the user has access for this route, defined in access matrix\r\n * @param {GuardOptions} options: options to modify this middleware\r\n * @returns {RequestHandler}\r\n */\r\n hasAccess = (options?: GuardOptions): RequestHandler => {\r\n return async (req: Request, res: Response, next: NextFunction): Promise => {\r\n if (req.session && this.appSettings.accessMatrix) {\r\n\r\n const checkFor = options.accessRule.hasOwnProperty(AccessConstants.GROUPS) ? AccessConstants.GROUPS : AccessConstants.ROLES;\r\n\r\n switch (checkFor) {\r\n case AccessConstants.GROUPS:\r\n\r\n if (req.session.account.idTokenClaims[AccessConstants.GROUPS] === undefined) {\r\n if (req.session.account.idTokenClaims[AccessConstants.CLAIM_NAMES] || req.session.account.idTokenClaims[AccessConstants.CLAIM_SOURCES]) {\r\n Logger.logWarning(InfoMessages.OVERAGE_OCCURRED)\r\n return await this.handleOverage(req, res, next, options.accessRule);\r\n } else {\r\n Logger.logError(ErrorMessages.USER_HAS_NO_GROUP);\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n } else {\r\n const groups = req.session.account.idTokenClaims[AccessConstants.GROUPS];\r\n\r\n if (!this.checkAccessRule(req.method, options.accessRule, groups, AccessConstants.GROUPS)) {\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n }\r\n\r\n next();\r\n break;\r\n\r\n case AccessConstants.ROLES:\r\n if (req.session.account.idTokenClaims[AccessConstants.ROLES] === undefined) {\r\n Logger.logError(ErrorMessages.USER_HAS_NO_ROLE);\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n } else {\r\n const roles = req.session.account.idTokenClaims[AccessConstants.ROLES];\r\n\r\n if (!this.checkAccessRule(req.method, options.accessRule, roles, AccessConstants.ROLES)) {\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n }\r\n\r\n next();\r\n break;\r\n\r\n default:\r\n break;\r\n }\r\n } else {\r\n res.redirect(this.appSettings.authRoutes.unauthorized);\r\n }\r\n }\r\n }\r\n\r\n // ============== UTILS ===============\r\n\r\n /**\r\n * This method is used to generate an auth code url request\r\n * @param {Request} req: express request object\r\n * @param {Response} res: express response object\r\n * @param {NextFunction} next: express next function\r\n * @param {AuthCodeParams} params: modifies auth code url request\r\n * @returns {Promise}\r\n */\r\n private async getAuthCode(req: Request, res: Response, next: NextFunction, params: AuthCodeParams): Promise {\r\n // prepare the request\r\n req.session.authCodeRequest.authority = params.authority;\r\n req.session.authCodeRequest.scopes = params.scopes;\r\n req.session.authCodeRequest.state = params.state;\r\n req.session.authCodeRequest.redirectUri = params.redirect;\r\n req.session.authCodeRequest.prompt = params.prompt;\r\n req.session.authCodeRequest.account = params.account;\r\n\r\n req.session.tokenRequest.authority = params.authority;\r\n req.session.tokenRequest.scopes = params.scopes;\r\n req.session.tokenRequest.redirectUri = params.redirect;\r\n\r\n // request an authorization code to exchange for tokens\r\n try {\r\n const response = await this.msalClient.getAuthCodeUrl(req.session.authCodeRequest);\r\n res.redirect(response);\r\n } catch (error) {\r\n Logger.logError(ErrorMessages.AUTH_CODE_NOT_OBTAINED);\r\n next(error);\r\n }\r\n };\r\n\r\n /**\r\n * Handles group overage claims by querying MS Graph /memberOf endpoint\r\n * @param {Request} req: express request object\r\n * @param {Response} res: express response object\r\n * @param {NextFunction} next: express next function\r\n * @param {AccessRule} rule: a given access rule\r\n * @returns {Promise}\r\n */\r\n private async handleOverage(req: Request, res: Response, next: NextFunction, rule: AccessRule): Promise {\r\n const { _claim_names, _claim_sources, ...newIdTokenClaims } = req.session.account.idTokenClaims;\r\n\r\n const silentRequest: SilentFlowRequest = {\r\n account: req.session.account,\r\n scopes: AccessConstants.GRAPH_MEMBER_SCOPES.split(\" \"),\r\n };\r\n\r\n try {\r\n // acquire token silently to be used in resource call\r\n const tokenResponse = await this.msalClient.acquireTokenSilent(silentRequest);\r\n try {\r\n const graphResponse = await FetchManager.callApiEndpoint(AccessConstants.GRAPH_MEMBERS_ENDPOINT, tokenResponse.accessToken);\r\n\r\n /**\r\n * Some queries against Microsoft Graph return multiple pages of data either due to server-side paging \r\n * or due to the use of the $top query parameter to specifically limit the page size in a request. \r\n * When a result set spans multiple pages, Microsoft Graph returns an @odata.nextLink property in \r\n * the response that contains a URL to the next page of results. Learn more at https://docs.microsoft.com/graph/paging\r\n */\r\n if (graphResponse[AccessConstants.PAGINATION_LINK]) {\r\n try {\r\n const userGroups = await FetchManager.handlePagination(tokenResponse.accessToken, graphResponse[AccessConstants.PAGINATION_LINK]);\r\n\r\n req.session.account.idTokenClaims = {\r\n ...newIdTokenClaims,\r\n groups: userGroups\r\n }\r\n\r\n if (!this.checkAccessRule(req.method, rule, req.session.account.idTokenClaims[AccessConstants.GROUPS], AccessConstants.GROUPS)) {\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n } else {\r\n return next();\r\n }\r\n } catch (error) {\r\n next(error);\r\n }\r\n } else {\r\n req.session.account.idTokenClaims = {\r\n ...newIdTokenClaims,\r\n groups: graphResponse[\"value\"].map((v) => v.id)\r\n }\r\n\r\n if (!this.checkAccessRule(req.method, rule, req.session.account.idTokenClaims[AccessConstants.GROUPS], AccessConstants.GROUPS)) {\r\n return res.redirect(this.appSettings.authRoutes.unauthorized);\r\n } else {\r\n return next();\r\n }\r\n }\r\n } catch (error) {\r\n next(error);\r\n }\r\n } catch (error) {\r\n next(error);\r\n }\r\n }\r\n\r\n /**\r\n * Checks if the request passes a given access rule\r\n * @param {string} method: HTTP method for this route\r\n * @param {AccessRule} rule: access rule for this route\r\n * @param {Array} creds: user's credentials i.e. roles or groups\r\n * @param {string} credType: roles or groups\r\n * @returns {boolean}\r\n */\r\n private checkAccessRule(method: string, rule: AccessRule, creds: string[], credType: string): boolean {\r\n if (rule.methods.includes(method)) {\r\n switch (credType) {\r\n case AccessConstants.GROUPS:\r\n if (rule.groups.filter(elem => creds.includes(elem)).length < 1) {\r\n Logger.logError(ErrorMessages.USER_NOT_IN_GROUP);\r\n return false;\r\n }\r\n break;\r\n\r\n case AccessConstants.ROLES:\r\n if (rule.roles.filter(elem => creds.includes(elem)).length < 1) {\r\n Logger.logError(ErrorMessages.USER_NOT_IN_ROLE);\r\n return false;\r\n }\r\n break;\r\n\r\n default:\r\n break;\r\n }\r\n } else {\r\n Logger.logError(ErrorMessages.METHOD_NOT_ALLOWED);\r\n return false;\r\n }\r\n\r\n return true;\r\n }\r\n\r\n /**\r\n * Util method to get the resource name for a given scope(s)\r\n * @param {Array} scopes: an array of scopes that the resource is associated with\r\n * @returns {string}\r\n */\r\n private getResourceNameFromScopes(scopes: string[]): string {\r\n // TODO: deep check equality here \r\n\r\n const index = Object.values({ ...this.appSettings.remoteResources, ...this.appSettings.ownedResources })\r\n .findIndex((resource: Resource) => JSON.stringify(resource.scopes) === JSON.stringify(scopes));\r\n\r\n const resourceName = Object.keys({ ...this.appSettings.remoteResources, ...this.appSettings.ownedResources })[index];\r\n return resourceName;\r\n };\r\n}\r\n"],"names":["undefined","AppStages","SIGN_IN","SIGN_OUT","ACQUIRE_TOKEN","AADAuthorityConstants","COMMON","ORGANIZATIONS","CONSUMERS","KeyVaultCredentialTypes","SECRET","CERTIFICATE","AccessConstants","GROUPS","ROLES","CLAIM_NAMES","CLAIM_SOURCES","PAGINATION_LINK","GRAPH_MEMBERS_ENDPOINT","GRAPH_MEMBER_SCOPES","InfoMessages","REQUEST_FOR_RESOURCE","OVERAGE_OCCURRED","ErrorMessages","NOT_PERMITTED","INVALID_TOKEN","CANNOT_DETERMINE_APP_STAGE","CANNOT_VALIDATE_TOKEN","NONCE_MISMATCH","INTERACTION_REQUIRED","TOKEN_ACQUISITION_FAILED","AUTH_CODE_NOT_OBTAINED","TOKEN_NOT_FOUND","TOKEN_NOT_DECODED","TOKEN_NOT_VERIFIED","KEYS_NOT_OBTAINED","STATE_NOT_FOUND","USER_HAS_NO_ROLE","USER_NOT_IN_ROLE","USER_HAS_NO_GROUP","USER_NOT_IN_GROUP","METHOD_NOT_ALLOWED","RULE_NOT_FOUND","SESSION_NOT_FOUND","KEY_VAULT_CONFIG_NOT_FOUND","ConfigurationErrorMessages","NO_CLIENT_ID","INVALID_CLIENT_ID","NO_TENANT_INFO","INVALID_TENANT_INFO","NO_CLIENT_CREDENTIAL","NO_REDIRECT_URI","NO_ERROR_ROUTE","NO_UNAUTHORIZED_ROUTE","ErrorCodes","ConfigurationUtils","validateAppSettings","config","StringUtils","isEmpty","appCredentials","clientId","Error","isGuid","tenantId","Object","values","includes","clientSecret","clientCertificate","authRoutes","redirect","error","unauthorized","getMsalConfiguration","cachePlugin","auth","authority","b2cPolicies","entries","Constants","DEFAULT_AUTHORITY_HOST","hasOwnProperty","knownAuthorities","UrlString","getDomainFromUrl","cache","system","loggerOptions","loggerCallback","logLevel","message","containsPii","LogLevel","console","Info","info","Verbose","debug","Warning","warn","piiLoggingEnabled","guid","regexGuid","test","Logger","logError","log","logMessage","logWarning","logInfo","timestamp","Date","toUTCString","logHeader","TokenValidator","appSettings","msalConfig","verifyTokenSignature","authToken","decodedToken","jwt","decode","complete","getSigningKeys","header","payload","tid","keys","verifiedToken","verify","validateIdToken","idToken","validateIdTokenClaims","idTokenClaims","now","Math","round","getTime","checkIssuer","iss","checkAudience","aud","checkTimestamp","iat","exp","verifyAccessTokenSignature","accessToken","protectedRoute","validateAccessTokenClaims","checkScopes","ownedResources","find","resource","endpoint","scopes","every","scp","jwksUri","client","jwksClient","getSigningKeyAsync","kid","getPublicKey","KeyVaultManager","getCredentialFromKeyVault","credential","DefaultAzureCredential","keyVaultCredential","credentialType","getSecretCredential","secretResponse","value","getCertificateCredential","certificateResponse","thumbprint","properties","x509Thumbprint","toString","privateKey","split","secretClient","CertificateClient","keyVaultUrl","getCertificate","credentialName","keyVaultCertificate","SecretClient","getSecret","keyVaultSecret","FetchManager","options","headers","Authorization","axios","get","response","data","nextPage","callApiEndpoint","graphResponse","map","v","push","id","handlePagination","UrlUtils","req","url","urlComponents","getUrlComponents","Protocol","HostNameAndPort","protocol","PathSegments","join","AuthProvider","appRouter","express","Router","getPathFromUrl","handleRedirect","frontChannelLogout","res","next","session","destroy","sendStatus","authCodeRequest","state","redirectUri","tokenRequest","code","account","homeAccountId","environment","username","nonce","cryptoProvider","createNewGuid","base64Encode","JSON","stringify","stage","path","successRedirect","params","OIDC_DEFAULT_SCOPES","ensureAbsoluteUrl","prompt","PromptValue","SELECT_ACCOUNT","getAuthCode","postLogoutRedirectUri","logoutURI","isAuthenticated","query","parse","base64Decode","msalClient","acquireTokenByCode","tokenResponse","tokenValidator","isIdTokenValid","resourceName","getResourceNameFromScopes","remoteResources","silentRequest","acquireTokenSilent","InteractionRequiredAuthError","originalUrl","authHeader","authorization","oboRequest","oboAssertion","acquireTokenOnBehalfOf","baseUrl","accessMatrix","checkFor","accessRule","handleOverage","groups","checkAccessRule","method","roles","ConfidentialClientApplication","CryptoProvider","buildAsync","keyVault","appSettingsWithKeyVaultCredentials","authProvider","getAuthCodeUrl","rule","_claim_names","newIdTokenClaims","userGroups","creds","credType","methods","filter","elem","length","index","findIndex"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,OAAO,IAAI,UAAU,OAAO,EAAE;AAElC;AACA,EAAE,IAAI,EAAE,GAAG,MAAM,CAAC,SAAS,CAAC;AAC5B,EAAE,IAAI,MAAM,GAAG,EAAE,CAAC,cAAc,CAAC;AACjC,EAAE,IAAIA,WAAS,CAAC;AAChB,EAAE,IAAI,OAAO,GAAG,OAAO,MAAM,KAAK,UAAU,GAAG,MAAM,GAAG,EAAE,CAAC;AAC3D,EAAE,IAAI,cAAc,GAAG,OAAO,CAAC,QAAQ,IAAI,YAAY,CAAC;AACxD,EAAE,IAAI,mBAAmB,GAAG,OAAO,CAAC,aAAa,IAAI,iBAAiB,CAAC;AACvE,EAAE,IAAI,iBAAiB,GAAG,OAAO,CAAC,WAAW,IAAI,eAAe,CAAC;AACjE;AACA,EAAE,SAAS,MAAM,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE;AACnC,IAAI,MAAM,CAAC,cAAc,CAAC,GAAG,EAAE,GAAG,EAAE;AACpC,MAAM,KAAK,EAAE,KAAK;AAClB,MAAM,UAAU,EAAE,IAAI;AACtB,MAAM,YAAY,EAAE,IAAI;AACxB,MAAM,QAAQ,EAAE,IAAI;AACpB,KAAK,CAAC,CAAC;AACP,IAAI,OAAO,GAAG,CAAC,GAAG,CAAC,CAAC;AACpB,GAAG;AACH,EAAE,IA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ts b/src/AuthProvider.ts index 12aa3ec..9843dc5 100644 --- a/src/AuthProvider.ts +++ b/src/AuthProvider.ts @@ -116,7 +116,7 @@ export class AuthProvider { const appRouter = express.Router(); // handle redirect - appRouter.get(this.appSettings.authRoutes.redirect, this.handleRedirect()); + appRouter.get(UrlUtils.getPathFromUrl(this.appSettings.authRoutes.redirect), this.handleRedirect()); if (this.appSettings.authRoutes.frontChannelLogout) { /** diff --git a/src/UrlUtils.ts b/src/UrlUtils.ts index 0774ba4..0581983 100644 --- a/src/UrlUtils.ts +++ b/src/UrlUtils.ts @@ -25,4 +25,14 @@ export class UrlUtils { return url; } }; + + /** + * Gets the path segment from a given URL + * @param {string} url: a given URL + * @returns {string} + */ + static getPathFromUrl = (url: string): string => { + const urlComponents: IUri = new UrlString(url).getUrlComponents(); + return `/${urlComponents.PathSegments.join("/")}`; + }; }