UNPKG

cbp-js

Version:

Compiled Libraries for cbp

1,844 lines (1,577 loc) 94.4 kB
import axios from 'axios'; import { object, string, boolean } from 'yup'; import SHA256 from 'crypto-js/sha256'; import CryptoJS from 'crypto-js'; import crypto from 'crypto'; function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function (obj) { return typeof obj; }; } else { _typeof = function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _construct(Parent, args, Class) { if (isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } var BaseError = /*#__PURE__*/ function (_Error) { _inherits(BaseError, _Error); function BaseError(error) { var _this; _classCallCheck(this, BaseError); _this = _possibleConstructorReturn(this, _getPrototypeOf(BaseError).call(this, error)); _this.name = 'BaseError'; _this.message = error; _this.stackTrace = _this.stackTrace; return _this; } _createClass(BaseError, [{ key: "toString", value: function toString() { return { message: this.message, stackTrace: this.stackTrace }; } }, { key: "toJson", value: function toJson() { return { name: this.name, message: this.message, stackTrace: this.stackTrace }; } }]); return BaseError; }(_wrapNativeSuper(Error)); var ArgumentError = /*#__PURE__*/ function (_BaseError) { _inherits(ArgumentError, _BaseError); function ArgumentError(error) { var _this2; _classCallCheck(this, ArgumentError); _this2 = _possibleConstructorReturn(this, _getPrototypeOf(ArgumentError).call(this, error)); _this2.name = 'ArgumentError'; _this2.message = error; return _this2; } return ArgumentError; }(BaseError); var Validation = /*#__PURE__*/ function () { function Validation() { _classCallCheck(this, Validation); } _createClass(Validation, null, [{ key: "isEmpty", value: function isEmpty(value) { if (_typeof(value) === 'object') return Validation.isEmptyObject(value); if (!value || value === 'undefined' || value == '' || value == ' ' || value === null) { return true; } else { return false; } } }, { key: "isEmptyObject", value: function isEmptyObject(obj) { for (var key in obj) { if (obj.hasOwnProperty(key)) return false; } return true; } }, { key: "removeNullKey", value: function removeNullKey(obj) { var newObj = Object.assign({}, obj); for (var key in newObj) { if (newObj.hasOwnProperty(key)) { if (this.isEmpty(newObj[key])) { delete newObj[key]; } } } return newObj; } }]); return Validation; }(); /** * Helper function: * Make a call to the specified requestPath, and when the * results are done, invoke the callback. * * @param {String} requestMethod - the HTTP method (GET, POST, etc) * @param {String} requestPath - the request path (e.g., /lists, /items, etc) * @param {String} postData - a JSON string (must be well-formed) containing any * data that is to be sent in the request body * @param {Object} headers - additional HTTP headers * */ var httpRequest = function httpRequest(requestMethod, requestPath) { var postData = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; var headers = arguments.length > 3 ? arguments[3] : undefined; var options = ''; if (requestMethod == 'GET') { options = _objectSpread2({}, headers); return new Promise(function (resolve, reject) { axios.get(requestPath, options).then(function (result) { resolve(result.data); })["catch"](function (error) { reject(error); }); }); } else { options = _objectSpread2({ method: requestMethod, url: requestPath, data: postData }, headers); return new Promise(function (resolve, reject) { axios.request(options).then(function (result) { resolve(result.data); })["catch"](function (error) { reject(error); }); }); } }; var Schema = { authClientOptions: object().shape({ storage: object(), authorization_server: string().required(), authentication_endpoint: string().required(), token_endpoint: string().required(), token_endpoint_auth_method: string(), client_id: string().required(), client_secret: string(), grant_type: string(), userinfo_endpoint: string(), monitor_session: boolean(), check_session_iframe: string(), // for oidc end_session_endpoint: string(), // for oidc post_logout_redirect_uri: string(), // for oidc prompt: string(), // for oidc display: string(), // for oidc scope: string(), // for oidc response_type: string(), // for oidc redirect_uri: string(), // for oidc nonce: string(), state: string() }), mgmtClientOptions: object().shape({ resource_endpoint: string().required(), client_id: string(), // [optional] token: string() }) }; var validateSchema = function validateSchema(schema, data) { return new Promise(function (resolve, reject) { schema.validate(data)["catch"](function (error) { reject(error); }); }); }; var AuthenticationManager = /*#__PURE__*/ function () { function AuthenticationManager(options) { _classCallCheck(this, AuthenticationManager); if (_typeof(options) !== 'object') { throw new ArgumentError('argument options must be type \'object\''); } this.options = options; // validate options validateSchema(Schema.authClientOptions, options)["catch"](function (error) { throw new ArgumentError(error); }); } _createClass(AuthenticationManager, [{ key: "getToken", value: function getToken() {} }]); return AuthenticationManager; }(); var strictUriEncode = str => encodeURIComponent(str).replace(/[!'()*]/g, x => `%${x.charCodeAt(0).toString(16).toUpperCase()}`); var token = '%[a-f0-9]{2}'; var singleMatcher = new RegExp(token, 'gi'); var multiMatcher = new RegExp('(' + token + ')+', 'gi'); function decodeComponents(components, split) { try { // Try to decode the entire string first return decodeURIComponent(components.join('')); } catch (err) { // Do nothing } if (components.length === 1) { return components; } split = split || 1; // Split the array in 2 parts var left = components.slice(0, split); var right = components.slice(split); return Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right)); } function decode(input) { try { return decodeURIComponent(input); } catch (err) { var tokens = input.match(singleMatcher); for (var i = 1; i < tokens.length; i++) { input = decodeComponents(tokens, i).join(''); tokens = input.match(singleMatcher); } return input; } } function customDecodeURIComponent(input) { // Keep track of all the replacements and prefill the map with the `BOM` var replaceMap = { '%FE%FF': '\uFFFD\uFFFD', '%FF%FE': '\uFFFD\uFFFD' }; var match = multiMatcher.exec(input); while (match) { try { // Decode as big chunks as possible replaceMap[match[0]] = decodeURIComponent(match[0]); } catch (err) { var result = decode(match[0]); if (result !== match[0]) { replaceMap[match[0]] = result; } } match = multiMatcher.exec(input); } // Add `%C2` at the end of the map to make sure it does not replace the combinator before everything else replaceMap['%C2'] = '\uFFFD'; var entries = Object.keys(replaceMap); for (var i = 0; i < entries.length; i++) { // Replace all decoded components var key = entries[i]; input = input.replace(new RegExp(key, 'g'), replaceMap[key]); } return input; } var decodeUriComponent = function (encodedURI) { if (typeof encodedURI !== 'string') { throw new TypeError('Expected `encodedURI` to be of type `string`, got `' + typeof encodedURI + '`'); } try { encodedURI = encodedURI.replace(/\+/g, ' '); // Try the built in decoder first return decodeURIComponent(encodedURI); } catch (err) { // Fallback to a more advanced decoder return customDecodeURIComponent(encodedURI); } }; var splitOnFirst = (string, separator) => { if (!(typeof string === 'string' && typeof separator === 'string')) { throw new TypeError('Expected the arguments to be of type `string`'); } if (separator === '') { return [string]; } const separatorIndex = string.indexOf(separator); if (separatorIndex === -1) { return [string]; } return [ string.slice(0, separatorIndex), string.slice(separatorIndex + separator.length) ]; }; function encoderForArrayFormat(options) { switch (options.arrayFormat) { case 'index': return key => (result, value) => { const index = result.length; if (value === undefined || (options.skipNull && value === null)) { return result; } if (value === null) { return [...result, [encode(key, options), '[', index, ']'].join('')]; } return [ ...result, [encode(key, options), '[', encode(index, options), ']=', encode(value, options)].join('') ]; }; case 'bracket': return key => (result, value) => { if (value === undefined || (options.skipNull && value === null)) { return result; } if (value === null) { return [...result, [encode(key, options), '[]'].join('')]; } return [...result, [encode(key, options), '[]=', encode(value, options)].join('')]; }; case 'comma': return key => (result, value) => { if (value === null || value === undefined || value.length === 0) { return result; } if (result.length === 0) { return [[encode(key, options), '=', encode(value, options)].join('')]; } return [[result, encode(value, options)].join(',')]; }; default: return key => (result, value) => { if (value === undefined || (options.skipNull && value === null)) { return result; } if (value === null) { return [...result, encode(key, options)]; } return [...result, [encode(key, options), '=', encode(value, options)].join('')]; }; } } function parserForArrayFormat(options) { let result; switch (options.arrayFormat) { case 'index': return (key, value, accumulator) => { result = /\[(\d*)\]$/.exec(key); key = key.replace(/\[\d*\]$/, ''); if (!result) { accumulator[key] = value; return; } if (accumulator[key] === undefined) { accumulator[key] = {}; } accumulator[key][result[1]] = value; }; case 'bracket': return (key, value, accumulator) => { result = /(\[\])$/.exec(key); key = key.replace(/\[\]$/, ''); if (!result) { accumulator[key] = value; return; } if (accumulator[key] === undefined) { accumulator[key] = [value]; return; } accumulator[key] = [].concat(accumulator[key], value); }; case 'comma': return (key, value, accumulator) => { const isArray = typeof value === 'string' && value.split('').indexOf(',') > -1; const newValue = isArray ? value.split(',') : value; accumulator[key] = newValue; }; default: return (key, value, accumulator) => { if (accumulator[key] === undefined) { accumulator[key] = value; return; } accumulator[key] = [].concat(accumulator[key], value); }; } } function encode(value, options) { if (options.encode) { return options.strict ? strictUriEncode(value) : encodeURIComponent(value); } return value; } function decode$1(value, options) { if (options.decode) { return decodeUriComponent(value); } return value; } function keysSorter(input) { if (Array.isArray(input)) { return input.sort(); } if (typeof input === 'object') { return keysSorter(Object.keys(input)) .sort((a, b) => Number(a) - Number(b)) .map(key => input[key]); } return input; } function removeHash(input) { const hashStart = input.indexOf('#'); if (hashStart !== -1) { input = input.slice(0, hashStart); } return input; } function extract(input) { input = removeHash(input); const queryStart = input.indexOf('?'); if (queryStart === -1) { return ''; } return input.slice(queryStart + 1); } function parseValue(value, options) { if (options.parseNumbers && !Number.isNaN(Number(value)) && (typeof value === 'string' && value.trim() !== '')) { value = Number(value); } else if (options.parseBooleans && value !== null && (value.toLowerCase() === 'true' || value.toLowerCase() === 'false')) { value = value.toLowerCase() === 'true'; } return value; } function parse(input, options) { options = Object.assign({ decode: true, sort: true, arrayFormat: 'none', parseNumbers: false, parseBooleans: false }, options); const formatter = parserForArrayFormat(options); // Create an object with no prototype const ret = Object.create(null); if (typeof input !== 'string') { return ret; } input = input.trim().replace(/^[?#&]/, ''); if (!input) { return ret; } for (const param of input.split('&')) { let [key, value] = splitOnFirst(options.decode ? param.replace(/\+/g, ' ') : param, '='); // Missing `=` should be `null`: // http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters value = value === undefined ? null : decode$1(value, options); formatter(decode$1(key, options), value, ret); } for (const key of Object.keys(ret)) { const value = ret[key]; if (typeof value === 'object' && value !== null) { for (const k of Object.keys(value)) { value[k] = parseValue(value[k], options); } } else { ret[key] = parseValue(value, options); } } if (options.sort === false) { return ret; } return (options.sort === true ? Object.keys(ret).sort() : Object.keys(ret).sort(options.sort)).reduce((result, key) => { const value = ret[key]; if (Boolean(value) && typeof value === 'object' && !Array.isArray(value)) { // Sort object keys, not values result[key] = keysSorter(value); } else { result[key] = value; } return result; }, Object.create(null)); } var extract_1 = extract; var parse_1 = parse; var stringify = (object, options) => { if (!object) { return ''; } options = Object.assign({ encode: true, strict: true, arrayFormat: 'none' }, options); const formatter = encoderForArrayFormat(options); const objectCopy = Object.assign({}, object); if (options.skipNull) { for (const key of Object.keys(objectCopy)) { if (objectCopy[key] === undefined || objectCopy[key] === null) { delete objectCopy[key]; } } } const keys = Object.keys(objectCopy); if (options.sort !== false) { keys.sort(options.sort); } return keys.map(key => { const value = object[key]; if (value === undefined) { return ''; } if (value === null) { return encode(key, options); } if (Array.isArray(value)) { return value .reduce(formatter(key), []) .join('&'); } return encode(key, options) + '=' + encode(value, options); }).filter(x => x.length > 0).join('&'); }; var parseUrl = (input, options) => { return { url: removeHash(input).split('?')[0] || '', query: parse(extract(input), options) }; }; var queryString = { extract: extract_1, parse: parse_1, stringify: stringify, parseUrl: parseUrl }; var Encryption = /*#__PURE__*/ function () { function Encryption() { _classCallCheck(this, Encryption); } _createClass(Encryption, [{ key: "createCodeVerifier", value: function createCodeVerifier(str) { return str.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, ''); } }, { key: "createCodeChallenge", value: function createCodeChallenge(buffer) { return this.createCodeVerifier(SHA256(buffer).toString(CryptoJS.enc.Base64)); } }]); return Encryption; }(); var Util = /*#__PURE__*/ function () { function Util() { _classCallCheck(this, Util); this.encryption = new Encryption(); } /** * Http helper method * * @param {*} method * @param {*} path * @param {*} data * @param {*} headers */ _createClass(Util, null, [{ key: "fetch", value: function fetch(method, path, data, headers) { return httpRequest(method, path, data, headers); } }]); return Util; }(); /** * The code was extracted from: * https://github.com/davidchambers/Base64.js */ var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; function InvalidCharacterError(message) { this.message = message; } InvalidCharacterError.prototype = new Error(); InvalidCharacterError.prototype.name = 'InvalidCharacterError'; function polyfill (input) { var str = String(input).replace(/=+$/, ''); if (str.length % 4 == 1) { throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded."); } for ( // initialize result and counters var bc = 0, bs, buffer, idx = 0, output = ''; // get next character buffer = str.charAt(idx++); // character found in table? initialize bit storage and add its ascii value; ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer, // and if not first of each 4 characters, // convert the first 8 bits to one ascii character bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0 ) { // try to find character in table (0-63, not found => -1) buffer = chars.indexOf(buffer); } return output; } var atob = typeof window !== 'undefined' && window.atob && window.atob.bind(window) || polyfill; function b64DecodeUnicode(str) { return decodeURIComponent(atob(str).replace(/(.)/g, function (m, p) { var code = p.charCodeAt(0).toString(16).toUpperCase(); if (code.length < 2) { code = '0' + code; } return '%' + code; })); } var base64_url_decode = function(str) { var output = str.replace(/-/g, "+").replace(/_/g, "/"); switch (output.length % 4) { case 0: break; case 2: output += "=="; break; case 3: output += "="; break; default: throw "Illegal base64url string!"; } try{ return b64DecodeUnicode(output); } catch (err) { return atob(output); } }; function InvalidTokenError(message) { this.message = message; } InvalidTokenError.prototype = new Error(); InvalidTokenError.prototype.name = 'InvalidTokenError'; var lib = function (token,options) { if (typeof token !== 'string') { throw new InvalidTokenError('Invalid token specified'); } options = options || {}; var pos = options.header === true ? 0 : 1; try { return JSON.parse(base64_url_decode(token.split('.')[pos])); } catch (e) { throw new InvalidTokenError('Invalid token specified: ' + e.message); } }; var InvalidTokenError_1 = InvalidTokenError; lib.InvalidTokenError = InvalidTokenError_1; var parseToken = function parseToken(token) { if (typeof token === 'string') { return JSON.parse(token); } else if (_typeof(token) === 'object') { return token; } else { throw new ArgumentError('parse error. invalid token'); } }; var TokenManager = /*#__PURE__*/ function () { function TokenManager(options) { _classCallCheck(this, TokenManager); this.store = options.store; this.token = parseToken(this.store.getItem('token')) || { access_token: '', id_token: '', refresh_token: '', token_type: '', expires_in: '' }; } _createClass(TokenManager, [{ key: "getAccessToken", value: function getAccessToken() { if (Validation.isEmpty(this.token) && Validation.isEmpty(this.token['access_token'])) { return; } return this.token['access_token']; } }, { key: "getIDToken", value: function getIDToken() { if (Validation.isEmpty(this.token) && Validation.isEmpty(this.token['id_token'])) { return; } return this.token['id_token']; } }, { key: "getRefreshToken", value: function getRefreshToken() { if (Validation.isEmpty(this.token) && Validation.isEmpty(this.token['refresh_token'])) { return; } return this.token['refresh_token']; } }, { key: "removeToken", value: function removeToken() { return this.store.removeItem('token'); } }, { key: "getTokenType", value: function getTokenType() { if (Validation.isEmpty(this.token) && Validation.isEmpty(this.token['token_type'])) { return; } return this.token['token_type']; } }, { key: "getTokenExpiration", value: function getTokenExpiration() { if (Validation.isEmpty(this.token) && Validation.isEmpty(this.token['expires_in'])) { return; } return this.token['expires_in']; } }, { key: "decodeToken", value: function decodeToken(token) { //Decode token var decoded = lib(token); return Promise.resolve(decoded); } }]); return TokenManager; }(); var nopLogger = { debug: function debug() {}, info: function info() {}, warn: function warn() {}, error: function error() {} }; var NONE = 0; var ERROR = 1; var WARN = 2; var INFO = 3; var DEBUG = 4; var logger; var level; var Log = /*#__PURE__*/ function () { function Log() { _classCallCheck(this, Log); } _createClass(Log, null, [{ key: "reset", value: function reset() { level = INFO; logger = nopLogger; } }, { key: "error", value: function error() { if (level >= ERROR) { for (var _len = arguments.length, _error = new Array(_len), _key = 0; _key < _len; _key++) { _error[_key] = arguments[_key]; } logger.error.apply(logger, Array.from(_error)); } } }, { key: "info", value: function info() { if (level >= INFO) { for (var _len2 = arguments.length, error = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { error[_key2] = arguments[_key2]; } logger.info.apply(logger, Array.from(error)); } } }, { key: "warn", value: function warn() { if (level >= WARN) { for (var _len3 = arguments.length, error = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { error[_key3] = arguments[_key3]; } logger.warn.apply(logger, Array.from(error)); } } }, { key: "debug", value: function debug() { if (level >= DEBUG) { for (var _len4 = arguments.length, error = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { error[_key4] = arguments[_key4]; } logger.debug.apply(logger, Array.from(error)); } } }, { key: "NONE", get: function get() { return NONE; } }, { key: "ERROR", get: function get() { return ERROR; } }, { key: "WARN", get: function get() { return WARN; } }, { key: "INFO", get: function get() { return INFO; } }, { key: "DEBUG", get: function get() { return DEBUG; } }, { key: "level", get: function get() { return level; }, set: function set(value) { if (INFO <= value && value <= DEBUG) { level = value; } else { throw new Error('Invalid log level'); } } }, { key: "logger", get: function get() { return logger; }, set: function set(value) { if (value.debug && value.info && value.warn && value.error) { logger = value; } else { throw new Error('Invalid logger'); } } }]); return Log; }(); Log.reset(); var _ = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : {}; var $ = _.document; var SessionIFrame = /*#__PURE__*/ function () { function SessionIFrame(callback, metadata) { var interval = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1000 * 120; _classCallCheck(this, SessionIFrame); this._callback = callback; this._interval = interval; this._metadata = metadata; this._iframe_origin = metadata.authorization_server; this._iframe = $.createElement('iframe'); this._iframe.style.visibility = 'hidden'; this._iframe.style.display = 'none'; this._iframe.style.height = '0'; this._iframe.style.width = '0'; this._iframe.src = this._metadata.check_session_iframe; } _createClass(SessionIFrame, [{ key: "load", value: function load() { var _this = this; return new Promise(function (resolve) { _this._iframe.onload = function () { resolve(); }; $.body.appendChild(_this._iframe); _this._recieveMessage = _this._message.bind(_this); _.addEventListener("message", _this._recieveMessage, false); }); } }, { key: "start", value: function start(session_state) { var _this2 = this; if (this._session_state !== session_state) { Log.debug("SessionIFrame.start"); this.stop(); this._session_state = session_state; var check = function check() { Log.debug("SessionIFrame.check : Checking session state..."); var text = _this2._metadata.client_id + " " + _this2._session_state; _this2._iframe.contentWindow.postMessage(text, _this2._iframe_origin); }; check(); // set up timer call this._timer = _.setInterval(check, this._interval); } } }, { key: "_message", value: function _message(e) { Log.debug("SessionIFrame._message: called message function...."); if (e.origin === this._iframe_origin && e.source === this._iframe.contentWindow) { if (e.data === 'error') { Log.error("SessionIFrame: Error " + e.data); this.stop(); } else if (e.data === 'changed') { // call the callback function Log.debug("SessionIFrame : session changed from op..."); this.stop(); this._callback(e.data); } else { Log.debug("SessionIFrame: " + e.data); } } } }, { key: "stop", value: function stop() { this._session_state = null; if (this._timer) { Log.debug("SessionIFrame: stopping check state..."); _.clearInterval(this._timer); this._timer = null; } } }]); return SessionIFrame; }(); var SessionMonitor = /*#__PURE__*/ function () { function SessionMonitor(authenticationOidc) { var _this = this; var SessionIFrameCtor = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : SessionIFrame; _classCallCheck(this, SessionMonitor); if (!authenticationOidc) { Log.error("SessionMonitor: No authenticationoidc passed to SessionMonitor"); throw new Error("AuthenticationOidc Required"); } this._authenticationOidc = authenticationOidc; this._metaData = this._authenticationOidc.options; this._SessionIFrameCtor = SessionIFrameCtor; this._authenticationOidc.querySessionState().then(function (session_state) { if (!Validation.isEmpty(session_state)) { _this._start(session_state); } })["catch"](function (error) { Log.error("SessionMonitor: " + error); }); } _createClass(SessionMonitor, [{ key: "_start", value: function _start(session_state) { var _this2 = this; if (session_state) { if (!this._sessionIFrame) { if (this._metaData.check_session_iframe && !Validation.isEmpty(this._metaData.check_session_iframe)) { Log.debug("SessionMonitor.start: Initializing sessionIframe..."); this._sessionIFrame = new this._SessionIFrameCtor(this.callback.bind(this), this._metaData); this._sessionIFrame.load().then(function () { _this2._sessionIFrame.start(session_state); }); } else { Log.warn('SessionMonitor: No check_session_iframe define in the options'); } } else { Log.debug("SessionMonitor.start SessionIFrame is intantiated."); this._sessionIFrame.start(session_state); } } } }, { key: "callback", value: function callback(data) { Log.debug("SessionMonitor.callback: Callback function called"); this._authenticationOidc.event._signOutEvent(data); } }]); return SessionMonitor; }(); var _$1 = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : {}; var $$1 = _$1.document; var RenewTokenIFrame = /*#__PURE__*/ function () { function RenewTokenIFrame(callback, metadata, authorizationUrl) { _classCallCheck(this, RenewTokenIFrame); this._callback = callback; this._metadata = metadata; this._authorizationUrl = authorizationUrl; this._iframe_origin = metadata.options.authorization_server; this._iframe = $$1.createElement('iframe'); this._iframe.style.visibility = 'hidden'; this._iframe.id = 'oidcSilentIFrame'; this._iframe.style.display = 'none'; this._iframe.style.height = '0'; this._iframe.style.width = '0'; this._iframe.src = authorizationUrl; // metadata.options.silent_redirect_uri } _createClass(RenewTokenIFrame, [{ key: "load", value: function load() { var _this = this; return new Promise(function (resolve) { _this._iframe.onload = function () { resolve(); }; $$1.body.appendChild(_this._iframe); // this._recieveMessage = this._message.bind(this) // _.addEventListener("message", this._recieveMessage, false) }); } }, { key: "start", value: function start() { Log.debug("RenewTokenIFrame.check : Checking renew token state..."); if (this._metadata.options.automatic_renew) { this._startRenew = this._metadata._event.accessTokenExpiringEvent.subscribe(function (expiring) { }); } } }, { key: "close", value: function close() { this._cleanup(); } }, { key: "_cleanup", value: function _cleanup() { if (this._iframe) { Log.debug("RenewTokenIFrame: cleanup"); this._iframe = null; this._message = null; } } }, { key: "_message", value: function _message(e) { Log.debug("SessionIFrame._message: called message function...."); if (e.data === 'error') { Log.error("RenewTokenIFrame: Error " + e.data); } else if (e.data === 'changed') { // call the callback function Log.debug("RenewTokenIFrame : Getting new token..."); this._callback(e.data); } else { Log.debug("SessionIFrame: " + e.data); } } }]); return RenewTokenIFrame; }(); var RenewTokenMonitor = /*#__PURE__*/ function () { function RenewTokenMonitor(authenticationOidc, authorizationUrl) { var _this = this; var RenewTokenIFrameCtor = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : RenewTokenIFrame; _classCallCheck(this, RenewTokenMonitor); if (!authenticationOidc) { Log.error("RenewTokenIFrameMonitor: No authenticationoidc passed to RenewTokenIFrameMonitor"); throw new Error("AuthenticationOidc Required"); } this._authenticationOidc = authenticationOidc; this._metaData = this._authenticationOidc; this._RenewTokenIFrameCtor = RenewTokenIFrameCtor; this._authorizationUrl = authorizationUrl; this._authenticationOidc.querySessionState().then(function (session_state) { if (!Validation.isEmpty(session_state)) { _this._start(session_state); } })["catch"](function (error) { Log.error("RenewTokenIFrameMonitor: " + error); }); } _createClass(RenewTokenMonitor, [{ key: "_start", value: function _start(session_state) { var _this2 = this; if (session_state) { this._parentIFrame = window.parent.document.getElementById("oidcSilentIFrame"); if (!this._renewTokenIFrame) { if (this._metaData.options.silent_renew && !Validation.isEmpty(this._metaData.options.silent_renew)) { Log.debug("RenewTokenIFrameMonitor.start: Initializing RenewTokenIFrame..."); this._renewTokenIFrame = new this._RenewTokenIFrameCtor(this.callback.bind(this), this._metaData, this._authorizationUrl); this._renewTokenIFrame.load().then(function () { _this2._renewTokenIFrame.start(); })["catch"](function (error) { Log.error('RenewTokenIFrameMonitor Error', error); throw new Error('RenewTokenIFrameMonitor Error'); }); this._renewTokenIFrame.close(); } else { Log.warn('RenewTokenIFrameMonitor: No silent_renew define in the options'); } } } } }, { key: "callback", value: function callback(data) { Log.debug("RenewTokenMonitor.callback: Callback function called"); } }]); return RenewTokenMonitor; }(); /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } /** PURE_IMPORTS_START PURE_IMPORTS_END */ function isFunction(x) { return typeof x === 'function'; } //# sourceMappingURL=isFunction.js.map /** PURE_IMPORTS_START PURE_IMPORTS_END */ var _enable_super_gross_mode_that_will_cause_bad_things = false; var config = { Promise: undefined, set useDeprecatedSynchronousErrorHandling(value) { if (value) { var error = /*@__PURE__*/ new Error(); /*@__PURE__*/ console.warn('DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \n' + error.stack); } _enable_super_gross_mode_that_will_cause_bad_things = value; }, get useDeprecatedSynchronousErrorHandling() { return _enable_super_gross_mode_that_will_cause_bad_things; }, }; //# sourceMappingURL=config.js.map /** PURE_IMPORTS_START PURE_IMPORTS_END */ function hostReportError(err) { setTimeout(function () { throw err; }, 0); } //# sourceMappingURL=hostReportError.js.map /** PURE_IMPORTS_START _config,_util_hostReportError PURE_IMPORTS_END */ var empty = { closed: true, next: function (value) { }, error: function (err) { if (config.useDeprecatedSynchronousErrorHandling) { throw err; } else { hostReportError(err); } }, complete: function () { } }; //# sourceMappingURL=Observer.js.map /** PURE_IMPORTS_START PURE_IMPORTS_END */ var isArray = /*@__PURE__*/ (function () { return Array.isArray || (function (x) { return x && typeof x.length === 'number'; }); })(); //# sourceMappingURL=isArray.js.map /** PURE_IMPORTS_START PURE_IMPORTS_END */ function isObject(x) { return x !== null && typeof x === 'object'; } //# sourceMappingURL=isObject.js.map /** PURE_IMPORTS_START PURE_IMPORTS_END */ var UnsubscriptionErrorImpl = /*@__PURE__*/ (function () { function UnsubscriptionErrorImpl(errors) { Error.call(this); this.message = errors ? errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n ') : ''; this.name = 'UnsubscriptionError'; this.errors = errors; return this; } UnsubscriptionErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype); return UnsubscriptionErrorImpl; })(); var UnsubscriptionError = UnsubscriptionErrorImpl; //# sourceMappingURL=UnsubscriptionError.js.map /** PURE_IMPORTS_START _util_isArray,_util_isObject,_util_isFunction,_util_UnsubscriptionError PURE_IMPORTS_END */ var Subscription = /*@__PURE__*/ (function () { function Subscription(unsubscribe) { this.closed = false; this._parentOrParents = null; this._subscriptions = null; if (unsubscribe) { this._unsubscribe = unsubscribe; } } Subscription.prototype.unsubscribe = function () { var errors; if (this.closed) { return; } var _a = this, _parentOrParents = _a._parentOrParents, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions; this.closed = true; this._parentOrParents = null; this._subscriptions = null; if (_parentOrParents instanceof Subscription) { _parentOrParents.remove(this); } else if (_parentOrParents !== null) { for (var index = 0; index < _parentOrParents.length; ++index) { var parent_1 = _parentOrParents[index]; parent_1.remove(this); } } if (isFunction(_unsubscribe)) { try { _unsubscribe.call(this); } catch (e) { errors = e instanceof UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e]; } } if (isArray(_subscriptions)) { var index = -1; var len = _subscriptions.length; while (++index < len) { var sub = _subscriptions[index]; if (isObject(sub)) { try { sub.unsubscribe(); } catch (e) { errors = errors || []; if (e instanceof UnsubscriptionError) { errors = errors.concat(flattenUnsubscriptionErrors(e.errors)); } else { errors.push(e); } } } } } if (errors) { throw new UnsubscriptionError(errors); } }; Subscription.prototype.add = function (teardown) { var subscription = teardown; if (!teardown) { return Subscription.EMPTY; } switch (typeof teardown) { case 'function': subscription = new Subscription(teardown); case 'object': if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') { return subscription; } else if (this.closed) { subscription.unsubscribe(); return subscription; } else if (!(subscription instanceof Subscription)) { var tmp = subscription; subscription = new Subscription(); subscription._subscriptions = [tmp]; } break; default: { throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.'); } } var _parentOrParents = subscription._parentOrParents; if (_parentOrParents === null) { subscription._parentOrParents = this; } else if (_parentOrParents instanceof Subscription) { if (_parentOrParents === this) { return subscription; } subscription._parentOrParents = [_parentOrParents, this]; } else if (_parentOrParents.indexOf(this) === -1) { _parentOrParents.push(this); } else { return subscription; } var subscriptions = this._subscriptions; if (subscriptions === null) { this._subscriptions = [subscription]; } else { subscriptions.push(subscription); } return subscription; }; Subscription.prototype.remove = function (subscription) { var subscriptions = this._subscriptions; if (subscriptions) { var subscriptionIndex = subscriptions.indexOf(subscription); if (subscriptionIndex !== -1) { subscriptions.splice(subscriptionIndex, 1); } } }; Subscription.EMPTY = (function (empty) { empty.closed = true; return empty; }(new Subscription())); return Subscription; }()); function flattenUnsubscriptionErrors(errors) { return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError) ? err.errors : err); }, []); } //# sourceMappingURL=Subscription.js.map /** PURE_IMPORTS_START PURE_IMPORTS_END */ var rxSubscriber = /*@__PURE__*/ (function () { return typeof Symbol === 'function' ? /*@__PURE__*/ Symbol('rxSubscriber') : '@@rxSubscriber_' + /*@__PURE__*/ Math.random(); })(); //# sourceMappingURL=rxSubscriber.js.map /** PURE_IMPORTS_START tslib,_util_isFunction,_Observer,_Subscription,_internal_symbol_rxSubscriber,_config,_util_hostReportError PURE_IMPORTS_END */ var Subscriber = /*@__PURE__*/ (function (_super) { __extends(Subscriber, _super); function Subscriber(destinationOrNext, error, complete) { var _this = _super.call(this) || this; _this.syncErrorValue = null; _this.syncErrorThrown = false; _this.syncErrorThrowable = false; _this.isStopped = false; switch (arguments.length) { case 0: _this.destination = empty; break; case 1: if (!destinationOrNext) { _this.destination = empty; break; } if (typeof destinationOrNext === 'object') { if (destinationOrNext instanceof Subscriber) { _this.syncErrorThrowable = destinationOrNext.syncErrorThrowable; _this.destination = destinationOrNext; destinationOrNext.add(_this); } else { _this.syncErrorThrowable = true; _this.destination = new SafeSubscriber(_this, destinationOrNext); } break; } default: _this.syncErrorThrowable = true; _this.destination = new SafeSubscriber(_this, destinationOrNext, error, complete); break; } return _this; } Subscriber.prototype[rxSubscriber] = function () { return this; }; Subscriber.create = function (next, error, complete) { var subscriber = new Subscriber(next, error, complete); subscriber.syncErrorThrowable = false; return subscriber; }; Subscriber.prototype.next = function (value) { if (!this.isStopped) { this._next(value); } }; Subscriber.prototype.error = function (err) { if (!this.isStopped) { this.isStopped = true; this._error(err); } }; Subscriber.prototype.complete = function () { if (!this.isStopped) { this.isStopped = true; this._complete(); } }; Subscriber