oidc-client-rx
Version:
ReactiveX enhanced OIDC and OAuth2 protocol support for browser-based JavaScript applications
1,009 lines • 272 kB
JavaScript
/*! For license information please see solid-js.cjs.LICENSE.txt */
"use strict";
var __webpack_require__ = {};
(()=>{
__webpack_require__.d = (exports1, definition)=>{
for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
enumerable: true,
get: definition[key]
});
};
})();
(()=>{
__webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
})();
(()=>{
__webpack_require__.r = (exports1)=>{
if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
value: 'Module'
});
Object.defineProperty(exports1, '__esModule', {
value: true
});
};
})();
var __webpack_exports__ = {};
__webpack_require__.r(__webpack_exports__);
__webpack_require__.d(__webpack_exports__, {
InjectorProvider: ()=>InjectorProvider,
useOidcClient: ()=>useOidcClient,
InjectorContext: ()=>InjectorContext,
InjectorContextVoidInjector: ()=>InjectorContextVoidInjector,
useInjector: ()=>useInjector
});
const external_solid_js_namespaceObject = require("solid-js");
const injection_js_namespaceObject = require("@outposts/injection-js");
const external_rxjs_namespaceObject = require("rxjs");
const operators_namespaceObject = require("rxjs/operators");
function injectAbstractType(abstractType) {
return (0, injection_js_namespaceObject.inject)(abstractType);
}
function _ts_decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc);
else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
class AbstractLoggerService {
}
AbstractLoggerService = _ts_decorate([
(0, injection_js_namespaceObject.Injectable)()
], AbstractLoggerService);
var log_level_LogLevel = /*#__PURE__*/ function(LogLevel) {
LogLevel[LogLevel["None"] = 0] = "None";
LogLevel[LogLevel["Debug"] = 1] = "Debug";
LogLevel[LogLevel["Warn"] = 2] = "Warn";
LogLevel[LogLevel["Error"] = 3] = "Error";
return LogLevel;
}({});
function logger_service_ts_decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc);
else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
class LoggerService {
logError(configuration, message, ...args) {
if (this.loggingIsTurnedOff(configuration)) return;
const { configId } = configuration;
const messageToLog = this.isObject(message) ? JSON.stringify(message) : message;
if (args && args.length) this.abstractLoggerService.logError(`[ERROR] ${configId} - ${messageToLog}`, ...args);
else this.abstractLoggerService.logError(`[ERROR] ${configId} - ${messageToLog}`);
}
logWarning(configuration, message, ...args) {
if (!this.logLevelIsSet(configuration)) return;
if (this.loggingIsTurnedOff(configuration)) return;
if (!this.currentLogLevelIsEqualOrSmallerThan(configuration, log_level_LogLevel.Warn)) return;
const { configId } = configuration;
const messageToLog = this.isObject(message) ? JSON.stringify(message) : message;
if (args && args.length) this.abstractLoggerService.logWarning(`[WARN] ${configId} - ${messageToLog}`, ...args);
else this.abstractLoggerService.logWarning(`[WARN] ${configId} - ${messageToLog}`);
}
logDebug(configuration, message, ...args) {
if (!configuration) return;
if (!this.logLevelIsSet(configuration)) return;
if (this.loggingIsTurnedOff(configuration)) return;
if (!this.currentLogLevelIsEqualOrSmallerThan(configuration, log_level_LogLevel.Debug)) return;
const { configId } = configuration;
const messageToLog = this.isObject(message) ? JSON.stringify(message) : message;
if (args && args.length) this.abstractLoggerService.logDebug(`[DEBUG] ${configId} - ${messageToLog}`, ...args);
else this.abstractLoggerService.logDebug(`[DEBUG] ${configId} - ${messageToLog}`);
}
currentLogLevelIsEqualOrSmallerThan(configuration, logLevelToCompare) {
const { logLevel } = configuration || {};
if (!logLevel) return false;
return logLevel <= logLevelToCompare;
}
logLevelIsSet(configuration) {
const { logLevel } = configuration || {};
if (null === logLevel) return false;
return void 0 !== logLevel;
}
loggingIsTurnedOff(configuration) {
const { logLevel } = configuration || {};
return logLevel === log_level_LogLevel.None;
}
isObject(possibleObject) {
return '[object Object]' === Object.prototype.toString.call(possibleObject);
}
constructor(){
this.abstractLoggerService = injectAbstractType(AbstractLoggerService);
}
}
LoggerService = logger_service_ts_decorate([
(0, injection_js_namespaceObject.Injectable)()
], LoggerService);
var event_types_EventTypes = /*#__PURE__*/ function(EventTypes) {
EventTypes[EventTypes["ConfigLoaded"] = 0] = "ConfigLoaded";
EventTypes[EventTypes["CheckingAuth"] = 1] = "CheckingAuth";
EventTypes[EventTypes["CheckingAuthFinished"] = 2] = "CheckingAuthFinished";
EventTypes[EventTypes["CheckingAuthFinishedWithError"] = 3] = "CheckingAuthFinishedWithError";
EventTypes[EventTypes["ConfigLoadingFailed"] = 4] = "ConfigLoadingFailed";
EventTypes[EventTypes["CheckSessionReceived"] = 5] = "CheckSessionReceived";
EventTypes[EventTypes["UserDataChanged"] = 6] = "UserDataChanged";
EventTypes[EventTypes["NewAuthenticationResult"] = 7] = "NewAuthenticationResult";
EventTypes[EventTypes["TokenExpired"] = 8] = "TokenExpired";
EventTypes[EventTypes["IdTokenExpired"] = 9] = "IdTokenExpired";
EventTypes[EventTypes["SilentRenewStarted"] = 10] = "SilentRenewStarted";
EventTypes[EventTypes["SilentRenewFailed"] = 11] = "SilentRenewFailed";
return EventTypes;
}({});
function public_events_service_ts_decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc);
else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
class PublicEventsService {
fireEvent(type, value) {
this.notify.next({
type,
value
});
}
registerForEvents() {
return this.notify.asObservable();
}
constructor(){
this.notify = new external_rxjs_namespaceObject.ReplaySubject(1);
}
}
PublicEventsService = public_events_service_ts_decorate([
(0, injection_js_namespaceObject.Injectable)()
], PublicEventsService);
function abstract_security_storage_ts_decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc);
else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
class AbstractSecurityStorage {
}
AbstractSecurityStorage = abstract_security_storage_ts_decorate([
(0, injection_js_namespaceObject.Injectable)()
], AbstractSecurityStorage);
function browser_storage_service_ts_decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc);
else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
class BrowserStorageService {
read(key, configuration) {
const { configId } = configuration;
if (!configId) {
this.loggerService.logDebug(configuration, `Wanted to read '${key}' but configId was '${configId}'`);
return null;
}
if (!this.hasStorage()) {
this.loggerService.logDebug(configuration, `Wanted to read '${key}' but Storage was undefined`);
return null;
}
const storedConfig = this.abstractSecurityStorage.read(configId);
if (!storedConfig) return null;
return JSON.parse(storedConfig);
}
write(value, configuration) {
const { configId } = configuration;
if (!configId) {
this.loggerService.logDebug(configuration, `Wanted to write but configId was '${configId}'`);
return false;
}
if (!this.hasStorage()) {
this.loggerService.logDebug(configuration, 'Wanted to write but Storage was falsy');
return false;
}
value = value || null;
this.abstractSecurityStorage.write(configId, JSON.stringify(value));
return true;
}
remove(key, configuration) {
if (!this.hasStorage()) {
this.loggerService.logDebug(configuration, `Wanted to remove '${key}' but Storage was falsy`);
return false;
}
this.abstractSecurityStorage.remove(key);
return true;
}
clear(configuration) {
if (!this.hasStorage()) {
this.loggerService.logDebug(configuration, 'Wanted to clear storage but Storage was falsy');
return false;
}
this.abstractSecurityStorage.clear();
return true;
}
hasStorage() {
return 'undefined' != typeof Storage;
}
constructor(){
this.loggerService = (0, injection_js_namespaceObject.inject)(LoggerService);
this.abstractSecurityStorage = injectAbstractType(AbstractSecurityStorage);
}
}
BrowserStorageService = browser_storage_service_ts_decorate([
(0, injection_js_namespaceObject.Injectable)()
], BrowserStorageService);
class StoragePersistenceService {
read(key, config) {
const storedConfig = this.browserStorageService.read(key, config) || {};
return storedConfig[key];
}
write(key, value, config) {
const storedConfig = this.browserStorageService.read(key, config) || {};
storedConfig[key] = value;
return this.browserStorageService.write(storedConfig, config);
}
remove(key, config) {
const storedConfig = this.browserStorageService.read(key, config) || {};
delete storedConfig[key];
this.browserStorageService.write(storedConfig, config);
}
clear(config) {
this.browserStorageService.clear(config);
}
resetStorageFlowData(config) {
this.remove('session_state', config);
this.remove('storageSilentRenewRunning', config);
this.remove('storageCodeFlowInProgress', config);
this.remove('codeVerifier', config);
this.remove('userData', config);
this.remove('storageCustomParamsAuthRequest', config);
this.remove('access_token_expires_at', config);
this.remove('storageCustomParamsRefresh', config);
this.remove('storageCustomParamsEndSession', config);
this.remove('reusable_refresh_token', config);
}
resetAuthStateInStorage(config) {
this.remove('authzData', config);
this.remove('reusable_refresh_token', config);
this.remove('authnResult', config);
}
getAccessToken(config) {
return this.read('authzData', config);
}
getIdToken(config) {
var _this_read;
return null == (_this_read = this.read('authnResult', config)) ? void 0 : _this_read.id_token;
}
getRefreshToken(config) {
var _this_read;
const refreshToken = null == (_this_read = this.read('authnResult', config)) ? void 0 : _this_read.refresh_token;
if (!refreshToken && config.allowUnsafeReuseRefreshToken) return this.read('reusable_refresh_token', config);
return refreshToken;
}
getAuthenticationResult(config) {
return this.read('authnResult', config);
}
constructor(){
this.browserStorageService = (0, injection_js_namespaceObject.inject)(BrowserStorageService);
}
}
const external_rfc4648_namespaceObject = require("rfc4648");
function jwk_extractor_ts_decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc);
else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
class JwkExtractor {
extractJwk(keys, spec, throwOnEmpty = true) {
if (0 === keys.length) throw JwkExtractorInvalidArgumentError;
const foundKeys = keys.filter((k)=>(null == spec ? void 0 : spec.kid) ? k.kid === spec.kid : true).filter((k)=>(null == spec ? void 0 : spec.use) ? k.use === spec.use : true).filter((k)=>(null == spec ? void 0 : spec.kty) ? k.kty === spec.kty : true);
if (0 === foundKeys.length && throwOnEmpty) throw JwkExtractorNoMatchingKeysError;
if (foundKeys.length > 1 && null == spec) throw JwkExtractorSeveralMatchingKeysError;
return foundKeys;
}
}
JwkExtractor = jwk_extractor_ts_decorate([
(0, injection_js_namespaceObject.Injectable)()
], JwkExtractor);
function buildErrorName(name) {
return `${JwkExtractor.name}: ${name}`;
}
const JwkExtractorInvalidArgumentError = {
name: buildErrorName('InvalidArgumentError'),
message: 'Array of keys was empty. Unable to extract'
};
const JwkExtractorNoMatchingKeysError = {
name: buildErrorName('NoMatchingKeysError'),
message: 'No key found matching the spec'
};
const JwkExtractorSeveralMatchingKeysError = {
name: buildErrorName('SeveralMatchingKeysError'),
message: 'More than one key found. Please use spec to filter'
};
const DOCUMENT = new injection_js_namespaceObject.InjectionToken('document');
function token_helper_service_ts_decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc);
else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
const PARTS_OF_TOKEN = 3;
class TokenHelperService {
getTokenExpirationDate(dataIdToken) {
if (!Object.prototype.hasOwnProperty.call(dataIdToken, 'exp')) return new Date(new Date().toUTCString());
const date = new Date(0);
date.setUTCSeconds(dataIdToken.exp);
return date;
}
getSigningInputFromToken(token, encoded, configuration) {
if (!this.tokenIsValid(token, configuration)) return '';
const header = this.getHeaderFromToken(token, encoded, configuration);
const payload = this.getPayloadFromToken(token, encoded, configuration);
return [
header,
payload
].join('.');
}
getHeaderFromToken(token, encoded, configuration) {
if (!this.tokenIsValid(token, configuration)) return {};
return this.getPartOfToken(token, 0, encoded);
}
getPayloadFromToken(token, encoded, configuration) {
if (!configuration) return {};
if (!this.tokenIsValid(token, configuration)) return {};
return this.getPartOfToken(token, 1, encoded);
}
getSignatureFromToken(token, encoded, configuration) {
if (!this.tokenIsValid(token, configuration)) return {};
return this.getPartOfToken(token, 2, encoded);
}
getPartOfToken(token, index, encoded) {
const partOfToken = this.extractPartOfToken(token, index);
if (encoded) return partOfToken;
const result = this.urlBase64Decode(partOfToken);
return JSON.parse(result);
}
urlBase64Decode(str) {
var _this_document_defaultView;
let output = str.replace(/-/g, '+').replace(/_/g, '/');
switch(output.length % 4){
case 0:
break;
case 2:
output += '==';
break;
case 3:
output += '=';
break;
default:
throw new Error('Illegal base64url string!');
}
const decoded = void 0 !== this.document.defaultView ? null == (_this_document_defaultView = this.document.defaultView) ? void 0 : _this_document_defaultView.atob(output) : Buffer.from(output, 'base64').toString('binary');
if (!decoded) return '';
try {
return decodeURIComponent(decoded.split('').map((c)=>`%${`00${c.charCodeAt(0).toString(16)}`.slice(-2)}`).join(''));
} catch {
return decoded;
}
}
tokenIsValid(token, configuration) {
if (!token) {
this.loggerService.logError(configuration, `token '${token}' is not valid --> token falsy`);
return false;
}
if (!token.includes('.')) {
this.loggerService.logError(configuration, `token '${token}' is not valid --> no dots included`);
return false;
}
const parts = token.split('.');
if (parts.length !== PARTS_OF_TOKEN) {
this.loggerService.logError(configuration, `token '${token}' is not valid --> token has to have exactly ${PARTS_OF_TOKEN - 1} dots`);
return false;
}
return true;
}
extractPartOfToken(token, index) {
return token.split('.')[index];
}
constructor(){
this.loggerService = (0, injection_js_namespaceObject.inject)(LoggerService);
this.document = (0, injection_js_namespaceObject.inject)(DOCUMENT);
}
}
TokenHelperService = token_helper_service_ts_decorate([
(0, injection_js_namespaceObject.Injectable)()
], TokenHelperService);
function crypto_service_ts_decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc);
else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
class CryptoService {
getCrypto() {
var _this_document_defaultView, _this_document_defaultView1;
return (null == (_this_document_defaultView = this.document.defaultView) ? void 0 : _this_document_defaultView.crypto) || (null == (_this_document_defaultView1 = this.document.defaultView) ? void 0 : _this_document_defaultView1.msCrypto);
}
constructor(){
this.document = (0, injection_js_namespaceObject.inject)(DOCUMENT);
}
}
CryptoService = crypto_service_ts_decorate([
(0, injection_js_namespaceObject.Injectable)()
], CryptoService);
function jwk_window_crypto_service_ts_decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc);
else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
class JwkWindowCryptoService {
importVerificationKey(key, algorithm) {
return this.cryptoService.getCrypto().subtle.importKey('jwk', key, algorithm, false, [
'verify'
]);
}
verifyKey(verifyAlgorithm, cryptoKey, signature, signingInput) {
return this.cryptoService.getCrypto().subtle.verify(verifyAlgorithm, cryptoKey, signature, new TextEncoder().encode(signingInput));
}
constructor(){
this.cryptoService = (0, injection_js_namespaceObject.inject)(CryptoService);
}
}
JwkWindowCryptoService = jwk_window_crypto_service_ts_decorate([
(0, injection_js_namespaceObject.Injectable)()
], JwkWindowCryptoService);
function MockUtil(options) {
return (targetClass, propertyKey, _descriptor)=>{
var _Reflect_defineMetadata, _Reflect;
null == (_Reflect = Reflect) || null == (_Reflect_defineMetadata = _Reflect.defineMetadata) || _Reflect_defineMetadata.call(_Reflect, 'mock:implementation', options.implementation, targetClass, propertyKey);
};
}
function jwt_window_crypto_service_ts_decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc);
else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function _ts_metadata(k, v) {
if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(k, v);
}
class JwtWindowCryptoService {
generateCodeChallenge(codeVerifier) {
return this.calcHash(codeVerifier).pipe((0, operators_namespaceObject.map)((challengeRaw)=>this.base64UrlEncode(challengeRaw)));
}
generateAtHash(accessToken, algorithm) {
return this.calcHash(accessToken, algorithm).pipe((0, operators_namespaceObject.map)((tokenHash)=>{
const substr = tokenHash.substr(0, tokenHash.length / 2);
const tokenHashBase64 = btoa(substr);
return tokenHashBase64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
}));
}
calcHash(valueToHash, algorithm = 'SHA-256') {
const msgBuffer = new TextEncoder().encode(valueToHash);
return (0, external_rxjs_namespaceObject.from)(this.cryptoService.getCrypto().subtle.digest(algorithm, msgBuffer)).pipe((0, operators_namespaceObject.map)((hashBuffer)=>{
const buffer = hashBuffer;
const hashArray = Array.from(new Uint8Array(buffer));
return this.toHashString(hashArray);
}));
}
toHashString(byteArray) {
let result = '';
for (const e of byteArray)result += String.fromCharCode(e);
return result;
}
base64UrlEncode(str) {
const base64 = btoa(str);
return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
}
constructor(){
this.cryptoService = (0, injection_js_namespaceObject.inject)(CryptoService);
}
}
jwt_window_crypto_service_ts_decorate([
MockUtil({
implementation: ()=>new external_rxjs_namespaceObject.BehaviorSubject(void 0)
}),
_ts_metadata("design:type", Function),
_ts_metadata("design:paramtypes", [
String
]),
_ts_metadata("design:returntype", "undefined" == typeof Observable ? Object : Observable)
], JwtWindowCryptoService.prototype, "generateCodeChallenge", null);
JwtWindowCryptoService = jwt_window_crypto_service_ts_decorate([
(0, injection_js_namespaceObject.Injectable)()
], JwtWindowCryptoService);
function getVerifyAlg(alg) {
switch(alg.charAt(0)){
case 'R':
return {
name: 'RSASSA-PKCS1-v1_5',
hash: 'SHA-256'
};
case 'E':
if (alg.includes('256')) return {
name: 'ECDSA',
hash: 'SHA-256'
};
if (alg.includes('384')) return {
name: 'ECDSA',
hash: 'SHA-384'
};
return null;
default:
return null;
}
}
function alg2kty(alg) {
switch(alg.charAt(0)){
case 'R':
return 'RSA';
case 'E':
return 'EC';
default:
throw new Error(`Cannot infer kty from alg: ${alg}`);
}
}
function getImportAlg(alg) {
switch(alg.charAt(0)){
case 'R':
if (alg.includes('256')) return {
name: 'RSASSA-PKCS1-v1_5',
hash: 'SHA-256'
};
if (alg.includes('384')) return {
name: 'RSASSA-PKCS1-v1_5',
hash: 'SHA-384'
};
if (alg.includes('512')) return {
name: 'RSASSA-PKCS1-v1_5',
hash: 'SHA-512'
};
return null;
case 'E':
if (alg.includes('256')) return {
name: 'ECDSA',
namedCurve: 'P-256'
};
if (alg.includes('384')) return {
name: 'ECDSA',
namedCurve: 'P-384'
};
return null;
default:
return null;
}
}
function token_validation_service_ts_decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc);
else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
class TokenValidationService {
hasIdTokenExpired(token, configuration, offsetSeconds) {
const decoded = this.tokenHelperService.getPayloadFromToken(token, false, configuration);
return !this.validateIdTokenExpNotExpired(decoded, configuration, offsetSeconds);
}
validateIdTokenExpNotExpired(decodedIdToken, configuration, offsetSeconds) {
const tokenExpirationDate = this.tokenHelperService.getTokenExpirationDate(decodedIdToken);
offsetSeconds = offsetSeconds || 0;
if (!tokenExpirationDate) return false;
const tokenExpirationValue = tokenExpirationDate.valueOf();
const nowWithOffset = this.calculateNowWithOffset(offsetSeconds);
const tokenNotExpired = tokenExpirationValue > nowWithOffset;
this.loggerService.logDebug(configuration, `Has idToken expired: ${!tokenNotExpired} --> expires in ${this.millisToMinutesAndSeconds(tokenExpirationValue - nowWithOffset)} , ${new Date(tokenExpirationValue).toLocaleTimeString()} > ${new Date(nowWithOffset).toLocaleTimeString()}`);
return tokenNotExpired;
}
validateAccessTokenNotExpired(accessTokenExpiresAt, configuration, offsetSeconds) {
if (!accessTokenExpiresAt) return true;
offsetSeconds = offsetSeconds || 0;
const accessTokenExpirationValue = accessTokenExpiresAt.valueOf();
const nowWithOffset = this.calculateNowWithOffset(offsetSeconds);
const tokenNotExpired = accessTokenExpirationValue > nowWithOffset;
this.loggerService.logDebug(configuration, `Has accessToken expired: ${!tokenNotExpired} --> expires in ${this.millisToMinutesAndSeconds(accessTokenExpirationValue - nowWithOffset)} , ${new Date(accessTokenExpirationValue).toLocaleTimeString()} > ${new Date(nowWithOffset).toLocaleTimeString()}`);
return tokenNotExpired;
}
validateRequiredIdToken(dataIdToken, configuration) {
let validated = true;
if (!Object.prototype.hasOwnProperty.call(dataIdToken, 'iss')) {
validated = false;
this.loggerService.logWarning(configuration, 'iss is missing, this is required in the id_token');
}
if (!Object.prototype.hasOwnProperty.call(dataIdToken, 'sub')) {
validated = false;
this.loggerService.logWarning(configuration, 'sub is missing, this is required in the id_token');
}
if (!Object.prototype.hasOwnProperty.call(dataIdToken, 'aud')) {
validated = false;
this.loggerService.logWarning(configuration, 'aud is missing, this is required in the id_token');
}
if (!Object.prototype.hasOwnProperty.call(dataIdToken, 'exp')) {
validated = false;
this.loggerService.logWarning(configuration, 'exp is missing, this is required in the id_token');
}
if (!Object.prototype.hasOwnProperty.call(dataIdToken, 'iat')) {
validated = false;
this.loggerService.logWarning(configuration, 'iat is missing, this is required in the id_token');
}
return validated;
}
validateIdTokenIatMaxOffset(dataIdToken, maxOffsetAllowedInSeconds, disableIatOffsetValidation, configuration) {
if (disableIatOffsetValidation) return true;
if (!Object.prototype.hasOwnProperty.call(dataIdToken, 'iat')) return false;
const dateTimeIatIdToken = new Date(0);
dateTimeIatIdToken.setUTCSeconds(dataIdToken.iat);
maxOffsetAllowedInSeconds = maxOffsetAllowedInSeconds || 0;
const nowInUtc = new Date(new Date().toUTCString());
const diff = nowInUtc.valueOf() - dateTimeIatIdToken.valueOf();
const maxOffsetAllowedInMilliseconds = 1000 * maxOffsetAllowedInSeconds;
this.loggerService.logDebug(configuration, `validate id token iat max offset ${diff} < ${maxOffsetAllowedInMilliseconds}`);
if (diff > 0) return diff < maxOffsetAllowedInMilliseconds;
return -diff < maxOffsetAllowedInMilliseconds;
}
validateIdTokenNonce(dataIdToken, localNonce, ignoreNonceAfterRefresh, configuration) {
const isFromRefreshToken = (void 0 === dataIdToken.nonce || ignoreNonceAfterRefresh) && localNonce === TokenValidationService.refreshTokenNoncePlaceholder;
if (!isFromRefreshToken && dataIdToken.nonce !== localNonce) {
this.loggerService.logDebug(configuration, `Validate_id_token_nonce failed, dataIdToken.nonce: ${dataIdToken.nonce} local_nonce:${localNonce}`);
return false;
}
return true;
}
validateIdTokenIss(dataIdToken, authWellKnownEndpointsIssuer, configuration) {
if (dataIdToken.iss !== authWellKnownEndpointsIssuer) {
this.loggerService.logDebug(configuration, `Validate_id_token_iss failed, dataIdToken.iss: ${dataIdToken.iss} authWellKnownEndpoints issuer:${authWellKnownEndpointsIssuer}`);
return false;
}
return true;
}
validateIdTokenAud(dataIdToken, aud, configuration) {
if (Array.isArray(dataIdToken.aud)) {
const result = dataIdToken.aud.includes(aud);
if (!result) {
this.loggerService.logDebug(configuration, `Validate_id_token_aud array failed, dataIdToken.aud: ${dataIdToken.aud} client_id:${aud}`);
return false;
}
return true;
}
if (dataIdToken.aud !== aud) {
this.loggerService.logDebug(configuration, `Validate_id_token_aud failed, dataIdToken.aud: ${dataIdToken.aud} client_id:${aud}`);
return false;
}
return true;
}
validateIdTokenAzpExistsIfMoreThanOneAud(dataIdToken) {
if (!dataIdToken) return false;
return !(Array.isArray(dataIdToken.aud) && dataIdToken.aud.length > 1 && !dataIdToken.azp);
}
validateIdTokenAzpValid(dataIdToken, clientId) {
if (!(null == dataIdToken ? void 0 : dataIdToken.azp)) return true;
return dataIdToken.azp === clientId;
}
validateStateFromHashCallback(state, localState, configuration) {
if (`${state}` !== `${localState}`) {
this.loggerService.logDebug(configuration, `ValidateStateFromHashCallback failed, state: ${state} local_state:${localState}`);
return false;
}
return true;
}
validateSignatureIdToken(idToken, jwtkeys, configuration) {
if (!idToken) return (0, external_rxjs_namespaceObject.of)(true);
if (!jwtkeys || !jwtkeys.keys) return (0, external_rxjs_namespaceObject.of)(false);
const headerData = this.tokenHelperService.getHeaderFromToken(idToken, false, configuration);
if (0 === Object.keys(headerData).length && headerData.constructor === Object) {
this.loggerService.logWarning(configuration, 'id token has no header data');
return (0, external_rxjs_namespaceObject.of)(false);
}
const kid = headerData.kid;
const alg = headerData.alg;
const keys = jwtkeys.keys;
let foundKeys;
let key;
if (!this.keyAlgorithms.includes(alg)) {
this.loggerService.logWarning(configuration, 'alg not supported', alg);
return (0, external_rxjs_namespaceObject.of)(false);
}
const kty = alg2kty(alg);
const use = 'sig';
try {
foundKeys = kid ? this.jwkExtractor.extractJwk(keys, {
kid,
kty,
use
}, false) : this.jwkExtractor.extractJwk(keys, {
kty,
use
}, false);
if (0 === foundKeys.length) foundKeys = kid ? this.jwkExtractor.extractJwk(keys, {
kid,
kty
}) : this.jwkExtractor.extractJwk(keys, {
kty
});
key = foundKeys[0];
} catch (e) {
this.loggerService.logError(configuration, e);
return (0, external_rxjs_namespaceObject.of)(false);
}
const algorithm = getImportAlg(alg);
const signingInput = this.tokenHelperService.getSigningInputFromToken(idToken, true, configuration);
const rawSignature = this.tokenHelperService.getSignatureFromToken(idToken, true, configuration);
return (0, external_rxjs_namespaceObject.from)(this.jwkWindowCryptoService.importVerificationKey(key, algorithm)).pipe((0, operators_namespaceObject.mergeMap)((cryptoKey)=>{
const signature = external_rfc4648_namespaceObject.base64url.parse(rawSignature, {
loose: true
});
const verifyAlgorithm = getVerifyAlg(alg);
return (0, external_rxjs_namespaceObject.from)(this.jwkWindowCryptoService.verifyKey(verifyAlgorithm, cryptoKey, signature, signingInput));
}), (0, operators_namespaceObject.tap)((isValid)=>{
if (!isValid) this.loggerService.logWarning(configuration, 'incorrect Signature, validation failed for id_token');
}));
}
validateIdTokenAtHash(accessToken, atHash, idTokenAlg, configuration) {
this.loggerService.logDebug(configuration, `at_hash from the server:${atHash}`);
let sha = 'SHA-256';
if (idTokenAlg.includes('384')) sha = 'SHA-384';
else if (idTokenAlg.includes('512')) sha = 'SHA-512';
return this.jwtWindowCryptoService.generateAtHash(`${accessToken}`, sha).pipe((0, operators_namespaceObject.mergeMap)((hash)=>{
this.loggerService.logDebug(configuration, `at_hash client validation not decoded:${hash}`);
if (hash === atHash) return (0, external_rxjs_namespaceObject.of)(true);
return this.jwtWindowCryptoService.generateAtHash(`${decodeURIComponent(accessToken)}`, sha).pipe((0, operators_namespaceObject.map)((newHash)=>{
this.loggerService.logDebug(configuration, `-gen access--${hash}`);
return newHash === atHash;
}));
}));
}
millisToMinutesAndSeconds(millis) {
const minutes = Math.floor(millis / 60000);
const seconds = (millis % 60000 / 1000).toFixed(0);
return `${minutes}:${+seconds < 10 ? '0' : ''}${seconds}`;
}
calculateNowWithOffset(offsetSeconds) {
return new Date(new Date().toUTCString()).valueOf() + 1000 * offsetSeconds;
}
constructor(){
this.keyAlgorithms = [
'HS256',
'HS384',
'HS512',
'RS256',
'RS384',
'RS512',
'ES256',
'ES384',
'PS256',
'PS384',
'PS512'
];
this.tokenHelperService = (0, injection_js_namespaceObject.inject)(TokenHelperService);
this.loggerService = (0, injection_js_namespaceObject.inject)(LoggerService);
this.jwkExtractor = (0, injection_js_namespaceObject.inject)(JwkExtractor);
this.jwkWindowCryptoService = (0, injection_js_namespaceObject.inject)(JwkWindowCryptoService);
this.jwtWindowCryptoService = (0, injection_js_namespaceObject.inject)(JwtWindowCryptoService);
}
}
TokenValidationService.refreshTokenNoncePlaceholder = '--RefreshToken--';
TokenValidationService = token_validation_service_ts_decorate([
(0, injection_js_namespaceObject.Injectable)()
], TokenValidationService);
function auth_state_service_ts_decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc);
else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
const DEFAULT_AUTHRESULT = {
isAuthenticated: false,
allConfigsAuthenticated: []
};
class AuthStateService {
get authenticated$() {
return this.authenticatedInternal$.asObservable().pipe((0, operators_namespaceObject.distinctUntilChanged)());
}
setAuthenticatedAndFireEvent(allConfigs) {
const result = this.composeAuthenticatedResult(allConfigs);
this.authenticatedInternal$.next(result);
}
setUnauthenticatedAndFireEvent(currentConfig, allConfigs) {
this.storagePersistenceService.resetAuthStateInStorage(currentConfig);
const result = this.composeUnAuthenticatedResult(allConfigs);
this.authenticatedInternal$.next(result);
}
updateAndPublishAuthState(authenticationResult) {
this.publicEventsService.fireEvent(event_types_EventTypes.NewAuthenticationResult, authenticationResult);
}
setAuthorizationData(accessToken, authResult, currentConfig, allConfigs) {
this.loggerService.logDebug(currentConfig, `storing the accessToken '${accessToken}'`);
this.storagePersistenceService.write('authzData', accessToken, currentConfig);
this.persistAccessTokenExpirationTime(authResult, currentConfig);
this.setAuthenticatedAndFireEvent(allConfigs);
}
getAccessToken(configuration) {
if (!configuration) return '';
if (!this.isAuthenticated(configuration)) return '';
const token = this.storagePersistenceService.getAccessToken(configuration);
return this.decodeURIComponentSafely(token);
}
getIdToken(configuration) {
if (!configuration) return '';
if (!this.isAuthenticated(configuration)) return '';
const token = this.storagePersistenceService.getIdToken(configuration);
return this.decodeURIComponentSafely(token);
}
getRefreshToken(configuration) {
if (!configuration) return '';
if (!this.isAuthenticated(configuration)) return '';
const token = this.storagePersistenceService.getRefreshToken(configuration);
return this.decodeURIComponentSafely(token);
}
getAuthenticationResult(configuration) {
if (!configuration) return null;
if (!this.isAuthenticated(configuration)) return null;
return this.storagePersistenceService.getAuthenticationResult(configuration);
}
areAuthStorageTokensValid(configuration) {
if (!configuration) return false;
if (!this.isAuthenticated(configuration)) return false;
if (this.hasIdTokenExpiredAndRenewCheckIsEnabled(configuration)) {
this.loggerService.logDebug(configuration, 'persisted idToken is expired');
return false;
}
if (this.hasAccessTokenExpiredIfExpiryExists(configuration)) {
this.loggerService.logDebug(configuration, 'persisted accessToken is expired');
return false;
}
this.loggerService.logDebug(configuration, 'persisted idToken and accessToken are valid');
return true;
}
hasIdTokenExpiredAndRenewCheckIsEnabled(configuration) {
const { renewTimeBeforeTokenExpiresInSeconds, triggerRefreshWhenIdTokenExpired, disableIdTokenValidation } = configuration;
if (!triggerRefreshWhenIdTokenExpired || disableIdTokenValidation) return false;
const tokenToCheck = this.storagePersistenceService.getIdToken(configuration);
const idTokenExpired = this.tokenValidationService.hasIdTokenExpired(tokenToCheck, configuration, renewTimeBeforeTokenExpiresInSeconds);
if (idTokenExpired) this.publicEventsService.fireEvent(event_types_EventTypes.IdTokenExpired, idTokenExpired);
return idTokenExpired;
}
hasAccessTokenExpiredIfExpiryExists(configuration) {
const { renewTimeBeforeTokenExpiresInSeconds } = configuration;
const accessTokenExpiresIn = this.storagePersistenceService.read('access_token_expires_at', configuration);
const accessTokenHasNotExpired = this.tokenValidationService.validateAccessTokenNotExpired(accessTokenExpiresIn, configuration, renewTimeBeforeTokenExpiresInSeconds);
const hasExpired = !accessTokenHasNotExpired;
if (hasExpired) this.publicEventsService.fireEvent(event_types_EventTypes.TokenExpired, hasExpired);
return hasExpired;
}
isAuthenticated(configuration) {
if (!configuration) {
(0, external_rxjs_namespaceObject.throwError)(()=>new Error('Please provide a configuration before setting up the module'));
return false;
}
const hasAccessToken = !!this.storagePersistenceService.getAccessToken(configuration);
const hasIdToken = !!this.storagePersistenceService.getIdToken(configuration);
return hasAccessToken && hasIdToken;
}
decodeURIComponentSafely(token) {
if (token) return decodeURIComponent(token);
return '';
}
persistAccessTokenExpirationTime(authResult, configuration) {
if (null == authResult ? void 0 : authResult.expires_in) {
const accessTokenExpiryTime = new Date(new Date().toUTCString()).valueOf() + 1000 * authResult.expires_in;
this.storagePersistenceService.write('access_token_expires_at', accessTokenExpiryTime, configuration);
}
}
composeAuthenticatedResult(allConfigs) {
if (1 === allConfigs.length) {
const { configId } = allConfigs[0];
return {
isAuthenticated: true,
allConfigsAuthenticated: [
{
configId: configId ?? '',
isAuthenticated: true
}
]
};
}
return this.checkallConfigsIfTheyAreAuthenticated(allConfigs);
}
composeUnAuthenticatedResult(allConfigs) {
if (1 === allConfigs.length) {
const { configId } = allConfigs[0];
return {
isAuthenticated: false,
allConfigsAuthenticated: [
{
configId: configId ?? '',
isAuthenticated: false
}
]
};
}
return this.checkallConfigsIfTheyAreAuthenticated(allConfigs);
}
checkallConfigsIfTheyAreAuthenticated(allConfigs) {
const allConfigsAuthenticated = allConfigs.map((config)=>({
configId: config.configId ?? '',
isAuthenticated: this.isAuthenticated(config)
}));
const isAuthenticated = allConfigsAuthenticated.every((x)=>!!x.isAuthenticated);
return {
allConfigsAuthenticated,
isAuthenticated
};
}
constructor(){
this.storagePersistenceService = (0, injection_js_namespaceObject.inject)(StoragePersistenceService);
this.loggerService = (0, injection_js_namespaceObject.inject)(LoggerService);
this.publicEventsService = (0, injection_js_namespaceObject.inject)(PublicEventsService);
this.tokenValidationService = (0, injection_js_namespaceObject.inject)(TokenValidationService);
this.authenticatedInternal$ = new external_rxjs_namespaceObject.BehaviorSubject(DEFAULT_AUTHRESULT);
}
}
AuthStateService = auth_state_service_ts_decorate([
(0, injection_js_namespaceObject.Injectable)()
], AuthStateService);
class AbstractRouter {
}
function auto_login_service_ts_decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc);
else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
const STORAGE_KEY = 'redirect';
class AutoLoginService {
checkSavedRedirectRouteAndNavigate(config) {
if (!config) return;
const savedRouteForRedirect = this.getStoredRedirectRoute(config);
if (null != savedRouteForRedirect) {
this.deleteStoredRedirectRoute(config);
this.router.navigateByUrl(savedRouteForRedirect);
}
}
saveRedirectRoute(config, url) {
if (!config) return;
this.storageService.write(STORAGE_KEY, url, config);
}
getStoredRedirectRoute(config) {
return this.storageService.read(STORAGE_KEY, config);
}
deleteStoredRedirectRoute(config) {
this.storageService.remove(STORAGE_KEY, config);
}
constructor(){
this.storageService = (0, injection_js_namespaceObject.inject)(StoragePersistenceService);
this.router = injectAbstractType(AbstractRouter);
}
}
AutoLoginService = auto_login_service_ts_decorate([
(0, injection_js_namespaceObject.Injectable)()
], AutoLoginService);
function flow_helper_service_ts_decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc);
else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
class FlowHelper {
isCurrentFlowCodeFlow(configuration) {
return this.currentFlowIs('code', configuration);
}
isCurrentFlowAnyImplicitFlow(configuration) {
return this.isCurrentFlowImplicitFlowWithAccessToken(configuration) || this.isCurrentFlowImplicitFlowWithoutAccessToken(configuration);
}
isCurrentFlowCodeFlowWithRefreshTokens(configuration) {
if (!configuration) return false;
const { useRefreshToken } = configuration;
return this.isCurrentFlowCodeFlow(configuration) && Boolean(useRefreshToken);
}
isCurrentFlowImplicitFlowWithAccessToken(configuration) {
return this.currentFlowIs('id_token token', configuration);
}
currentFlowIs(flowTypes, configuration) {
const { responseType } = configuration;
if (Array.isArray(flowTypes)) return flowTypes.some((x)=>responseType === x);
return responseType === flowTypes;
}
isCurrentFlowImplicitFlowWithoutAccessToken(configuration) {
return this.currentFlowIs('id_token', configuration);
}
}
FlowHelper = flow_helper_service_ts_decorate([
(0, injection_js_namespaceObject.Injectable)()
], FlowHelper);
function random_service_ts_decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc);
else for(var i = decorators.length - 1; i >=