/**
 * Minified by jsDelivr using Terser v5.39.0.
 * Original file: /npm/@celastrina/http@4.9.25/HTTP.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
/**
 * @author Robert R Murrell
 * @copyright Robert R Murrell
 * @license MIT
 */
"use strict";const axios=require("axios").default,{v4:uuidv4}=require("uuid"),moment=require("moment"),jwt=require("jsonwebtoken"),jwkToPem=require("jwk-to-pem"),cookie=require("cookie"),{CelastrinaError:CelastrinaError,CelastrinaValidationError:CelastrinaValidationError,AddOn:AddOn,LOG_LEVEL:LOG_LEVEL,Configuration:Configuration,Subject:Subject,Sentry:Sentry,Algorithm:Algorithm,AES256Algorithm:AES256Algorithm,Cryptography:Cryptography,RoleFactory:RoleFactory,RoleFactoryParser:RoleFactoryParser,Context:Context,BaseFunction:BaseFunction,ValueMatch:ValueMatch,AttributeParser:AttributeParser,ConfigLoader:ConfigLoader,Authenticator:Authenticator,instanceOfCelastrinaType:instanceOfCelastrinaType,AddOnEvent:AddOnEvent}=require("@celastrina/core");class Cookie{static get $object(){return{schema:"https://celastrinajs/schema/v1.0.0/http/Cookie#",type:"celastrinajs.http.Cookie"}}constructor(e,t=null,r={},s=!1){if("string"!=typeof e||0===e.trim().length)throw CelastrinaValidationError.newValidationError("Invalid String. Attribute 'name' cannot be undefined, null, or zero length.","cookie.name");this._name=e.trim(),this._value=t,this._options=r,this._dirty=s}get doSetCookie(){return this._dirty}get name(){return this._name}get parseValue(){return null==this._value?"":this._value}get value(){return this._value}set value(e){this._value=e,this._dirty=!0}get options(){return this._options}set options(e){null!=e&&void 0!==e||(e={}),this._options=e,this._dirty=!0}setOption(e,t){this._options[e]=t,this._dirty=!0}serialize(){return cookie.serialize(this._name,this.parseValue,this._options)}async toAzureCookie(){let e={name:this._name,value:this.parseValue};return Object.assign(e,this._options),e}set maxAge(e){this.setOption("maxAge",e)}set expires(e){this.setOption("expires",e)}set httpOnly(e){this.setOption("httpOnly",e)}set domain(e){this.setOption("domain",e)}set path(e){this.setOption("path",e)}set secure(e){this.setOption("secure",e)}set sameSite(e){this.setOption("sameSite",e)}get maxAge(){return this._options.maxAge}get expires(){return this._options.expires}get httpOnly(){return this._options.httpOnly}get domain(){return this._options.domain}get path(){return this._options.path}get secure(){return this._options.secure}get sameSite(){return this._options.sameSite}encodeStringToValue(e){this.value=Buffer.from(e).toString("base64")}encodeObjectToValue(e){this.encodeStringToValue(JSON.stringify(e))}decodeStringFromValue(){return Buffer.from(this.value).toString("ascii")}decodeObjectFromValue(){return JSON.parse(this.decodeStringFromValue())}delete(){this.value=null;let e=moment("1970-01-01T00:00:00Z");this.expires=e.utc().toDate()}static newCookie(e,t=null,r={}){return new Cookie(e,t,r,!0)}static async loadCookie(e,t=null,r={}){return new Cookie(e,t,r)}static async parseCookies(e,t=[]){let r=cookie.parse(e);for(let e in r)r.hasOwnProperty(e)&&t.unshift(new Cookie(e,r[e]));return t}}class JwtSubject{static get $object(){return{schema:"https://celastrinajs/schema/v1.0.0/http/JwtSubject#",type:"celastrinajs.http.JwtSubject"}}static PROP_JWT_HEADER="celastrinajs.jwt.header";static PROP_JWT_SIGNATURE="celastrinajs.jwt.signature";static PROP_JWT_NONCE="nonce";static PROP_JWT_TOKEN="celastrinajs.jwt";static PROP_JWT_AUD="aud";static PROP_JWT_ISS="iss";static PROP_JWT_ISSUED="iat";static PROP_JWT_NOTBEFORE="nbf";static PROP_JWT_EXP="exp";constructor(e){this._subject=e}get subject(){return this._subject}get header(){return this._subject.getClaimSync(JwtSubject.PROP_JWT_HEADER)}get signature(){return this._subject.getClaimSync(JwtSubject.PROP_JWT_SIGNATURE)}get token(){return this._subject.getClaimSync(JwtSubject.PROP_JWT_TOKEN)}get nonce(){return this._subject.getClaimSync(JwtSubject.PROP_JWT_NONCE)}get audience(){return this._subject.getClaimSync(JwtSubject.PROP_JWT_AUD)}get issuer(){return this._subject.getClaimSync(JwtSubject.PROP_JWT_ISS)}get issued(){return moment.unix(this._subject.getClaimSync(JwtSubject.PROP_JWT_ISSUED))}get notBefore(){let e=this._subject.getClaimSync(JwtSubject.PROP_JWT_NOTBEFORE);return null!=e&&(e=moment.unix(e)),e}get expires(){return moment.unix(this._subject.getClaimSync(JwtSubject.PROP_JWT_EXP))}get expired(){return moment().isSameOrAfter(this.expires)}async setAuthorizationHeader(e,t="Authorization",r="Bearer "){return void 0!==e&&null!=e||(e={}),e[t]=r+this._subject.getClaimSync(JwtSubject.PROP_JWT_TOKEN),e}async getHeader(e,t=null){let r=this.header[e];return void 0!==r&&null!=r||(r=t),r}static async decode(e,t){return JwtSubject.decodeSync(e,t)}static decodeSync(e,t){if("string"!=typeof t||0===t.trim().length)throw CelastrinaError.newError("Not Authorized.",401);let r=jwt.decode(t,{complete:!0});if(void 0===r||null==r)throw CelastrinaError.newError("Not Authorized.",401);return e.addClaims(r.payload),e.addClaim(JwtSubject.PROP_JWT_HEADER,r.header),e.addClaim(JwtSubject.PROP_JWT_SIGNATURE,r.signature),e.addClaim(JwtSubject.PROP_JWT_TOKEN,t),new JwtSubject(e)}static async wrap(e,t,r){return e.addClaims(t.payload),e.addClaim(JwtSubject.PROP_JWT_HEADER,t.header),e.addClaim(JwtSubject.PROP_JWT_SIGNATURE,t.signature),e.addClaim(JwtSubject.PROP_JWT_TOKEN,r),new JwtSubject(e)}}class Issuer{static get $object(){return{schema:"https://celastrinajs/schema/v1.0.0/http/Issuer#",type:"celastrinajs.http.Issuer"}}constructor(e=null,t=null,r=null,s=!1){this._issuer=e,this._audiences=t,this._assignments=r,this._validateNonce=s}get issuer(){return this._issuer}set issuer(e){this._issuer=e}get audiences(){return this._audiences}set audiences(e){this._audiences=e}get assignments(){return this._assignments}set assignments(e){this._assignments=e}get validateNonce(){return this._validateNonce}set validateNonce(e){return this._validateNonce=e}async getKey(e,t){throw CelastrinaError.newError("Not Implemented",501)}async getNonce(e,t){return null}async verify(e,t){if(t.issuer!==this._issuer)return{verified:!1};try{let r=jwt.verify(t.token,await this.getKey(e,t),{algorithm:"RSA"});if(void 0===r||null==r)return e.log("Failed to verify token.",LOG_LEVEL.THREAT,"Issuer.verify(context, _jwt)"),{verified:!1};if(null!=this._audiences&&!this._audiences.includes(t.audience))return e.log("Subject '"+t.subject.id+"' with audience '"+t.audience+"' failed to match audiences.",LOG_LEVEL.THREAT,"Issuer.verify(context, _jwt)"),{verified:!1};if(this._validateNonce){let r=await this.getNonce(e,t);if("string"==typeof r&&r.trim().length>0&&t.nonce!==r)return e.log("Subject '"+t.subject.id+"' failed to pass nonce validation.",LOG_LEVEL.THREAT,"Issuer.verify(context, _jwt)"),{verified:!1}}return{verified:!0,assignments:this._assignments}}catch(t){return e.log("Exception authenticating JWT: "+t,LOG_LEVEL.THREAT,"Issuer.verify(context, _jwt)"),{verified:!1}}}}class LocalJwtIssuer extends Issuer{static get $object(){return{schema:"https://celastrinajs/schema/v1.0.0/http/LocalJwtIssuer#",type:"celastrinajs.http.LocalJwtIssuer"}}constructor(e=null,t=null,r=null,s=null,n=!1){super(e,r,s,n),this._key=t}async getKey(e,t){return this._key}get key(){return this._key}set key(e){this._key=e}}class OpenIDJwtIssuer extends Issuer{static get $object(){return{schema:"https://celastrinajs/schema/v1.0.0/http/OpenIDJwtIssuer#",type:"celastrinajs.http.OpenIDJwtIssuer"}}constructor(e=null,t=null,r=null,s=null,n=!1){super(e,r,s,n),this._configUrl=t}get configURL(){return this._configUrl}set configURL(e){this._configUrl=e}static async _replaceURLEndpoint(e,t,r){let s,n=RegExp(/{([^}]*)}/g),a=new Set;for(;null!==(s=n.exec(r));)a.add(s[1]);for(const s of a){let n=t.subject.getClaimSync(s);if(null==n)throw e.log("Claim '"+s+"' not found for subject '"+t.subject.id+"' while building OpenID configuration URL.",LOG_LEVEL.THREAT,"OpenIDJwtIssuer._replaceURLEndpoint(context, _jwt, url)"),CelastrinaError.newError("Not Authorized.",401);Array.isArray(n)&&(n=n[0]),r=r.split("{"+s+"}").join(n)}return r}static async _getKey(e,t,r){let s=await OpenIDJwtIssuer._replaceURLEndpoint(e,t,r);try{let e=await axios.get(s),r=e.data.issuer;s=e.data.jwks_uri,e=await axios.get(s);let n=null;for(const s of e.data.keys)if(s.kid===t.header.kid){n={issuer:r,type:s.kty,key:s};break}return n}catch(r){e.log("Exception getting OpenID configuration for subject "+t.subject.id+": "+r,LOG_LEVEL.ERROR,"OpenIDJwtIssuer._getKey(subject, context)"),CelastrinaError.newError("Exception authenticating user.",401)}}async _getPemX5C(e,t){return"-----BEGIN PUBLIC KEY-----\n"+e.key.x5c+"\n-----END PUBLIC KEY-----\n"}async getKey(e,t){let r,s=await OpenIDJwtIssuer._getKey(e,t,this._configUrl);return r=void 0===s.key.x5c||null==s.key.x5c?jwkToPem(s.key):await this._getPemX5C(s,e),r}}class IssuerParser extends AttributeParser{static get $object(){return{schema:"https://celastrinajs/schema/v1.0.0/http/IssuerParser#",type:"celastrinajs.http.IssuerParser"}}constructor(e=null,t="BaseIssuer",r="1.0.0"){super(t,e,r)}_loadIssuer(e,t){if(!e.hasOwnProperty("issuer")||"string"!=typeof e.issuer||0===e.issuer.trim().length)throw CelastrinaValidationError.newValidationError("[IssuerParser._loadIssuer(_Issuer, _issuer)][_Issuer.issuer]: Issuer cannot be null, undefined, or empty.","_Issuer.issuer");if(!e.hasOwnProperty("audiences")||!Array.isArray(e.audiences)||0===e.audiences.length)throw CelastrinaValidationError.newValidationError("[IssuerParser._loadIssuer(_Issuer, _issuer)][_Issuer.audiences]: Audiences cannot be null.","_Issuer.audiences");let r=[];e.hasOwnProperty("assignments")&&Array.isArray(e.assignments)&&e.assignments.length>0&&(r=e.assignments);let s=!1;e.hasOwnProperty("validateNonce")&&"boolean"==typeof e.validateNonce&&(s=e.validateNonce),t.issuer=e.issuer.trim(),t.audiences=e.audiences,t.assignments=r,t.validateNonce=s}}class LocalJwtIssuerParser extends IssuerParser{static get $object(){return{schema:"https://celastrinajs/schema/v1.0.0/http/LocalJwtIssuerParser#",type:"celastrinajs.http.LocalJwtIssuerParser"}}constructor(e=null,t="1.0.0"){super(e,"LocalJwtIssuer",t)}async _create(e,t){let r=new LocalJwtIssuer;if(await this._loadIssuer(e,r),!e.hasOwnProperty("key")||"string"!=typeof e.key||0===e.key.trim().length)throw CelastrinaValidationError.newValidationError("[LocalJwtIssuerParser._create(_LocalJwtIssuer)][_LocalJwtIssuer.key]: ","_LocalJwtIssuer.key");return r.key=e.key.trim(),r}}class OpenIDJwtIssuerParser extends IssuerParser{static get $object(){return{schema:"https://celastrinajs/schema/v1.0.0/http/OpenIDJwtIssuerParser#",type:"celastrinajs.http.OpenIDJwtIssuerParser"}}constructor(e=null,t="1.0.0"){super(e,"OpenIDJwtIssuer",t)}async _create(e,t){let r=new OpenIDJwtIssuer;if(await this._loadIssuer(e,r),!e.hasOwnProperty("configURL")||"string"!=typeof e.configURL||0===e.configURL.trim().length)throw CelastrinaValidationError.newValidationError("[OpenIDJwtIssuerParser._create(_OpenIDJwtIssuer)][_OpenIDJwtIssuer.configURL]: configURL cannot be null or empty.","_OpenIDJwtIssuer.configURL");return r.configURL=e.configURL.trim(),r}}class HTTPParameter{static get $object(){return{schema:"https://celastrinajs/schema/v1.0.0/http/HTTPParameter#",type:"celastrinajs.http.HTTPParameter"}}constructor(e="HTTPParameter",t=!1){this._type=e,this._readOnly=t}get type(){return this._type}get readOnly(){return this._readOnly}async _getParameter(e,t){throw CelastrinaError.newError("Not Implemented.",501)}async getParameter(e,t,r=null){let s=await this._getParameter(e,t);return void 0!==s&&null!=s||(s=r),s}async _setParameter(e,t,r=null){}async setParameter(e,t,r=null){if(this._readOnly)throw CelastrinaError.newError("Set Parameter not supported.");await this._setParameter(e,t,r)}}class HeaderParameter extends HTTPParameter{static get $object(){return{schema:"https://celastrinajs/schema/v1.0.0/http/HeaderParameter#",type:"celastrinajs.http.HeaderParameter"}}constructor(e="header"){super(e)}async _getParameter(e,t){return e.getRequestHeader(t)}async _setParameter(e,t,r=null){await e.setResponseHeader(t,r)}}class CookieParameter extends HTTPParameter{static get $object(){return{schema:"https://celastrinajs/schema/v1.0.0/http/CookieParameter#",type:"celastrinajs.http.CookieParameter"}}constructor(e="cookie"){super(e)}async _getParameter(e,t){let r=await e.getCookie(t,null);return null!=r&&(r=r.value),r}async _setParameter(e,t,r=null){let s=await e.getCookie(t,null);null==s?s=Cookie.newCookie(t,r):s.value=r,await e.setCookie(s)}}class QueryParameter extends HTTPParameter{static get $object(){return{schema:"https://celastrinajs/schema/v1.0.0/http/QueryParameter#",type:"celastrinajs.http.QueryParameter"}}constructor(e="query"){super(e,!0)}async _getParameter(e,t){return e.getQuery(t)}async _setParameter(e,t,r=null){throw CelastrinaError.newError("QueryParameter.setParameter not supported.",501)}}class BodyParameter extends HTTPParameter{static get $object(){return{schema:"https://celastrinajs/schema/v1.0.0/http/BodyParameter#",type:"celastrinajs.http.BodyParameter"}}constructor(e="body"){super(e)}async _getParameter(e,t){let r=e.requestBody,s=t.split(".");for(const e of s)r=r[e];return r}async _setParameter(e,t,r=null){let s=e.responseBody,n=t.trim().split(".");for(let e=0;e<n.length-2;++e)if(s=s[n[e]],void 0===s||null==s)throw CelastrinaError.newError("Invalid object path '"+t+"'.");s[n[n.length-1]]=r}}class HTTPParameterParser extends AttributeParser{static get $object(){return{schema:"https://celastrinajs/schema/v1.0.0/http/HTTPParameterParser#",type:"celastrinajs.http.HTTPParameterParser"}}constructor(e=null,t="1.0.0"){super("HTTPParameter",e,t)}async _create(e,t){let r="header";return e.hasOwnProperty("parameter")&&"string"==typeof e.parameter&&e.parameter.trim().length>0&&(r=e.parameter.trim()),HTTPParameterParser.createHTTPParameter(r)}static createHTTPParameter(e){switch(e){case"header":return new HeaderParameter;case"cookie":return new CookieParameter;case"query":return new QueryParameter;case"body":return new BodyParameter;default:throw CelastrinaValidationError.newValidationError("[HTTPParameterParser.getHTTPParameter(type)][type]: '"+e+"' is not supported.","type")}}}class Session{static get $object(){return{schema:"https://celastrinajs/schema/v1.0.0/http/Session#",type:"celastrinajs.http.Session"}}constructor(e={},t=!1,r=uuidv4()){void 0!==e.id&&null!=e.id||(e.id=r),this._values=e,this._dirty=t,this._new=t}get id(){return this._values.id}get isNew(){return this._new}async getProperty(e,t=null){let r=this._values[e];return void 0===r||null==r?t:r}async setProperty(e,t){this._values[e]=t,this._dirty=!0}async deleteProperty(e){delete this._values[e],this._dirty=!0}get doWriteSession(){return this._dirty}static load(e){return new Session(e)}}class SessionManager{static get $object(){return{schema:"https://celastrinajs/schema/v1.0.0/http/SessionManager#",type:"celastrinajs.http.SessionManager"}}constructor(e,t="celastrinajs_session",r=!0){if(void 0===e||null==e)throw CelastrinaValidationError.newValidationError("Argument 'parameter' cannot be null.","parameter");if("string"!=typeof t||0===t.trim().length)throw CelastrinaValidationError.newValidationError("Argument 'name' cannot be null or empty.","name");this._parameter=e,this._name=t.trim(),this._createNew=r}get parameter(){return this._parameter}get name(){return this._name}get createNew(){return this._createNew}async initialize(e,t){}async newSession(){return this._session=new Session({},!0),this._session}async _loadSession(e,t){return e}async loadSession(e){let t=await this._parameter.getParameter(e,this._name);if(void 0===t||null==t){if(!this._createNew)return null;t=this.newSession()}else{let r=await this._loadSession(t,e);if(void 0===r||null==r||0===r.trim().length){if(!this._createNew)return null;t=await this.newSession()}else t=Session.load(JSON.parse(r))}return t}async _saveSession(e,t){return e}async saveSession(e=null,t){instanceOfCelastrinaType(Session,e)&&e.doWriteSession&&!this._parameter.readOnly&&await this._parameter.setParameter(t,this._name,await this._saveSession(JSON.stringify(e),t))}}class SecureSessionManager extends SessionManager{static get $object(){return{schema:"https://celastrinajs/schema/v1.0.0/http/SecureSessionManager#",type:"celastrinajs.http.SecureSessionManager"}}constructor(e,t,r="celastrinajs_session",s=!0){super(t,r,s),this._crypto=new Cryptography(e)}get cryptography(){return this._crypto}async initialize(e,t){await super.initialize(e,t),await this._crypto.initialize()}async _loadSession(e,t){return this._crypto.decrypt(e)}async _saveSession(e,t){return this._crypto.encrypt(e)}}class AESSessionManager extends SecureSessionManager{static get $object(){return{schema:"https://celastrinajs/schema/v1.0.0/http/AESSessionManager#",type:"celastrinajs.http.AESSessionManager"}}constructor(e,t,r="celastrinajs_session",s=!0){if(void 0===e||null==e)throw CelastrinaValidationError.newValidationError("Argement 'options' cannot be undefined or null","options");if("string"!=typeof e.key||0===e.key.trim().length)throw CelastrinaValidationError.newValidationError("Argement 'key' cannot be undefined, null or zero length.","options.key");if("string"!=typeof e.iv||0===e.iv.trim().length)throw CelastrinaValidationError.newValidationError("Argement 'iv' cannot be undefined, null or zero length.","options.iv");super(AES256Algorithm.create(e),t,r,s)}}class SessionRoleFactory extends RoleFactory{static get $object(){return{schema:"https://celastrinajs/schema/v1.0.0/http/SessionRoleFactory#",type:"celastrinajs.http.SessionRoleFactory"}}constructor(e="roles"){super(),this._key=e}get key(){return this._key}async getSubjectRoles(e,t){let r=await e.session.getProperty(this._key,[]);if(!Array.isArray(r))throw CelastrinaError.newError("Invalid role assignments for session key '"+this._key+"'.");return r}}class SessionRoleFactoryParser extends RoleFactoryParser{static get $object(){return{schema:"https://celastrinajs/schema/v1.0.0/http/SessionRoleFactoryParser#",type:"celastrinajs.http.SessionRoleFactoryParser"}}constructor(e=null,t="1.0.0"){super(e,"SessionRoleFactory",t)}async _create(e,t){let r="roles";return e.hasOwnProperty("key")&&"string"==typeof e.key&&(r=e.key),new SessionRoleFactory(r)}}class AESSessionManagerParser extends AttributeParser{static get $object(){return{schema:"https://celastrinajs/schema/v1.0.0/http/AESSessionManagerParser#",type:"celastrinajs.http.AESSessionManagerParser"}}constructor(e=null,t="1.0.0"){super("AESSessionManager",e,t)}async _create(e,t){let r="cookie",s="celastrinajs_session";e.hasOwnProperty("parameter")&&"string"==typeof e.parameter&&(r=e.parameter),e.hasOwnProperty("name")&&"string"==typeof e.name&&(s=e.name);let n=!0;e.hasOwnProperty("createNew")&&"boolean"==typeof e.createNew&&(n=e.createNew);let a=null;if(!e.hasOwnProperty("options")||"object"!=typeof e.options||null==e.options)throw CelastrinaValidationError.newValidationError("[AESSessionManagerParser._create(_AESSessionManager)][AESSessionManager.options]: Argument 'optiosn' cannot be null or undefined.","AESSessionManager.options");if(a=e.options,!a.hasOwnProperty("iv")||"string"!=typeof a.iv||0===a.iv.trim().length)throw CelastrinaValidationError.newValidationError("[AESSessionManagerParser._create(_AESSessionManager)][AESSessionManager.options.iv]: Aregument 'iv' cannot be null or empty.","AESSessionManager.options.iv");if(!a.hasOwnProperty("key")||"string"!=typeof a.key||0===a.key.trim().length)throw CelastrinaValidationError.newValidationError("[AESSessionManagerParser._create(_AESSessionManager)][AESSessionManager.options.key]: Argument 'key' cannot be null or empty.","AESSessionManager.options.key");return new AESSessionManager(a,HTTPParameterParser.createHTTPParameter(r),s,n)}}class HMAC{static get $object(){return{schema:"https://celastrinajs/schema/v1.0.0/http/HMAC#",type:"celastrinajs.http.HMAC"}}constructor(e,t=new HeaderParameter,r="x-ms-content-sha256",s="sha256",n="hex",a=[]){this._parameter=t,this._name=r,this._secret=e,this._algorithm=s,this._assignments=a,this._encoding=n}get name(){return this._name}get secret(){return this._secret}get algorithm(){return this._algorithm}get encoding(){return this._encoding}get parameter(){return this._parameter}get assignments(){return this._assignments}set assignments(e){return this._assignments=e}}class HTTPConfigLoader extends ConfigLoader{static get $object(){return{schema:"https://celastrinajs/schema/v1.0.0/http/HTTPConfigLoader#",type:"celastrinajs.http.HTTPConfigLoader"}}constructor(e=null,t="1.0.0"){super("HTTP",e,t)}async _load(e,t){if(!e.hasOwnProperty("session")||"object"!=typeof e.session||null==e.session)throw CelastrinaValidationError.newValidationError("Argument 'session' is required.","_Configuration.session");if(!e.session.hasOwnProperty("manager")||!instanceOfCelastrinaType(SessionManager,e.session.manager))throw CelastrinaValidationError.newValidationError("Argument 'manager' is required.","_Configuration.session.manager");t[HTTPAddOn.CONFIG_HTTP]=e}}class HTTPAddOn extends AddOn{static get $object(){return{schema:"https://celastrinajs/schema/v1.0.0/http/HTTPAddOn#",type:"celastrinajs.http.HTTPAddOn",addOn:"celastrinajs.addon.http"}}static CONFIG_HTTP="celastrinajs.addon.http.config";constructor(){super([]),this._httpconfig={session:{manager:null}}}getConfigLoader(){return new HTTPConfigLoader}getAttributeParser(){return new AESSessionManagerParser(new SessionRoleFactoryParser(new HTTPParameterParser))}get sessionManager(){return this._httpconfig.session.manager}set sesionManager(e){this._httpconfig.session.manager=e}setSessionManager(e=null){return this._httpconfig.session.manager=e,this}async install(e,t,r){let s=t[HTTPAddOn.CONFIG_HTTP];void 0!==s&&null!=s&&Object.assign(this._httpconfig,s),instanceOfCelastrinaType(SessionManager,this._httpconfig.session.manager)&&await this._httpconfig.session.manager.initialize(e,t),await r.addEventListener(AddOnEvent.TYPE.AFTER_PROCESS,this,HTTPAddOn.handleProcessLifecycle),await r.addEventListener(AddOnEvent.TYPE.AFTER_TERMINATE,this,HTTPAddOn.handleTerminateLifecycle),await r.addEventListener(AddOnEvent.TYPE.AFTER_EXCEPTION,this,HTTPAddOn.handleExceptionLifecycle),await r.addEventListener(AddOnEvent.TYPE.AFTER_MONITOR,this,HTTPAddOn.handleMonitorLifecycle)}async loadSession(e){return null!=this._httpconfig.session.manager?this._httpconfig.session.manager.loadSession(e):null}async saveSession(e,t){if(null!=this._httpconfig.session.manager)return this._httpconfig.session.manager.saveSession(e,t)}static async handleProcessLifecycle(e,t,r){let s=e.source[e.context.method];"function"!=typeof s?await e.source.unhandledRequestMethod(e.context):await s.call(e.source,e.context)}static async handleTerminateLifecycle(e,t,r){await e.context.terminate()}static async handleExceptionLifecycle(e,t,r){let s=e.data;instanceOfCelastrinaType(CelastrinaValidationError,s)?e.context.sendValidationError(s):instanceOfCelastrinaType(CelastrinaError,s)?e.context.sendServerError(s):s instanceof Error?(s=CelastrinaError.wrapError(s),e.context.sendServerError(s)):void 0===s||null==s?(s=CelastrinaError.newError("Unhandled server error."),e.context.sendServerError(s)):(s=CelastrinaError.wrapError(s),e.context.sendServerError(s)),e.context.log("Request failed to process. \r\n (MESSAGE: "+s.message+") \r\n (STACK: "+s.stack+") \r\n (CAUSE: "+s.cause+")",LOG_LEVEL.ERROR,"HTTP.exception(context, exception)")}static async handleMonitorLifecycle(e,t,r){let s=[{test:context.name,passed:e.context.monitorResponse.passed,failed:e.context.monitorResponse.failed,result:e.context.monitorResponse.result}];e.context.send(s,200)}}class JwtConfigLoader extends ConfigLoader{static get $object(){return{schema:"https://celastrinajs/schema/v1.0.0/http/JwtConfigurationParser#",type:"celastrinajs.http.JwtConfigLoader"}}constructor(e=null,t="1.0.0"){super("JWT",e,t)}async _load(e,t){t[JwtAddOn.CONFIG_JWT]=e}}class JwtAddOn extends AddOn{static get $object(){return{schema:"https://celastrinajs/schema/v1.0.0/http/JwtAddOn#",type:"celastrinajs.http.JwtAddOn",addOn:"celastrinajs.addon.http.jwt"}}static CONFIG_JWT="celastrinajs.addon.http.jwt.config";constructor(){super([HTTPAddOn.$object.addOn]),this._jwtconfig={issuers:[],parameter:new HeaderParameter,name:"authorization",scheme:"Bearer",removeScheme:!0,required:!1}}getConfigLoader(){return new JwtConfigLoader}getAttributeParser(){return new OpenIDJwtIssuerParser(new LocalJwtIssuerParser)}async install(e,t,r){let s=t[JwtAddOn.CONFIG_JWT];void 0!==s&&null!=s&&Object.assign(this._jwtconfig,s),t[Configuration.CONFIG_SENTRY].addAuthenticator(new JwtAuthenticator(this._jwtconfig.required,null,this._jwtconfig.parameter,this._jwtconfig.name,this._jwtconfig.scheme,this._jwtconfig.removeScheme,this._jwtconfig.issuers))}get issuers(){return this._jwtconfig.issuers}set issuers(e){void 0!==e&&null!=e||(e=[]),this._jwtconfig.issuers=e}get parameter(){return this._jwtconfig.parameter}set parameter(e){this._jwtconfig.parameter=e}get token(){return this._jwtconfig.name}set token(e){this._jwtconfig.name=e}get scheme(){return this._jwtconfig.scheme}set scheme(e){this._jwtconfig.scheme=e}get removeScheme(){return this._jwtconfig.removeScheme}set removeScheme(e){this._jwtconfig.removeScheme=e}get required(){return this._jwtconfig.required}set required(e){this._jwtconfig.required=e}setIssuers(e=[]){return this._jwtconfig.issuers=e,this}addIssuer(e){return this._jwtconfig.issuers.unshift(e),this}setParameter(e){return this._jwtconfig.parameter=e,this}setToken(e){return this._jwtconfig.name=e,this}setScheme(e){return this._jwtconfig.scheme=e,this}setRemoveScheme(e){return this._jwtconfig.removeScheme=e,this}setRequired(e){return this._jwtconfig.required=e,this}}class HTTPContext extends Context{static get $object(){return{schema:"https://celastrinajs/schema/v1.0.0/http/HTTPContext#",type:"celastrinajs.http.HTTPContext"}}constructor(e){super(e),this._cookies={},this._session=null}get cookies(){return this._cookies}get method(){return this._action}get url(){return this._config.context.req.originalUrl}get request(){return this._config.context.req}get response(){return this._config.context.res}get headers(){return this._config.context.req.headers}get params(){return this._config.context.req.params}get query(){return this._config.context.req.query}get raw(){return this._config.context.req.rawBody}get requestBody(){return this._config.context.req.body}get responseBody(){return this._config.context.res.body}get session(){return this._session}async _setRequestId(){let e=this._config.context.req.query.requestId;void 0!==e&&null!=e||(e=this._config.context.req.headers["x-celastrina-requestId"]),"string"==typeof e&&(this._requestId=e)}async _setMonitorMode(){let e;"trace"===this.method?e=!0:(e=this._config.context.req.query.monitor,void 0!==e&&null!=e||(e=this._config.context.req.headers["x-celastrina-monitor"]),e="string"==typeof e&&"true"===e),this._monitor=e}async _parseCookies(){let e=cookie.parse(await this.getRequestHeader("cookie",""),"");for(let t in e)if(e.hasOwnProperty(t)){let r=e[t];void 0!==r&&null!=r&&(this._cookies[t]=new Cookie(t,r))}}async _setSession(){let e=await this._config.addOns.get(HTTPAddOn);null!=e&&(this._session=await e.loadSession(this))}async initialize(){await super.initialize(),this._config.context.res.status=200,this._config.context.res.headers["Content-Type"]="text/html; charset=ISO-8859-1",this._config.context.res.body='<html lang="en"><head><title>'+this._config.name+"</title></head><body><header>200, Success</header><footer>Powered by celastrinajs.</footer></body></html>",this._action=this._config.context.req.method.toLowerCase(),await this._setMonitorMode(),await this._setRequestId(),await this._parseCookies(),await this._setSession()}async _rewriteSession(){let e=await this._config.addOns.get(HTTPAddOn);null!=e&&null!=this.session&&this.session.doWriteSession&&await e.saveSession(this,this._session)}async _setCookies(){let e=this.cookies,t=[];for(const r in e)if(e.hasOwnProperty(r)){let s=e[r];instanceOfCelastrinaType(Cookie,s)&&t.unshift(s.toAzureCookie())}t=await Promise.all(t),t.length>0&&(this.azureFunctionContext.res.cookies=t)}async terminate(){await this._rewriteSession(),await this._setCookies()}async getURIBinding(e,t=null){let r=this._config.context.bindingData[e];return void 0===r||null==r?t:r}async getCookie(e,t=null){let r=this._cookies[e];return void 0===r||null==r?t:r}async setCookie(e){this._cookies[e.name]=e}async getQuery(e,t=null){let r=this._config.context.req.query[e];return"string"!=typeof r?t:r}async splitHeader(e,t=";",r=!0){if(null!=e){let s=e.split(t);if(r)for(let e=0;e<s.length;++e)s[e]=s[e].trim();return s}return[]}async getRequestHeader(e,t=null){let r=this._config.context.req.headers[e];return"string"!=typeof r?t:r}async splitRequestHeader(e,t=null,r=";",s=!0){return this.splitHeader(await this.getRequestHeader(e,t),r,s)}async requestHeaderContains(e,t,r=!1){let s=await this.getRequestHeader(e);return null!=s&&-1!==s.search(t)}async containsRequestHeader(e){return this.config.context.req.headers.hasOwnProperty(e)}async deleteResponseHeader(e){try{delete this._config.context.res.headers[e]}catch(e){this.log("Silent exception thrown while deleting response header: "+e+". \r\nNo action taken.",LOG_LEVEL.ERROR,"HTTPContext.deleteResponseHeader(name)")}}async getResponseHeader(e,t=null){let r=this._config.context.res.headers[e];return"string"!=typeof r?t:r}async splitResponseHeader(e,t=null,r=";",s=!0){return this.splitHeader(await this.getResponseHeader(e,t),r,s)}async setResponseHeader(e,t){this._config.context.res.headers[e]=t}send(e=null,t=200){t>=200&&t<=299&&(null==e||"string"==typeof e&&0===e.length)&&(t=204),this._config.context.res.status=t,this._config.context.res.headers["X-celastrina-request-uuid"]=this._requestId,this._config.context.res.body=e}sendValidationError(e=null,t=null){null==e&&(e=CelastrinaValidationError.newValidationError("bad request")),null==t&&(t='<html lang="en"><head><title>'+this._config.name+"</title></head><body><header>400 - Bad Request</header><main><p><h2>"+e.message+"</h2><br />"+e.tag+"</p></main><footer>Powered by celastrinajs.</footer></body></html>"),this.send(t,e.code)}sendRedirect(e,t=null){this._config.context.res.headers.Location=e,null==t&&(t='<html lang="en"><head><title>'+this._config.name+"</title></head><body><header>302 - Redirect</header><main><p><h2>"+e+"</h2></main><footer>Pwered by celastrinajs.</footer></body></html>"),this.send(t,302)}sendRedirectForwardBody(e){this.sendRedirect(e,this._config.context.req.body)}sendServerError(e=null,t=null){switch(null==e?e=CelastrinaError.newError("Internal Server Error."):instanceOfCelastrinaType(CelastrinaError,e)||(e=CelastrinaError.wrapError(e,500)),e.code){case 403:this.sendForbiddenError(e);break;case 401:this.sendNotAuthorizedError(e);break;case 400:this.sendValidationError(e);break;default:null==t&&(t='<html lang="en"><head><title>'+this._config.name+"</title></head><body><header>"+e.code+" - Internal Server Error</header><main><p><h2>"+e.message+"</h2></main><footer>Powered by celastrinajs.</footer></body></html>"),this.send(t,e.code)}}sendNotAuthorizedError(e=null,t=null){null==e?e=CelastrinaError.newError("Not Authorized.",401):instanceOfCelastrinaType(CelastrinaError,e)||(e=CelastrinaError.wrapError(e,401)),null==t&&(t='<html lang="en"><head><title>'+this._config.name+"</title></head><body><header>401 - Not Authorized</header><main><p><h2>"+e.message+"</h2></main><footer>Powered by celastrinajs.</footer></body></html>"),this.send(t,401)}sendForbiddenError(e=null,t=null){null==e?e=CelastrinaError.newError("Forbidden.",403):instanceOfCelastrinaType(CelastrinaError,e)||(e=CelastrinaError.wrapError(e,403)),null==t&&(t='<html lang="en"><head><title>'+this._config.name+"</title></head><body><header>403 - Forbidden</header><main><p><h2>"+e.message+"</h2></main><footer>Powered by celastrinajs.</footer></body></html>"),this.send(t,403)}}class JSONHTTPContext extends HTTPContext{static get $object(){return{schema:"https://celastrinajs/schema/v1.0.0/http/JSONHTTPContext#",type:"celastrinajs.http.JSONHTTPContext"}}constructor(e){super(e)}async initialize(){await super.initialize(),this._config.context.res.status=200,this._config.context.res.headers["Content-Type"]="application/json; charset=utf-8",this._config.context.res.body={name:this._config.name,code:200,message:"Success! Welcome to celastrinajs."}}sendCelastrinaError(e,t=null){let r=null;"string"==typeof e.tag&&e.tag.trim().length>0&&(r=e.tag);let s=null;e.cause instanceof Error&&(s=e.cause.message);let n=e.code;null!=t&&(n=t),this.send({name:e.name,message:e.message,tag:r,code:n,cause:s,drop:e.drop},n)}sendValidationError(e=null,t=null){null==e&&(e=CelastrinaValidationError.newValidationError("bad request")),null==t?this.sendCelastrinaError(e,400):this.send(t,400)}sendRedirect(e,t=null){this._config.context.res.headers.Location=e,null==t&&(t={code:302,url:e}),this.send(t,302)}sendServerError(e=null,t=null){null==e?e=CelastrinaError.newError("Internal Server Error."):instanceOfCelastrinaType(CelastrinaError,e)||(e=CelastrinaError.wrapError(e,500)),null==t?this.sendCelastrinaError(e):this.send(t,500)}sendNotAuthorizedError(e=null,t=null){null==e?e=CelastrinaError.newError("Not Authorized.",401):instanceOfCelastrinaType(CelastrinaError,e)||(e=CelastrinaError.wrapError(e,401)),null==t?this.sendCelastrinaError(e,401):this.send(t,401)}sendForbiddenError(e=null,t=null){null==e?e=CelastrinaError.newError("Forbidden.",403):instanceOfCelastrinaType(CelastrinaError,e)||(e=CelastrinaError.wrapError(e,403)),null==t?this.sendCelastrinaError(e,403):this.send(t,403)}}class JwtAuthenticator extends Authenticator{static get $object(){return{schema:"https://celastrinajs/schema/v1.0.0/http/JwtAuthenticator#",type:"celastrinajs.http.JwtAuthenticator"}}constructor(e=!1,t=null,r,s,n,a,i){super("JWT",e,t),this._parameter=r,this._token=s,this._scheme=n,this._removeScheme=a,this._issuers=i}async _getToken(e){let t=await this._parameter.getParameter(e,this._token);if("string"!=typeof t)return e.log("JWT "+this._parameter.type+" token "+this._token+" but none was found.",LOG_LEVEL.THREAT,"JwtAuthenticator._getToken(context, _config)"),null;let r=this._scheme;if("string"==typeof r&&r.length>0){if(!t.startsWith(r))return e.log("Expected JWT token scheme '"+r+"' but none was found.",LOG_LEVEL.THREAT,"JwtAuthenticator._getToken(context, _config)"),null;this._removeScheme&&(t=t.slice(r.length).trim())}return t}async _authenticate(e){let t=await this._getToken(e.context);if(null!=t){let r=null;try{r=JwtSubject.decodeSync(e.subject,t)}catch(t){return e.context.log("JWT Token failed to decode, invlid signature.",LOG_LEVEL.THREAT,"JwtAuthenticator.createSubject(context)"),e.assert(this._name,!1,null,"Invalid Signature.")}let s=e.subject.id;if(void 0!==s&&null!=s||(s=e.context.requestId),r.expired)return e.context.log("'"+s+"' token expired.",LOG_LEVEL.THREAT,"JwtAuthenticator.createSubject(context)"),e.assert(this._name,!1,null,"Token Expired.");let n=[];for(const t of this._issuers)n.unshift(t.verify(e.context,r));let a=await Promise.all(n),i=!1,o=[];for(let e of a)e.verified&&!i&&(i=!0),o=o.concat(e.assignments);return e.assert(this._name,i,o)}return e.context.log("No JWT token found.",LOG_LEVEL.THREAT,"JwtAuthenticator.createSubject(context)"),e.assert(this._name,!1,null,"No Token Found.")}}class HTTPFunction extends BaseFunction{static get $object(){return{schema:"https://celastrinajs/schema/v1.0.0/http/HTTPFunction#",type:"celastrinajs.http.HTTPFunction"}}constructor(e){super(e)}async createContext(e){return new HTTPContext(e)}async unhandledRequestMethod(e){throw CelastrinaError.newError("HTTP Method '"+e.method+"' not supported.",501)}async handleError(e,t,r){e.res.status=r.code,e.res.headers["X-celastrinajs-invocationId"]=e.executionContext.invocationId,e.res.headers["Content-Type"]="text/html; charset=UTF-8",e.res.body='<html lang="en"><head><title>'+e.executionContext.functionName+"</title></head><body><header>"+r.code+" - "+r.message+"</header><main></main><footer>Powered by celastrinajs</footer></body></html>"}}class JSONHTTPFunction extends HTTPFunction{static get $object(){return{schema:"https://celastrinajs/schema/v1.0.0/http/JSONHTTPFunction#",type:"celastrinajs.http.JSONHTTPFunction"}}constructor(e){super(e)}async createContext(e){return new JSONHTTPContext(e)}async handleError(e,t,r){e.res.status=r.code,e.res.headers["X-celastrinajs-invocationId"]=e.executionContext.invocationId,e.res.headers["Content-Type"]="application/json; charset=UTF-8",e.res.body={name:r.name,message:r.message,code:r.code,drop:r.drop}}}class MatchAlways extends ValueMatch{static get $object(){return{schema:"https://celastrinajs/schema/v1.0.0/http/MatchAlways#",type:"celastrinajs.http.MatchAlways"}}constructor(){super("MatchAlways")}async isMatch(e,t){return!0}}class HMACAuthenticator extends Authenticator{static get $object(){return{schema:"https://celastrinajs/schema/v1.0.0/http/HMACAuthenticator#",type:"celastrinajs.http.HMACAuthenticator"}}constructor(e=!1,t,r=null){super("HMAC",e,r),this._hmac=t}async _authenticate(e){let t=e.context,r=crypto.createHmac(this._hmac.algorithm,this._hmac.secret).update(t.raw).digest(this._hmac.encoding).toString(),s=(await this._hmac.parameter.getParameter(t,this._hmac.name)).toUpperCase()===r.toUpperCase(),n=null;s?n=this._hmac.assignments:e.context.log("'"+e.subject.id+"' has an invalid HMAC signature.",LOG_LEVEL.THREAT,"HMACAuthenticator._authenticate(assertion)"),e.assert(this._name,s,n)}}class HMACConfigLoader extends ConfigLoader{static get $object(){return{schema:"https://celastrinajs/schema/v1.0.0/http/HMACConfigurationParser#",type:"celastrinajs.http.HMACConfigurationParser"}}constructor(e=null,t="1.0.0"){super("HMAC",e,t)}async _load(e,t){t[HMACAddOn.CONFIG_HMAC]=e}}class HMACParser extends AttributeParser{static get $object(){return{schema:"https://celastrinajs/schema/v1.0.0/http/HMACParser#",type:"celastrinajs.http.HMACParser"}}constructor(e=null,t="1.0.0"){super("HMAC",e,t)}async _create(e,t){if(!e.hasOwnProperty("secret")||"string"!=typeof e.secret||0===e.secret.length)throw CelastrinaValidationError.newValidationError("Argument 'secret' is required.","_HMAC.secret");let r,s="x-celastrinajs-hmac",n=new HeaderParameter,a="sha256",i="hex";return e.hasOwnProperty("parameter")&&instanceOfCelastrinaType(HTTPParameter,e.parameter)&&(n=e.parameter),e.hasOwnProperty("name")&&"string"==typeof e.name&&e.name.trim().length>0&&(s=e.name.trim()),e.hasOwnProperty("algorithm")&&"string"==typeof e.algorithm&&e.algorithm.trim().length>0&&(a=e.algorithm.trim()),e.hasOwnProperty("encoding")&&"string"==typeof e.encoding&&e.encoding.trim().length>0&&(i=e.encoding.trim()),r=e.hasOwnProperty("assignments")&&Array.isArray(e.assignments)?e.assignments:[],new HMAC(e.secret,n,s,a,i,r)}}class HMACAddOn extends AddOn{static get $object(){return{schema:"https://celastrinajs/schema/v1.0.0/http/HMACAddOn#",type:"celastrinajs.http.HMACAddOn",addOn:"celastrinajs.addon.http.hmac"}}static CONFIG_HMAC="celastrinajs.addon.http.hmac.config";constructor(e=[HTTPAddOn.$object.addOn]){super(e),this._hmacconfig={required:!1,hmac:null}}getConfigLoader(){return new HMACConfigLoader}getAttributeParser(){return new HMACParser}get hmac(){return this._hmacconfig.hmac}set hmac(e){this._hmacconfig.hmac=e}get required(){return this._hmacconfig.required}set required(e){this._hmacconfig.required=e}async install(e,t,r){let s=t[HMACAddOn.CONFIG_HMAC];void 0!==s&&null!=s&&Object.assign(this._hmacconfig,s);let n=t[Configuration.CONFIG_SENTRY];if(!instanceOfCelastrinaType(HMAC,this._hmacconfig.hmac)||void 0===this._hmacconfig.hmac.secret||null==this._hmacconfig.hmac.secret||0===this._hmacconfig.hmac.secret.length)throw CelastrinaError.newError("Cannot load HMAC Add-On, missing required HMAC configuration.");n.addAuthenticator(new HMACAuthenticator(this._hmacconfig.required,this._hmacconfig.hmac))}}module.exports={MatchAlways:MatchAlways,Cookie:Cookie,JwtSubject:JwtSubject,HTTPContext:HTTPContext,JSONHTTPContext:JSONHTTPContext,Issuer:Issuer,IssuerParser:IssuerParser,LocalJwtIssuer:LocalJwtIssuer,LocalJwtIssuerParser:LocalJwtIssuerParser,OpenIDJwtIssuer:OpenIDJwtIssuer,OpenIDJwtIssuerParser:OpenIDJwtIssuerParser,HTTPParameter:HTTPParameter,HeaderParameter:HeaderParameter,QueryParameter:QueryParameter,BodyParameter:BodyParameter,CookieParameter:CookieParameter,Session:Session,SessionManager:SessionManager,SecureSessionManager:SecureSessionManager,AESSessionManager:AESSessionManager,AESSessionManagerParser:AESSessionManagerParser,SessionRoleFactory:SessionRoleFactory,SessionRoleFactoryParser:SessionRoleFactoryParser,HTTPConfigLoader:HTTPConfigLoader,HTTPAddOn:HTTPAddOn,HMAC:HMAC,HMACAuthenticator:HMACAuthenticator,HMACParser:HMACParser,HMACConfigLoader:HMACConfigLoader,HMACAddOn:HMACAddOn,JwtAuthenticator:JwtAuthenticator,JwtConfigLoader:JwtConfigLoader,JwtAddOn:JwtAddOn,HTTPFunction:HTTPFunction,JSONHTTPFunction:JSONHTTPFunction};
//# sourceMappingURL=/sm/d3cbdaea061c746b96fd31dad0efdf766ad8c46a9ab93d44466fb32437266051.map