@crossauth/frontend 1.1.2 → 1.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var He=Object.defineProperty;var ge=r=>{throw TypeError(r)};var je=(r,e,t)=>e in r?He(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var f=(r,e,t)=>je(r,typeof e!="symbol"?e+"":e,t),pe=(r,e,t)=>e.has(r)||ge("Cannot "+t);var p=(r,e,t)=>(pe(r,e,"read from private field"),t?t.call(r):e.get(r)),R=(r,e,t)=>e.has(r)?ge("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),T=(r,e,t,o)=>(pe(r,e,"write to private field"),o?o.call(r,t):e.set(r,t),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var De=Object.defineProperty,Ce=r=>{throw TypeError(r)},Je=(r,e,t)=>e in r?De(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,u=(r,e,t)=>Je(r,typeof e!="symbol"?e+"":e,t),Se=(r,e,t)=>e.has(r)||Ce("Cannot "+t),w=(r,e,t)=>(Se(r,e,"read from private field"),e.get(r)),ye=(r,e,t)=>e.has(r)?Ce("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),te=(r,e,t,o)=>(Se(r,e,"write to private field"),e.set(r,t),t);class K{}u(K,"active","active"),u(K,"disabled","disabled"),u(K,"awaitingTwoFactorSetup","awaitingtwofactorsetup"),u(K,"awaitingTwoFactorSetupAndEmailVerification","awaitingtwofactorsetupandemailverification"),u(K,"awaitingEmailVerification","awaitingemailverification"),u(K,"passwordChangeNeeded","passwordchangeneeded"),u(K,"passwordResetNeeded","passwordresetneeded"),u(K,"factor2ResetNeeded","factor2resetneeded"),u(K,"passwordAndFactor2ResetNeeded","passwordandfactor2resetneeded");class O{}u(O,"session","s:"),u(O,"passwordResetToken","p:"),u(O,"emailVerificationToken","e:"),u(O,"apiKey","api:"),u(O,"authorizationCode","authz:"),u(O,"accessToken","access:"),u(O,"refreshToken","refresh:"),u(O,"mfaToken","omfa:"),u(O,"deviceCode","dc:"),u(O,"userCode","uc:");var m=(r=>(r[r.UserNotExist=0]="UserNotExist",r[r.PasswordInvalid=1]="PasswordInvalid",r[r.EmailNotExist=2]="EmailNotExist",r[r.UsernameOrPasswordInvalid=3]="UsernameOrPasswordInvalid",r[r.InvalidClientId=4]="InvalidClientId",r[r.ClientExists=5]="ClientExists",r[r.InvalidClientSecret=6]="InvalidClientSecret",r[r.InvalidClientIdOrSecret=7]="InvalidClientIdOrSecret",r[r.InvalidRedirectUri=8]="InvalidRedirectUri",r[r.InvalidOAuthFlow=9]="InvalidOAuthFlow",r[r.UserNotActive=10]="UserNotActive",r[r.EmailNotVerified=11]="EmailNotVerified",r[r.TwoFactorIncomplete=12]="TwoFactorIncomplete",r[r.Unauthorized=13]="Unauthorized",r[r.UnauthorizedClient=14]="UnauthorizedClient",r[r.InvalidScope=15]="InvalidScope",r[r.InsufficientScope=16]="InsufficientScope",r[r.InsufficientPriviledges=17]="InsufficientPriviledges",r[r.Forbidden=18]="Forbidden",r[r.InvalidKey=19]="InvalidKey",r[r.InvalidCsrf=20]="InvalidCsrf",r[r.InvalidSession=21]="InvalidSession",r[r.Expired=22]="Expired",r[r.Connection=23]="Connection",r[r.InvalidHash=24]="InvalidHash",r[r.UnsupportedAlgorithm=25]="UnsupportedAlgorithm",r[r.KeyExists=26]="KeyExists",r[r.PasswordChangeNeeded=27]="PasswordChangeNeeded",r[r.PasswordResetNeeded=28]="PasswordResetNeeded",r[r.Factor2ResetNeeded=29]="Factor2ResetNeeded",r[r.Configuration=30]="Configuration",r[r.InvalidEmail=31]="InvalidEmail",r[r.InvalidPhoneNumber=32]="InvalidPhoneNumber",r[r.InvalidUsername=33]="InvalidUsername",r[r.PasswordMatch=34]="PasswordMatch",r[r.InvalidToken=35]="InvalidToken",r[r.MfaRequired=36]="MfaRequired",r[r.PasswordFormat=37]="PasswordFormat",r[r.DataFormat=38]="DataFormat",r[r.FetchError=39]="FetchError",r[r.UserExists=40]="UserExists",r[r.FormEntry=41]="FormEntry",r[r.BadRequest=42]="BadRequest",r[r.AuthorizationPending=43]="AuthorizationPending",r[r.SlowDown=44]="SlowDown",r[r.ExpiredToken=45]="ExpiredToken",r[r.ConstraintViolation=46]="ConstraintViolation",r[r.NotImplemented=47]="NotImplemented",r[r.UnknownError=48]="UnknownError",r))(m||{});class g extends Error{constructor(e,t=void 0){let o,s=500;e==0?(o="User does not exist",s=401):e==1?(o="Password doesn't match",s=401):e==3?(o="Username or password incorrect",s=401):e==4?(o="Client id is invalid",s=401):e==5?(o="Client ID or name already exists",s=500):e==6?(o="Client secret is invalid",s=401):e==7?(o="Client id or secret is invalid",s=401):e==8?(o="Redirect Uri is not registered",s=401):e==9?(o="Invalid OAuth flow type",s=500):e==2?(o="No user exists with that email address",s=401):e==10?(o="Account is not active",s=403):e==33?(o="Username is not in an allowed format",s=400):e==31?(o="Email is not in an allowed format",s=400):e==32?(o="Phone number is not in an allowed format",s=400):e==11?(o="Email address has not been verified",s=403):e==12?(o="Two-factor setup is not complete",s=403):e==13?(o="Not authorized",s=401):e==14?(o="Client not authorized",s=401):e==15?(o="Invalid scope",s=403):e==16?(o="Insufficient scope",s=403):e==23?o="Connection failure":e==22?(o="Token has expired",s=401):e==24?o="Hash is not in a valid format":e==19?(o="Key is invalid",s=401):e==18?(o="You do not have permission to access this resource",s=403):e==17?(o="You do not have the right privileges to access this resource",s=401):e==20?(o="CSRF token is invalid",s=401):e==21?(o="Session cookie is invalid",s=401):e==25?o="Algorithm not supported":e==26?o="Attempt to create a key that already exists":e==27?(o="User must change password",s=403):e==28?(o="User must reset password",s=403):e==29?(o="User must reset 2FA",s=403):e==30?o="There was an error in the configuration":e==34?(o="Passwords do not match",s=401):e==35?(o="Token is not valid",s=401):e==36?(o="MFA is required",s=401):e==37?(o="Password format was incorrect",s=401):e==40?(o="User already exists",s=400):e==42?(o="The request is invalid",s=400):e==38?(o="Session data has unexpected format",s=500):e==39?(o="Couldn't execute a fetch",s=500):e==43?(o="Waiting for authorization",s=200):e==44?(o="Slow polling down by 5 seconds",s=200):e==45?(o="Token has expired",s=401):e==46?(o="Database update/insert caused a constraint violation",s=500):e==47?(o="This method has not been implemented",s=500):(o="Unknown error",s=500),t!=null&&!Array.isArray(t)?o=t:Array.isArray(t)&&(o=t.join(". ")),super(o),u(this,"isCrossauthError",!0),u(this,"httpStatus"),u(this,"code"),u(this,"codeName"),u(this,"messages"),this.code=e,this.codeName=m[e],this.httpStatus=s,this.name="CrossauthError",Array.isArray(t)?this.messages=t:this.messages=[o],Object.setPrototypeOf(this,g.prototype)}static fromOAuthError(e,t){let o;switch(e){case"invalid_request":o=42;break;case"unauthorized_client":o=14;break;case"access_denied":o=13;break;case"unsupported_response_type":o=42;break;case"invalid_scope":o=15;break;case"server_error":o=48;break;case"temporarily_unavailable":o=23;break;case"invalid_token":o=35;break;case"expired_token":o=45;break;case"insufficient_scope":o=35;break;case"mfa_required":o=36;break;case"authorization_pending":o=43;break;case"slow_down":o=44;break;default:o=48}return new g(o,t)}get oauthErrorCode(){switch(this.code){case 42:return"invalid_request";case 14:return"unauthorized_client";case 13:return"access_denied";case 15:return"invalid_scope";case 23:return"temporarily_unavailable";case 35:return"invalid_token";case 36:return"mfa_required";case 43:return"authorization_pending";case 44:return"slow_down";case 45:return"expired_token";case 22:return"expired_token";default:return"server_error"}}static asCrossauthError(e,t){if(e instanceof Error)return"isCrossauthError"in e?e:new g(48,e.message);if("errorCode"in e){let s=48;try{s=Number(e.errorCode)??48}catch{}let n=t??m[s];return"errorMessage"in e?n=e.errorMessage:"message"in e&&(n=e.message),new g(s,n)}let o=t??m[48];return"message"in e&&(o=e.message),new g(48,o)}}const L=class P{constructor(e){if(u(this,"level"),e)this.level=e;else if(typeof process<"u"&&"CROSSAUTH_LOG_LEVEL"in process.env){const t=(process.env.CROSSAUTH_LOG_LEVEL??"ERROR").toUpperCase();P.levelName.includes(t)?this.level=P.levelName.indexOf(t):this.level=P.Error}else this.level=P.Error}static get logger(){return globalThis.crossauthLogger}setLevel(e){this.level=e}log(e,t){e<=this.level&&(typeof t=="string"?console.log("Crossauth "+P.levelName[e]+" "+new Date().toISOString(),t):console.log(JSON.stringify({level:P.levelName[e],time:new Date().toISOString(),...t})))}error(e){this.log(P.Error,e)}warn(e){this.log(P.Warn,e)}info(e){this.log(P.Info,e)}debug(e){this.log(P.Debug,e)}static setLogger(e,t){globalThis.crossauthLogger=e,globalThis.crossauthLoggerAcceptsJson=t}};u(L,"None",0),u(L,"Error",1),u(L,"Warn",2),u(L,"Info",3),u(L,"Debug",4),u(L,"levelName",["NONE","ERROR","WARN","INFO","DEBUG"]);let d=L;function l(r){let e;typeof r=="object"&&"err"in r&&typeof r.err=="object"&&(e=r.err.stack);try{typeof r=="object"&&"err"in r&&typeof r.err=="object"&&r.err&&"message"in r.err&&!("msg"in r)&&(r.msg=r.err.message)}catch{}try{typeof r=="object"&&"err"in r&&typeof r.err=="object"&&(r.err={...r.err,stack:e})}catch{}try{typeof r=="object"&&"err"in r&&!("msg"in r)&&(r.msg=r.msg="An unknown error occurred")}catch{}try{typeof r=="object"&&"cerr"in r&&"isCrossauthError"in r.cerr&&r.cerr&&(r.errorCode=r.cerr.code,r.errorCodeName=r.cerr.codeName,r.httpStatus=r.cerr.httpStatus,"msg"in r||(r.msg=r.cerr.message),delete r.cerr)}catch{}return typeof r=="string"||globalThis.crossauthLoggerAcceptsJson?r:JSON.stringify(r)}globalThis.crossauthLogger=new d;globalThis.crossauthLoggerAcceptsJson=!0;const Te={issuer:"",authorization_endpoint:"",token_endpoint:"",jwks_uri:"",response_types_supported:[],subject_types_supported:[],response_modes_supported:["query","fragment"],grant_types_supported:["authorization_code","implicit"],id_token_signing_alg_values_supported:[],claim_types_supported:["normal"],claims_parameter_supported:!1,request_parameter_supported:!1,request_uri_parameter_supported:!0,require_request_uri_registration:!1},ae=crypto,Ee=r=>r instanceof CryptoKey,oe=new TextEncoder,re=new TextDecoder;function ze(...r){const e=r.reduce((s,{length:n})=>s+n,0),t=new Uint8Array(e);let o=0;for(const s of r)t.set(s,o),o+=s.length;return t}const Le=r=>{const e=atob(r),t=new Uint8Array(e.length);for(let o=0;o<e.length;o++)t[o]=e.charCodeAt(o);return t},z=r=>{let e=r;e instanceof Uint8Array&&(e=re.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return Le(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class E extends Error{constructor(e,t){var o;super(e,t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(o=Error.captureStackTrace)==null||o.call(Error,this,this.constructor)}}E.code="ERR_JOSE_GENERIC";class Fe extends E{constructor(e,t,o="unspecified",s="unspecified"){super(e,{cause:{claim:o,reason:s,payload:t}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=o,this.reason=s,this.payload=t}}Fe.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class Me extends E{constructor(e,t,o="unspecified",s="unspecified"){super(e,{cause:{claim:o,reason:s,payload:t}}),this.code="ERR_JWT_EXPIRED",this.claim=o,this.reason=s,this.payload=t}}Me.code="ERR_JWT_EXPIRED";class Be extends E{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}Be.code="ERR_JOSE_ALG_NOT_ALLOWED";class I extends E{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}I.code="ERR_JOSE_NOT_SUPPORTED";class $e extends E{constructor(e="decryption operation failed",t){super(e,t),this.code="ERR_JWE_DECRYPTION_FAILED"}}$e.code="ERR_JWE_DECRYPTION_FAILED";class qe extends E{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}qe.code="ERR_JWE_INVALID";class C extends E{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}C.code="ERR_JWS_INVALID";class x extends E{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}x.code="ERR_JWT_INVALID";class Ve extends E{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}Ve.code="ERR_JWK_INVALID";class Ge extends E{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}Ge.code="ERR_JWKS_INVALID";class Ye extends E{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_NO_MATCHING_KEY"}}Ye.code="ERR_JWKS_NO_MATCHING_KEY";class Xe extends E{constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}Xe.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class Qe extends E{constructor(e="request timed out",t){super(e,t),this.code="ERR_JWKS_TIMEOUT"}}Qe.code="ERR_JWKS_TIMEOUT";class be extends E{constructor(e="signature verification failed",t){super(e,t),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}be.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function U(r,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${r}`)}function Q(r,e){return r.name===e}function ce(r){return parseInt(r.name.slice(4),10)}function Ze(r){switch(r){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function er(r,e){if(e.length&&!e.some(t=>r.usages.includes(t))){let t="CryptoKey does not support this operation, its usages must include ";if(e.length>2){const o=e.pop();t+=`one of ${e.join(", ")}, or ${o}.`}else e.length===2?t+=`one of ${e[0]} or ${e[1]}.`:t+=`${e[0]}.`;throw new TypeError(t)}}function rr(r,e,...t){switch(e){case"HS256":case"HS384":case"HS512":{if(!Q(r.algorithm,"HMAC"))throw U("HMAC");const o=parseInt(e.slice(2),10);if(ce(r.algorithm.hash)!==o)throw U(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!Q(r.algorithm,"RSASSA-PKCS1-v1_5"))throw U("RSASSA-PKCS1-v1_5");const o=parseInt(e.slice(2),10);if(ce(r.algorithm.hash)!==o)throw U(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!Q(r.algorithm,"RSA-PSS"))throw U("RSA-PSS");const o=parseInt(e.slice(2),10);if(ce(r.algorithm.hash)!==o)throw U(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(r.algorithm.name!=="Ed25519"&&r.algorithm.name!=="Ed448")throw U("Ed25519 or Ed448");break}case"Ed25519":{if(!Q(r.algorithm,"Ed25519"))throw U("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!Q(r.algorithm,"ECDSA"))throw U("ECDSA");const o=Ze(e);if(r.algorithm.namedCurve!==o)throw U(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}er(r,t)}function Ae(r,e,...t){var o;if(t=t.filter(Boolean),t.length>2){const s=t.pop();r+=`one of type ${t.join(", ")}, or ${s}.`}else t.length===2?r+=`one of type ${t[0]} or ${t[1]}.`:r+=`of type ${t[0]}.`;return e==null?r+=` Received ${e}`:typeof e=="function"&&e.name?r+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&(o=e.constructor)!=null&&o.name&&(r+=` Received an instance of ${e.constructor.name}`),r}const we=(r,...e)=>Ae("Key must be ",r,...e);function Re(r,e,...t){return Ae(`Key for the ${r} algorithm must be `,e,...t)}const Pe=r=>Ee(r)?!0:(r==null?void 0:r[Symbol.toStringTag])==="KeyObject",ie=["CryptoKey"],tr=(...r)=>{const e=r.filter(Boolean);if(e.length===0||e.length===1)return!0;let t;for(const o of e){const s=Object.keys(o);if(!t||t.size===0){t=new Set(s);continue}for(const n of s){if(t.has(n))return!1;t.add(n)}}return!0};function or(r){return typeof r=="object"&&r!==null}function G(r){if(!or(r)||Object.prototype.toString.call(r)!=="[object Object]")return!1;if(Object.getPrototypeOf(r)===null)return!0;let e=r;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(r)===e}const sr=(r,e)=>{if(r.startsWith("RS")||r.startsWith("PS")){const{modulusLength:t}=e.algorithm;if(typeof t!="number"||t<2048)throw new TypeError(`${r} requires key modulusLength to be 2048 bits or larger`)}};function Y(r){return G(r)&&typeof r.kty=="string"}function ir(r){return r.kty!=="oct"&&typeof r.d=="string"}function nr(r){return r.kty!=="oct"&&typeof r.d>"u"}function ar(r){return Y(r)&&r.kty==="oct"&&typeof r.k=="string"}function cr(r){let e,t;switch(r.kty){case"RSA":{switch(r.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${r.alg.slice(-3)}`},t=r.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${r.alg.slice(-3)}`},t=r.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(r.alg.slice(-3),10)||1}`},t=r.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new I('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(r.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},t=r.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},t=r.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},t=r.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:r.crv},t=r.d?["deriveBits"]:[];break;default:throw new I('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(r.alg){case"Ed25519":e={name:"Ed25519"},t=r.d?["sign"]:["verify"];break;case"EdDSA":e={name:r.crv},t=r.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:r.crv},t=r.d?["deriveBits"]:[];break;default:throw new I('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new I('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:t}}const Ie=async r=>{if(!r.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:e,keyUsages:t}=cr(r),o=[e,r.ext??!1,r.key_ops??t],s={...r};return delete s.alg,delete s.use,ae.subtle.importKey("jwk",s,...o)},Oe=r=>z(r);let F,M;const Ue=r=>(r==null?void 0:r[Symbol.toStringTag])==="KeyObject",ne=async(r,e,t,o,s=!1)=>{let n=r.get(e);if(n!=null&&n[o])return n[o];const i=await Ie({...t,alg:o});return s&&Object.freeze(e),n?n[o]=i:r.set(e,{[o]:i}),i},dr=(r,e)=>{if(Ue(r)){let t=r.export({format:"jwk"});return delete t.d,delete t.dp,delete t.dq,delete t.p,delete t.q,delete t.qi,t.k?Oe(t.k):(M||(M=new WeakMap),ne(M,r,t,e))}return Y(r)?r.k?z(r.k):(M||(M=new WeakMap),ne(M,r,r,e,!0)):r},lr=(r,e)=>{if(Ue(r)){let t=r.export({format:"jwk"});return t.k?Oe(t.k):(F||(F=new WeakMap),ne(F,r,t,e))}return Y(r)?r.k?z(r.k):(F||(F=new WeakMap),ne(F,r,r,e,!0)):r},hr={normalizePublicKey:dr,normalizePrivateKey:lr},H=(r,e,t=0)=>{t===0&&(e.unshift(e.length),e.unshift(6));const o=r.indexOf(e[0],t);if(o===-1)return!1;const s=r.subarray(o,o+e.length);return s.length!==e.length?!1:s.every((n,i)=>n===e[i])||H(r,e,o+1)},me=r=>{switch(!0){case H(r,[42,134,72,206,61,3,1,7]):return"P-256";case H(r,[43,129,4,0,34]):return"P-384";case H(r,[43,129,4,0,35]):return"P-521";case H(r,[43,101,110]):return"X25519";case H(r,[43,101,111]):return"X448";case H(r,[43,101,112]):return"Ed25519";case H(r,[43,101,113]):return"Ed448";default:throw new I("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},Ne=async(r,e,t,o,s)=>{let n,i;const a=new Uint8Array(atob(t.replace(r,"")).split("").map(h=>h.charCodeAt(0))),c=e==="spki";switch(o){case"PS256":case"PS384":case"PS512":n={name:"RSA-PSS",hash:`SHA-${o.slice(-3)}`},i=c?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":n={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${o.slice(-3)}`},i=c?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":n={name:"RSA-OAEP",hash:`SHA-${parseInt(o.slice(-3),10)||1}`},i=c?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":n={name:"ECDSA",namedCurve:"P-256"},i=c?["verify"]:["sign"];break;case"ES384":n={name:"ECDSA",namedCurve:"P-384"},i=c?["verify"]:["sign"];break;case"ES512":n={name:"ECDSA",namedCurve:"P-521"},i=c?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{const h=me(a);n=h.startsWith("P-")?{name:"ECDH",namedCurve:h}:{name:h},i=c?[]:["deriveBits"];break}case"Ed25519":n={name:"Ed25519"},i=c?["verify"]:["sign"];break;case"EdDSA":n={name:me(a)},i=c?["verify"]:["sign"];break;default:throw new I('Invalid or unsupported "alg" (Algorithm) value')}return ae.subtle.importKey(e,a,n,!1,i)},ur=(r,e,t)=>Ne(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",r,e),fr=(r,e,t)=>Ne(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",r,e);async function gr(r,e,t){if(typeof r!="string"||r.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return fr(r,e)}async function pr(r,e,t){if(typeof r!="string"||r.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return ur(r,e)}async function le(r,e){if(!G(r))throw new TypeError("JWK must be an object");switch(e||(e=r.alg),r.kty){case"oct":if(typeof r.k!="string"||!r.k)throw new TypeError('missing "k" (Key Value) Parameter value');return z(r.k);case"RSA":if("oth"in r&&r.oth!==void 0)throw new I('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return Ie({...r,alg:e});default:throw new I('Unsupported "kty" (Key Type) Parameter value')}}const B=r=>r==null?void 0:r[Symbol.toStringTag],he=(r,e,t)=>{var o,s;if(e.use!==void 0&&e.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(e.key_ops!==void 0&&((s=(o=e.key_ops).includes)==null?void 0:s.call(o,t))!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${t}`);if(e.alg!==void 0&&e.alg!==r)throw new TypeError(`Invalid key for this operation, when present its alg must be ${r}`);return!0},yr=(r,e,t,o)=>{if(!(e instanceof Uint8Array)){if(o&&Y(e)){if(ar(e)&&he(r,e,t))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!Pe(e))throw new TypeError(Re(r,e,...ie,"Uint8Array",o?"JSON Web Key":null));if(e.type!=="secret")throw new TypeError(`${B(e)} instances for symmetric algorithms must be of type "secret"`)}},wr=(r,e,t,o)=>{if(o&&Y(e))switch(t){case"sign":if(ir(e)&&he(r,e,t))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(nr(e)&&he(r,e,t))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Pe(e))throw new TypeError(Re(r,e,...ie,o?"JSON Web Key":null));if(e.type==="secret")throw new TypeError(`${B(e)} instances for asymmetric algorithms must not be of type "secret"`);if(t==="sign"&&e.type==="public")throw new TypeError(`${B(e)} instances for asymmetric algorithm signing must be of type "private"`);if(t==="decrypt"&&e.type==="public")throw new TypeError(`${B(e)} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&t==="verify"&&e.type==="private")throw new TypeError(`${B(e)} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&t==="encrypt"&&e.type==="private")throw new TypeError(`${B(e)} instances for asymmetric algorithm encryption must be of type "public"`)};function Ke(r,e,t,o){e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?yr(e,t,o,r):wr(e,t,o,r)}Ke.bind(void 0,!1);const ve=Ke.bind(void 0,!0);function mr(r,e,t,o,s){if(s.crit!==void 0&&(o==null?void 0:o.crit)===void 0)throw new r('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||o.crit===void 0)return new Set;if(!Array.isArray(o.crit)||o.crit.length===0||o.crit.some(i=>typeof i!="string"||i.length===0))throw new r('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let n;n=e;for(const i of o.crit){if(!n.has(i))throw new I(`Extension Header Parameter "${i}" is not recognized`);if(s[i]===void 0)throw new r(`Extension Header Parameter "${i}" is missing`);if(n.get(i)&&o[i]===void 0)throw new r(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(o.crit)}function vr(r,e){const t=`SHA-${r.slice(-3)}`;switch(r){case"HS256":case"HS384":case"HS512":return{hash:t,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:t,name:"RSA-PSS",saltLength:r.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:t,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:t,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:e.name};default:throw new I(`alg ${r} is not supported either by JOSE or your javascript runtime`)}}async function _r(r,e,t){if(e=await hr.normalizePublicKey(e,r),Ee(e))return rr(e,r,t),e;if(e instanceof Uint8Array){if(!r.startsWith("HS"))throw new TypeError(we(e,...ie));return ae.subtle.importKey("raw",e,{hash:`SHA-${r.slice(-3)}`,name:"HMAC"},!1,[t])}throw new TypeError(we(e,...ie,"Uint8Array","JSON Web Key"))}const kr=async(r,e,t,o)=>{const s=await _r(r,e,"verify");sr(r,s);const n=vr(r,s.algorithm);try{return await ae.subtle.verify(n,s,t,o)}catch{return!1}};async function Cr(r,e,t){if(!G(r))throw new C("Flattened JWS must be an object");if(r.protected===void 0&&r.header===void 0)throw new C('Flattened JWS must have either of the "protected" or "header" members');if(r.protected!==void 0&&typeof r.protected!="string")throw new C("JWS Protected Header incorrect type");if(r.payload===void 0)throw new C("JWS Payload missing");if(typeof r.signature!="string")throw new C("JWS Signature missing or incorrect type");if(r.header!==void 0&&!G(r.header))throw new C("JWS Unprotected Header incorrect type");let o={};if(r.protected)try{const X=z(r.protected);o=JSON.parse(re.decode(X))}catch{throw new C("JWS Protected Header is invalid")}if(!tr(o,r.header))throw new C("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const s={...o,...r.header},n=mr(C,new Map([["b64",!0]]),void 0,o,s);let i=!0;if(n.has("b64")&&(i=o.b64,typeof i!="boolean"))throw new C('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=s;if(typeof a!="string"||!a)throw new C('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(i){if(typeof r.payload!="string")throw new C("JWS Payload must be a string")}else if(typeof r.payload!="string"&&!(r.payload instanceof Uint8Array))throw new C("JWS Payload must be a string or an Uint8Array instance");let c=!1;typeof e=="function"?(e=await e(o,r),c=!0,ve(a,e,"verify"),Y(e)&&(e=await le(e,a))):ve(a,e,"verify");const h=ze(oe.encode(r.protected??""),oe.encode("."),typeof r.payload=="string"?oe.encode(r.payload):r.payload);let y;try{y=z(r.signature)}catch{throw new C("Failed to base64url decode the signature")}if(!await kr(a,e,y,h))throw new be;let _;if(i)try{_=z(r.payload)}catch{throw new C("Failed to base64url decode the payload")}else typeof r.payload=="string"?_=oe.encode(r.payload):_=r.payload;const b={payload:_};return r.protected!==void 0&&(b.protectedHeader=o),r.header!==void 0&&(b.unprotectedHeader=r.header),c?{...b,key:e}:b}async function Sr(r,e,t){if(r instanceof Uint8Array&&(r=re.decode(r)),typeof r!="string")throw new C("Compact JWS must be a string or Uint8Array");const{0:o,1:s,2:n,length:i}=r.split(".");if(i!==3)throw new C("Invalid Compact JWS");const a=await Cr({payload:s,protected:o,signature:n},e),c={payload:a.payload,protectedHeader:a.protectedHeader};return typeof e=="function"?{...c,key:a.key}:c}const We=z;function _e(r){let e;if(typeof r=="string"){const t=r.split(".");(t.length===3||t.length===5)&&([e]=t)}else if(typeof r=="object"&&r)if("protected"in r)e=r.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof e!="string"||!e)throw new Error;const t=JSON.parse(re.decode(We(e)));if(!G(t))throw new Error;return t}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}function Tr(r){if(typeof r!="string")throw new x("JWTs must use Compact JWS serialization, JWT must be a string");const{1:e,length:t}=r.split(".");if(t===5)throw new x("Only JWTs using Compact JWS serialization can be decoded");if(t!==3)throw new x("Invalid JWT");if(!e)throw new x("JWTs must contain a payload");let o;try{o=We(e)}catch{throw new x("Failed to base64url decode the payload")}let s;try{s=JSON.parse(re.decode(o))}catch{throw new x("Failed to parse the decoded payload as JSON")}if(!G(s))throw new x("Invalid JWT Claims Set");return s}const k=class v{static flowNames(e){let t={};return e.forEach(o=>{o in v.flowName&&(t[o]=v.flowName[o])}),t}static isValidFlow(e){return v.allFlows().includes(e)}static areAllValidFlows(e){let t=!0;return e.forEach(o=>{v.isValidFlow(o)||(t=!1)}),t}static allFlows(){return[v.AuthorizationCode,v.AuthorizationCodeWithPKCE,v.ClientCredentials,v.RefreshToken,v.DeviceCode,v.Password,v.PasswordMfa,v.OidcAuthorizationCode]}static grantType(e){switch(e){case v.AuthorizationCode:case v.AuthorizationCodeWithPKCE:case v.OidcAuthorizationCode:return["authorization_code"];case v.ClientCredentials:return["client_credentials"];case v.RefreshToken:return["refresh_token"];case v.Password:return["password"];case v.PasswordMfa:return["http://auth0.com/oauth/grant-type/mfa-otp","http://auth0.com/oauth/grant-type/mfa-oob"];case v.DeviceCode:return["urn:ietf:params:oauth:grant-type:device_code"]}}};u(k,"All","all"),u(k,"AuthorizationCode","authorizationCode"),u(k,"AuthorizationCodeWithPKCE","authorizationCodeWithPKCE"),u(k,"ClientCredentials","clientCredentials"),u(k,"RefreshToken","refreshToken"),u(k,"DeviceCode","deviceCode"),u(k,"Password","password"),u(k,"PasswordMfa","passwordMfa"),u(k,"OidcAuthorizationCode","oidcAuthorizationCode"),u(k,"flowName",{[k.AuthorizationCode]:"Authorization Code",[k.AuthorizationCodeWithPKCE]:"Authorization Code with PKCE",[k.ClientCredentials]:"Client Credentials",[k.RefreshToken]:"Refresh Token",[k.DeviceCode]:"Device Code",[k.Password]:"Password",[k.PasswordMfa]:"Password MFA",[k.OidcAuthorizationCode]:"OIDC Authorization Code"});var S,A;class Er{constructor({authServerBaseUrl:e,client_id:t,client_secret:o,redirect_uri:s,codeChallengeMethod:n,stateLength:i,verifierLength:a,tokenConsumer:c,authServerCredentials:h,authServerMode:y,authServerHeaders:_}){u(this,"authServerBaseUrl",""),ye(this,S),ye(this,A),u(this,"codeChallengeMethod","S256"),u(this,"verifierLength",32),u(this,"redirect_uri"),u(this,"stateLength",32),u(this,"authzCode",""),u(this,"oidcConfig"),u(this,"tokenConsumer"),u(this,"authServerHeaders",{}),u(this,"authServerMode"),u(this,"authServerCredentials"),u(this,"oauthPostType","json"),u(this,"oauthLogFetch",!1),u(this,"oauthUseUserInfoEndpoint",!1),u(this,"oauthAuthorizeRedirect"),this.tokenConsumer=c,this.authServerBaseUrl=e,a&&(this.verifierLength=a),i&&(this.stateLength=i),t&&te(this,S,t),o&&te(this,A,o),s&&(this.redirect_uri=s),n&&(this.codeChallengeMethod=n),this.authServerBaseUrl=e,h&&(this.authServerCredentials=h),y&&(this.authServerMode=y),_&&(this.authServerHeaders=_)}set client_id(e){te(this,S,e)}set client_secret(e){te(this,A,e)}async loadConfig(e){if(e){d.logger.debug(l({msg:"Reading OIDC config locally"})),this.oidcConfig=e;return}let t;try{const o=new URL(this.authServerBaseUrl+"/.well-known/openid-configuration");d.logger.debug(l({msg:`Fetching OIDC config from ${o}`}));let s={headers:this.authServerHeaders};this.authServerMode&&(s.mode=this.authServerMode),this.authServerCredentials&&(s.credentials=this.authServerCredentials),t=await fetch(o,s)}catch(o){d.logger.error(l({err:o}))}if(!t||!t.ok)throw new g(m.Connection,"Couldn't get OIDC configuration from URL"+this.authServerBaseUrl+"/.well-known/openid-configuration");this.oidcConfig={...Te};try{const o=await t.json();for(const[s,n]of Object.entries(o))this.oidcConfig[s]=n}catch{throw new g(m.Connection,"Unrecognized response from OIDC configuration endpoint")}}getOidcConfig(){return this.oidcConfig}async startAuthorizationCodeFlow(e,t,o,s=!1){var n,i,a;if(d.logger.debug(l({msg:"Starting authorization code flow"})),this.oidcConfig||await this.loadConfig(),!((n=this.oidcConfig)!=null&&n.response_types_supported.includes("code"))||!((i=this.oidcConfig)!=null&&i.response_modes_supported.includes("query")))return{error:"invalid_request",error_description:"Server does not support authorization code flow"};if(!((a=this.oidcConfig)!=null&&a.authorization_endpoint))return{error:"server_error",error_description:"Cannot get authorize endpoint"};if(!w(this,S))return{error:"invalid_request",error_description:"Cannot make authorization code flow without client id"};if(!this.redirect_uri)return{error:"invalid_request",error_description:"Cannot make authorization code flow without Redirect Uri"};let c=this.oidcConfig.authorization_endpoint;this.oauthAuthorizeRedirect&&(c=this.oauthAuthorizeRedirect);let h=c+"?response_type=code&client_id="+encodeURIComponent(w(this,S))+"&state="+encodeURIComponent(e)+"&redirect_uri="+encodeURIComponent(this.redirect_uri);return t&&(h+="&scope="+encodeURIComponent(t)),s&&o&&(h+="&code_challenge="+o),{url:h}}async codeChallengeAndVerifier(){const e=this.randomValue(this.verifierLength);return{codeChallenge:this.codeChallengeMethod=="plain"?e:await this.sha256(e),codeVerifier:e}}async getIdPayload(e,t){let o,s;try{let n;if(n=await this.validateIdToken(e),!n)return o="access_denied",s="Invalid ID token received",{error:o,error_description:s};if(t&&this.oauthUseUserInfoEndpoint){const i=await this.userInfoEndpoint(t);if(i.error)return o=i.error,s="Failed getting user info: "+(i.error_description??"unknown error"),{error:o,error_description:s};n={...n,...i}}return{payload:n}}catch(n){const i=g.asCrossauthError(n);return d.logger.debug(l({err:i})),d.logger.error(l({msg:"Couldn't get user info",cerr:i})),o=i.oauthErrorCode,s="Couldn't get user info: "+i.message,{error:o,error_description:s}}}async getAccessPayload(e,t){let o,s;try{let n;return n=await this.validateAccessToken(e,t),n?{payload:n}:(o="access_denied",s="Invalid access token received",{error:o,error_description:s})}catch(n){const i=g.asCrossauthError(n);return d.logger.debug(l({err:i})),d.logger.error(l({msg:"Couldn't get user info",cerr:i})),o=i.oauthErrorCode,s="Couldn't get user info: "+i.message,{error:o,error_description:s}}}async redirectEndpoint(e,t,o,s,n){var i,a;if(this.oidcConfig||await this.loadConfig(),s||!e)return s||(s="server_error"),n||(n="Unknown error"),{error:s,error_description:n};if(this.authzCode=e,!((i=this.oidcConfig)!=null&&i.grant_types_supported.includes("authorization_code")))return{error:"invalid_request",error_description:"Server does not support authorization code grant"};if(!((a=this.oidcConfig)!=null&&a.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const c=this.oidcConfig.token_endpoint;let h,y;h="authorization_code",y=w(this,A);let _={grant_type:h,client_id:w(this,S),code:this.authzCode,redirect_uri:this.redirect_uri};t&&(_.scope=t),y&&(_.client_secret=y),o&&(_.code_verifier=o);try{let b=await this.post(c,_,this.authServerHeaders);if(b.id_token){const X=await this.getIdPayload(b.id_token,b.access_token);if(X.error)return X;b.id_payload=X.payload}return b}catch(b){return d.logger.error(l({err:b})),{error:"server_error",error_description:"Unable to get access token from server"}}}async clientCredentialsFlow(e){var t,o;if(d.logger.debug(l({msg:"Starting client credentials flow"})),this.oidcConfig||await this.loadConfig(),!((t=this.oidcConfig)!=null&&t.grant_types_supported.includes("client_credentials")))return{error:"invalid_request",error_description:"Server does not support client credentials grant"};if(!((o=this.oidcConfig)!=null&&o.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};if(!w(this,S))return{error:"invalid_request",error_description:"Cannot make client credentials flow without client id"};const s=this.oidcConfig.token_endpoint;let n={grant_type:"client_credentials",client_id:w(this,S),client_secret:w(this,A)};e&&(n.scope=e);try{let i=await this.post(s,n,this.authServerHeaders);if(i.id_token){const a=await this.getIdPayload(i.id_token,i.access_token);if(a.error)return a;i.id_payload=a.payload}return i}catch(i){return d.logger.error(l({err:i})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async passwordFlow(e,t,o){var s,n;if(d.logger.debug(l({msg:"Starting password flow"})),this.oidcConfig||await this.loadConfig(),!((s=this.oidcConfig)!=null&&s.grant_types_supported.includes("password")))return{error:"invalid_request",error_description:"Server does not support password grant"};if(!((n=this.oidcConfig)!=null&&n.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const i=this.oidcConfig.token_endpoint;let a={grant_type:"password",client_id:w(this,S),client_secret:w(this,A),username:e,password:t};o&&(a.scope=o);try{let c=await this.post(i,a,this.authServerHeaders);if(c.id_token){const h=await this.getIdPayload(c.id_token,c.access_token);if(h.error)return h;c.id_payload=h.payload}return c}catch(c){return d.logger.error(l({err:c})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async mfaAuthenticators(e){var t,o,s;if(d.logger.debug(l({msg:"Getting valid MFA authenticators"})),this.oidcConfig||await this.loadConfig(),!((t=this.oidcConfig)!=null&&t.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp"))&&(o=this.oidcConfig)!=null&&o.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-oob"))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((s=this.oidcConfig)!=null&&s.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const n=this.oidcConfig.issuer+(this.oidcConfig.issuer.endsWith("/")?"":"/")+"mfa/authenticators",i=await this.get(n,{authorization:"Bearer "+e,...this.authServerHeaders});if(!Array.isArray(i))return{error:"server_error",error_description:"Expected array of authenticators in mfa/authenticators response"};let a=[];for(let c=0;c<i.length;++c){const h=i[c];if(!h.id||!h.authenticator_type||!h.active)return{error:"server_error",error_description:"Invalid mfa/authenticators response"};a.push({id:h.id,authenticator_type:h.authenticator_type,active:h.active,name:h.name,oob_channel:h.oob_channel})}return{authenticators:a}}async mfaOtpRequest(e,t){var o,s;if(d.logger.debug(l({msg:"Making MFA OTB request"})),this.oidcConfig||await this.loadConfig(),!((o=this.oidcConfig)!=null&&o.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((s=this.oidcConfig)!=null&&s.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const n=this.oidcConfig.issuer+(this.oidcConfig.issuer.endsWith("/")?"":"/")+"mfa/challenge",i=await this.post(n,{client_id:w(this,S),client_secret:w(this,A),challenge_type:"otp",mfa_token:e,authenticator_id:t},this.authServerHeaders);return i.challenge_type!="otp"?{error:i.error??"server_error",error_description:i.error_description??"Invalid OTP challenge response"}:i}async mfaOtpComplete(e,t,o){var s,n;if(d.logger.debug(l({msg:"Completing MFA OTP request"})),this.oidcConfig||await this.loadConfig(),!((s=this.oidcConfig)!=null&&s.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((n=this.oidcConfig)!=null&&n.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const i=this.oidcConfig.token_endpoint,a=await this.post(i,{grant_type:"http://auth0.com/oauth/grant-type/mfa-otp",client_id:w(this,S),client_secret:w(this,A),challenge_type:"otp",mfa_token:e,otp:t,scope:o},this.authServerHeaders);if(a.id_token){const c=await this.getIdPayload(a.id_token,a.access_token);if(c.error)return c;a.id_payload=c.payload}return{id_token:a.id_token,access_token:a.access_token,refresh_token:a.refresh_token,expires_in:Number(a.expires_in),scope:a.scope,token_type:a.token_type,error:a.error,error_description:a.error_description}}async mfaOobRequest(e,t){var o,s;if(d.logger.debug(l({msg:"Making MFA OOB request"})),this.oidcConfig||await this.loadConfig(),!((o=this.oidcConfig)!=null&&o.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((s=this.oidcConfig)!=null&&s.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const n=this.oidcConfig.issuer+(this.oidcConfig.issuer.endsWith("/")?"":"/")+"mfa/challenge",i=await this.post(n,{client_id:w(this,S),client_secret:w(this,A),challenge_type:"oob",mfa_token:e,authenticator_id:t},this.authServerHeaders);return i.challenge_type!="oob"||!i.oob_code||!i.binding_method?{error:i.error??"server_error",error_description:i.error_description??"Invalid OOB challenge response"}:{challenge_type:i.challenge_type,oob_code:i.oob_code,binding_method:i.binding_method,error:i.error,error_description:i.error_description}}async mfaOobComplete(e,t,o,s){var n,i;if(d.logger.debug(l({msg:"Completing MFA OOB request"})),this.oidcConfig||await this.loadConfig(),!((n=this.oidcConfig)!=null&&n.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-oob")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((i=this.oidcConfig)!=null&&i.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const a=this.oidcConfig.token_endpoint,c=await this.post(a,{grant_type:"http://auth0.com/oauth/grant-type/mfa-oob",client_id:w(this,S),client_secret:w(this,A),challenge_type:"otp",mfa_token:e,oob_code:t,binding_code:o,scope:s},this.authServerHeaders);if(c.error)return{error:c.error,error_description:c.error_description};if(c.id_token){const h=await this.getIdPayload(c.id_token,c.access_token);if(h.error)return h;c.id_payload=h.payload}return{id_token:c.id_token,access_token:c.access_token,refresh_token:c.refresh_token,expires_in:"expires_in"in c?Number(c.expires_in):void 0,scope:c.scope,token_type:c.token_type}}async refreshTokenFlow(e){var t,o;if(d.logger.debug(l({msg:"Starting refresh token flow"})),this.oidcConfig||await this.loadConfig(),!((t=this.oidcConfig)!=null&&t.grant_types_supported.includes("refresh_token")))return{error:"invalid_request",error_description:"Server does not support refresh_token grant"};if(!((o=this.oidcConfig)!=null&&o.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const s=this.oidcConfig.token_endpoint;let n;n=w(this,A);let i={grant_type:"refresh_token",refresh_token:e,client_id:w(this,S)};n&&(i.client_secret=n);try{let a=await this.post(s,i,this.authServerHeaders);if(a.id_token){const c=await this.getIdPayload(a.id_token,a.access_token);if(c.error)return c;a.id_payload=c.payload}return a}catch(a){return d.logger.error(l({err:a})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async startDeviceCodeFlow(e,t){var o;if(d.logger.debug(l({msg:"Starting device code flow"})),this.oidcConfig||await this.loadConfig(),!((o=this.oidcConfig)!=null&&o.grant_types_supported.includes("urn:ietf:params:oauth:grant-type:device_code")))return{error:"invalid_request",error_description:"Server does not support device code grant"};let s={grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:w(this,S),client_secret:w(this,A)};t&&(s.scope=t);try{let n=await this.post(e,s,this.authServerHeaders);return n.id_token&&!await this.validateIdToken(n.id_token)?{error:"access_denied",error_description:"Invalid ID token"}:n}catch(n){return d.logger.error(l({err:n})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async pollDeviceCodeFlow(e){var t,o,s;if(d.logger.debug(l({msg:"Starting device code flow"})),this.oidcConfig||await this.loadConfig(),!((t=this.oidcConfig)!=null&&t.grant_types_supported.includes("urn:ietf:params:oauth:grant-type:device_code")))return{error:"invalid_request",error_description:"Server does not support device code grant"};if(!((o=this.oidcConfig)!=null&&o.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};let n={grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:w(this,S),client_secret:w(this,A),device_code:e};try{const i=await this.post((s=this.oidcConfig)==null?void 0:s.token_endpoint,n,this.authServerHeaders);if(i.error)return i;if(i.id_token){const a=await this.getIdPayload(i.id_token,i.access_token);if(a.error)return a;i.id_payload=a.payload}return i}catch(i){return d.logger.error(l({err:i})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async userInfoEndpoint(e){var t;if(!((t=this.oidcConfig)!=null&&t.userinfo_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const o=this.oidcConfig.userinfo_endpoint;return await this.post(o,{},{authorization:"Bearer "+e})}async post(e,t,o={}){d.logger.debug(l({msg:"Fetch POST",url:e,params:Object.keys(t)}));let s={};this.authServerCredentials&&(s.credentials=this.authServerCredentials),this.authServerMode&&(s.mode=this.authServerMode);let n="",i="";if(this.oauthPostType=="json")n=JSON.stringify(t),i="application/json";else{n="";for(let c in t)n!=""&&(n+="&"),n+=encodeURIComponent(c)+"="+encodeURIComponent(t[c]);i="application/x-www-form-urlencoded"}this.oauthLogFetch&&d.logger.debug(l({msg:"OAuth fetch",method:"POST",url:e,body:n}));const a=await(await fetch(e,{method:"POST",...s,headers:{Accept:"application/json","Content-Type":i,...o},body:n})).json();return this.oauthLogFetch&&d.logger.debug(l({msg:"OAuth fetch response",body:JSON.stringify(a)})),a}async get(e,t={}){d.logger.debug(l({msg:"Fetch GET",url:e}));let o={};this.authServerCredentials&&(o.credentials=this.authServerCredentials),this.authServerMode&&(o.mode=this.authServerMode),this.oauthLogFetch&&d.logger.debug(l({msg:"OAuth fetch",method:"GET",url:e}));const s=await(await fetch(e,{method:"GET",...o,headers:{Accept:"application/json",...t}})).json();return this.oauthLogFetch&&d.logger.debug(l({msg:"OAuth fetch response",body:JSON.stringify(s)})),s}async validateIdToken(e){try{return await this.tokenConsumer.tokenAuthorized(e,"id")}catch{return}}async validateAccessToken(e,t){try{return await this.tokenConsumer.tokenAuthorized(e,"access",t)}catch{return}}async idTokenAuthorized(e,t){try{return await this.tokenConsumer.tokenAuthorized(e,"id",t)}catch(o){d.logger.warn(l({err:o}));return}}getTokenPayload(e){return Tr(e)}}S=new WeakMap,A=new WeakMap;class br{constructor(e,t={}){if(u(this,"audience"),u(this,"jwtKeyType"),u(this,"jwtSecretKey"),u(this,"jwtPublicKey"),u(this,"clockTolerance",10),u(this,"authServerBaseUrl",""),u(this,"oidcConfig"),u(this,"keys",{}),this.audience=e,t.authServerBaseUrl&&(this.authServerBaseUrl=t.authServerBaseUrl),t.jwtKeyType&&(this.jwtKeyType=t.jwtKeyType),t.jwtSecretKey&&(this.jwtSecretKey=t.jwtSecretKey),t.jwtPublicKey&&(this.jwtPublicKey=t.jwtPublicKey),t.clockTolerance&&(this.clockTolerance=t.clockTolerance),t.oidcConfig&&(this.oidcConfig=t.oidcConfig),this.jwtPublicKey&&!this.jwtKeyType)throw new g(m.Configuration,"If specifying jwtPublic key, must also specify jwtKeyType")}async loadKeys(e){try{if(this.jwtSecretKey){if(!this.jwtKeyType)throw new g(m.Configuration,"Must specify jwtKeyType if setting jwtSecretKey");this.keys._default=await pr(this.jwtSecretKey,this.jwtKeyType)}else if(this.jwtPublicKey){if(!this.jwtKeyType)throw new g(m.Configuration,"Must specify jwtKeyType if setting jwtPublicKey");const t=await gr(this.jwtPublicKey,this.jwtKeyType);this.keys._default=t}else{if(this.oidcConfig||await this.loadConfig(),!this.oidcConfig)throw new g(m.Connection,"Load OIDC config before Jwks");await this.loadJwks(void 0,e)}}catch(t){throw d.logger.debug(l({err:t})),new g(m.Connection,"Couldn't load keys")}}async loadConfig(e){if(e){this.oidcConfig=e;return}if(!this.authServerBaseUrl)throw new g(m.Connection,"Couldn't get OIDC configuration. Either set authServerBaseUrl or set config manually");let t;try{let o=this.authServerBaseUrl;o.endsWith("/")||(o+="/"),t=await fetch(new URL(".well-known/openid-configuration",o))}catch(o){d.logger.error(l({err:o}))}if(!t||!t.ok)throw new g(m.Connection,"Couldn't get OIDC configuration");this.oidcConfig={...Te};try{const o=await t.json();for(const[s,n]of Object.entries(o))this.oidcConfig[s]=n}catch{throw new g(m.Connection,"Unrecognized response from OIDC configuration endpoint")}}async loadJwks(e,t){if(e){this.keys={};for(let o=0;o<e.keys.length;++o){const s=e.keys[o],n="kid"in s&&s.kid?s.kid:"_default";this.keys[n]=await le(e.keys[o])}}else{if(!this.oidcConfig)throw new g(m.Connection,"Load OIDC config before Jwks");let o;try{o=await fetch(new URL(this.oidcConfig.jwks_uri))}catch(s){d.logger.error(l({err:s}))}if(!o||!o.ok)throw new g(m.Connection,"Couldn't get OIDC configuration");this.keys={};try{const s=await o.json();if(!("keys"in s)||!Array.isArray(s.keys))throw new g(m.Connection,"Couldn't fetch keys");for(let n=0;n<s.keys.length;++n)try{let i="_default",a={...s.keys[n]};if("kid"in a&&typeof a.kid=="string"&&(i=String(a.kid)),a&&!a.alg&&!a.jwk_alg&&t)if(t.startsWith("RS")&&a.kty=="RSA")a.alg=t;else{d.logger.debug(l({msg:"Skipping key with "+a.kty}));continue}const c=await le(a);this.keys[i]=c}catch(i){throw d.logger.error(l({err:i})),new g(m.Connection,"Couldn't load keys")}}catch(s){throw d.logger.error(l({err:s})),new g(m.Connection,"Unrecognized response from OIDC jwks endpoint")}}}async tokenAuthorized(e,t,o){if(!this.keys||Object.keys(this.keys).length==0){const n=_e(e);await this.loadKeys(n.alg)}const s=await this.validateToken(e);if(s){if(s.iss!=this.authServerBaseUrl){const n=s.jti?s.jti:s.sid?s.sid:"";d.logger.error(l({msg:`Invalid issuer ${s.iss} ${t} token`,hashedAccessToken:await this.hash(n)}));return}if(o!=!1&&s.aud){const n=s.jti?s.jti:s.sid?s.sid:"";if(Array.isArray(s.aud)&&!s.aud.includes(this.audience)||!Array.isArray(s.aud)&&s.aud!=this.audience){d.logger.error(l({msg:`Invalid audience ${s.aud} in ${t} token`,hashedAccessToken:await this.hash(n)}));return}}return s}}async validateToken(e){(!this.keys||Object.keys(this.keys).length==0)&&d.logger.warn("No keys loaded so cannot validate tokens");let t;try{t=_e(e).kid}catch{d.logger.warn(l({msg:"Invalid access token format"}));return}let o;for(let s in this.keys)if(t==s){o=this.keys[s];break}if(!o&&"_default"in this.keys&&(o=this.keys._default),!o){d.logger.warn(l({msg:"No matching keys found for access token"}));return}try{const{payload:s}=await Sr(e,o),n=JSON.parse(new TextDecoder().decode(s));if(n.exp*1e3<Date.now()+this.clockTolerance){d.logger.warn(l({msg:"Access token has expired"}));return}return n}catch(s){const n=g.asCrossauthError(s);d.logger.debug(l({err:n})),d.logger.warn(l({msg:"Access token did not validate",cerr:n}));return}}}const ke=30,se=2,de=30;class ue{constructor(e){f(this,"autoRefreshUrl","/autorefresh");f(this,"csrfHeader","X-CROSSAUTH-CSRF");f(this,"headers",{});f(this,"autoRefreshActive",!1);f(this,"mode","cors");f(this,"credentials","same-origin");f(this,"tokenProvider");this.tokenProvider=e.tokenProvider,this.autoRefreshUrl=e.autoRefreshUrl,e.csrfHeader&&(this.csrfHeader=e.csrfHeader),e.headers&&(this.headers=e.headers),e.mode&&(this.mode=e.mode),e.credentials&&(this.credentials=e.credentials)}async startAutoRefresh(e=["access","id"],t){if(!this.autoRefreshActive){this.autoRefreshActive=!0,d.logger.debug(l({msg:"Starting auto refresh"}));try{await this.scheduleAutoRefresh(e,t)}catch(o){const s=g.asCrossauthError(o);d.logger.error(l({cerr:s})),d.logger.debug(l({err:s}))}}}stopAutoRefresh(){this.autoRefreshActive=!1,d.logger.debug(l({msg:"Stopping auto refresh"}))}async scheduleAutoRefresh(e,t){let o;const s=this.tokenProvider.getCsrfToken(),n=s?await s:void 0,i=await this.tokenProvider.getTokenExpiries([...e,"refresh"],n);if(i.refresh==null){d.logger.debug(l({msg:"No refresh token found"}));return}const a=Date.now();let c=i.id;if((!c||i.access&&i.access<c)&&(c=i.access),!c){d.logger.debug(l({msg:"No tokens expire"}));return}let h=c*1e3-a-ke;if(h<0&&o!=null&&o<=0){d.logger.debug(l({msg:"Expiry time has passed"}));return}if(h<0&&(h=0),i.refresh&&i.refresh-ke<h){d.logger.debug(l({msg:"Refresh token has expired"}));return}let y=_=>new Promise(b=>setTimeout(b,_));d.logger.debug(l({msg:`Waiting ${h} before refreshing tokens`})),o=h,await y(h),await this.autoRefresh(e,n,t)}async autoRefresh(e,t,o){if(this.autoRefreshActive){let s,n=!1,i=0;for(;!n&&i<=se;)try{let a={...this.headers};t&&(a[this.csrfHeader]=t),d.logger.debug(l({msg:"Initiating auto refresh"}));const c=await this.tokenProvider.jsonFetchWithToken(this.autoRefreshUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...a},mode:this.mode,credentials:this.credentials,body:{csrfToken:t}},"refresh");c.ok||d.logger.error(l({msg:"Failed auto refreshing tokens",status:c.status}));try{s=await c.json()}catch{try{d.logger.error(l({msg:"/refresh returned a non-JSON response "+(s?await s.text():void 0)}))}catch{d.logger.error(l({msg:"/refresh returned a with no body "}))}s={ok:!1,error:"Unknown"}}if(s!=null&&s.ok){await this.scheduleAutoRefresh(e,o),n=!0;try{await this.tokenProvider.receiveTokens(s)}catch(h){const y=g.asCrossauthError(h);o?o("Couldn't receive tokens",y):(d.logger.debug(l({err:h})),d.logger.error(l({msg:"Error receiving tokens",cerr:y})))}}else i<se?(d.logger.error(l({msg:`Failed auto refreshing tokens. Retrying in ${de} seconds`})),await(y=>new Promise(_=>setTimeout(_,y)))(de*1e3)):(d.logger.error(l({msg:"Failed auto refreshing tokens. Number of retries exceeded"})),o&&o("Failed auto refreshing tokens")),i++}catch(a){const c=g.asCrossauthError(a);d.logger.debug(l({err:c})),i<se?(d.logger.error(l({msg:`Failed auto refreshing tokens. Retrying in ${se} seconds`})),await(y=>new Promise(_=>setTimeout(_,y)))(de*1e3)):(d.logger.error(l({msg:"Failed auto refreshing tokens. Number of retries exceeded"})),o&&o(c.message,c)),i++}}}}class fe{constructor(e){f(this,"deviceCodePollUrl","/devicecodepoll");f(this,"headers",{});f(this,"pollingActive",!1);f(this,"mode","cors");f(this,"credentials","same-origin");f(this,"respectRedirect",!0);f(this,"oauthClient");this.oauthClient=e.oauthClient,e.deviceCodePollUrl!=null&&(this.deviceCodePollUrl=e.deviceCodePollUrl),e.headers&&(this.headers=e.headers),e.mode&&(this.mode=e.mode),e.credentials&&(this.credentials=e.credentials)}async startPolling(e,t,o=5){this.pollingActive||(this.pollingActive=!0,d.logger.debug(l({msg:"Starting auto refresh"})),await this.poll(e,o,t))}stopPolling(){this.pollingActive=!1,d.logger.debug(l({msg:"Stopping auto refresh"}))}async poll(e,t,o){var s;if(!e)d.logger.debug(l({msg:"device code poll: no device code provided"})),o("error","Error waiting for authorization");else try{if(d.logger.debug(l({msg:"device code poll: poll"})),!this.deviceCodePollUrl&&this.oauthClient){if(this.oauthClient.getOidcConfig()||await this.oauthClient.loadConfig(),!((s=this.oauthClient.getOidcConfig())!=null&&s.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-oob")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};let i=this.oauthClient.getOidcConfig();if(!(i!=null&&i.token_endpoint))return{error:"server_error",error_description:"Couldn't get OIDC configuration"};this.deviceCodePollUrl=i.token_endpoint}if(!this.deviceCodePollUrl)return{error:"server_error",error_description:"Must either provide deviceCodePollUrl or an oauthClient to fetch it from"};const n=await fetch(this.deviceCodePollUrl,{method:"POST",body:JSON.stringify({device_code:e}),headers:{"content-type":"application/json"}});if(n.redirected)this.pollingActive=!1,n.redirected&&o("completeAndRedirect",void 0,n.url);else if(!n.ok)this.pollingActive=!1,o("error","Received an error from the authorization server");else{const i=await n.json();if(d.logger.debug(l({msg:"device code poll: received"+JSON.stringify(i)})),i.error=="expired_token")this.pollingActive=!1,o("expired_token","Timeout waiting for authorization");else if(i.error=="authorization_pending"||i.error=="slow_down"){i.error=="slow_down"&&(t+=5);let a=i.interval??t,c=h=>new Promise(y=>setTimeout(y,h));d.logger.debug(l({msg:"device code poll: waiting "+String(a)+" seconds"})),await c(a*1e3),this.pollingActive&&this.poll(e,t,o)}else i.error?(this.pollingActive=!1,o("error",i.error_description??i.error)):(this.pollingActive=!1,o("complete"))}}catch(n){this.pollingActive=!1;const i=g.asCrossauthError(n);d.logger.debug(l({err:i})),d.logger.error(l({msg:"Polling failed",cerr:i})),o("error",i.message)}}}class Ar{constructor(e={}){f(this,"bffPrefix","/bff");f(this,"csrfHeader","X-CROSSAUTH-CSRF");f(this,"enableCsrfProtection",!0);f(this,"headers",{});f(this,"mode","cors");f(this,"credentials","same-origin");f(this,"autoRefresher");f(this,"deviceCodePoller");f(this,"getCsrfTokenUrl","/api/getcsrftoken");f(this,"autoRefreshUrl","/api/refreshtokens");f(this,"tokensUrl","/tokens");e.bffPrefix&&(this.bffPrefix=e.bffPrefix),e.csrfHeader&&(this.csrfHeader=e.csrfHeader),e.enableCsrfProtection!=null&&(this.enableCsrfProtection=e.enableCsrfProtection),e.getCsrfTokenUrl&&(this.getCsrfTokenUrl=e.getCsrfTokenUrl),e.tokensUrl&&(this.tokensUrl=e.tokensUrl),e.autoRefreshUrl&&(this.autoRefreshUrl=e.autoRefreshUrl),this.bffPrefix.endsWith("/")||(this.bffPrefix+="/"),e.headers&&(this.headers=e.headers),e.mode&&(this.mode=e.mode),e.credentials&&(this.credentials=e.credentials),this.autoRefresher=new ue({...e,autoRefreshUrl:this.autoRefreshUrl,tokenProvider:this}),this.deviceCodePoller=new fe({...e,oauthClient:void 0})}async getCsrfToken(){if(this.enableCsrfProtection)try{const t=await(await fetch(this.getCsrfTokenUrl,{headers:this.headers,credentials:this.credentials,mode:this.mode})).json();if(!t.ok)throw g.asCrossauthError(t);return t.csrfToken}catch(e){throw g.asCrossauthError(e)}}async getIdToken(e){const t=await this.getTokens(e);return(t==null?void 0:t.id_token)??null}async haveIdToken(e){const t=await this.getTokens(e);return t==null?!1:t.have_id_token!=null?t.have_id_token:"id_token"in t}async getAccessToken(e){const t=await this.getTokens(e);return(t==null?void 0:t.access_token)??null}async haveAccessToken(e){const t=await this.getTokens(e);return t==null?!1:t.have_access_token!=null?t.have_access_token:"access_token"in t}async getRefreshToken(e){const t=await this.getTokens(e);return(t==null?void 0:t.refresh_token)??null}async haveRefreshToken(e){const t=await this.getTokens(e);return t==null?!1:t.have_refresh_token!=null?t.have_refresh_token:"refresh_token"in t}async api(e,t,o,s){let n={...this.headers};!s&&!["GET","HEAD","OPTIONS"].includes(e)&&(s=await this.getCsrfToken(),s&&(n[this.csrfHeader]=s)),t.startsWith("/")&&(t=t.substring(1));let i={};o&&(i.body=JSON.stringify(o));const a=await fetch(this.bffPrefix+t,{headers:n,method:e,mode:this.mode,credentials:this.credentials,...i});let c=null;return a.body&&(c=await a.json()),{status:a.status,body:c}}async getTokens(e){e||(e=await this.getCsrfToken());let t={...this.headers};e&&(t[this.csrfHeader]=e);try{const o=await fetch(this.tokensUrl,{method:"POST",headers:t,mode:this.mode,credentials:this.credentials});return o.status==204?{}:await o.json()}catch(o){throw g.asCrossauthError(o)}}async startAutoRefresh(e=["access","id"],t){return this.autoRefresher.startAutoRefresh(e,t)}stopAutoRefresh(){return this.autoRefresher.stopAutoRefresh()}async startDeviceCodePolling(e,t,o=5){return this.deviceCodePoller.startPolling(e,t,o)}stopDeviceCodePolling(){return this.deviceCodePoller.stopPolling()}async getTokenExpiries(e,t){const o=await this.getTokens(t);try{const s=e.includes("id")?(o==null?void 0:o.id_token)??null:null,n=e.includes("access")?(o==null?void 0:o.access_token)??null:null,i=e.includes("refresh")?(o==null?void 0:o.refresh_token)??null:null;let a,c,h;return s&&(a=s.exp?s.exp:null),n&&(c=n.exp?n.exp:null),i&&(h=i.exp?i.exp:null),{id:a,access:c,refresh:h}}catch{return d.logger.error(l({msg:"getTokenExpiries received non JSON response "+o})),{id:0,access:0,refresh:0}}}async jsonFetchWithToken(e,t,o){return typeof t.body!="string"&&(t.body=JSON.stringify(t.body)),await fetch(e,t)}receiveTokens(e){return new Promise(t=>{})}}class Rr{getCsrfToken(){return new Promise(e=>{})}}class xe extends br{async hash(e){const o=new TextEncoder().encode(e),s=await crypto.subtle.digest("SHA-256",o),n=Array.from(new Uint8Array(s));return btoa(n.reduce((i,a)=>i+String.fromCharCode(a),"")).replace(/\//g,"_").replace(/\+/g,"-").replace(/=+$/,"")}}var j,W,N,D,J,$,q,Z,ee,V;class Pr extends Er{constructor(t){t.tokenConsumer||(t.tokenConsumer=new xe(t.client_id,{authServerBaseUrl:t.authServerBaseUrl}));super(t);f(this,"resServerBaseUrl","");f(this,"resServerHeaders",{});f(this,"resServerMode","cors");f(this,"resServerCredentials","same-origin");f(this,"accessTokenResponseType","memory");f(this,"refreshTokenResponseType","memory");f(this,"idTokenResponseType","memory");f(this,"accessTokenName","CROSSAUTH_AT");f(this,"refreshTokenName","CROSSAUTH_RT");f(this,"idTokenName","CROSSAUTH_IT");R(this,j);R(this,W);R(this,N);R(this,D);R(this,J);R(this,$);R(this,q);f(this,"autoRefresher");f(this,"deviceCodePoller");f(this,"deviceAuthorizationUrl","device_authorization");R(this,Z);R(this,ee);R(this,V);f(this,"scope");f(this,"logFetch",!1);this.resServerBaseUrl!=null&&(this.resServerBaseUrl=t.resServerBaseUrl??"",this.resServerBaseUrl.length>0&&!this.resServerBaseUrl.endsWith("/")&&(this.resServerBaseUrl+="/")),t.accessTokenResponseType&&(this.accessTokenResponseType=t.accessTokenResponseType),t.idTokenResponseType&&(this.idTokenResponseType=t.idTokenResponseType),t.refreshTokenResponseType&&(this.refreshTokenResponseType=t.refreshTokenResponseType),t.accessTokenName&&(this.accessTokenName=t.accessTokenName),t.idTokenName&&(this.idTokenName=t.idTokenName),t.refreshTokenName&&(this.refreshTokenName=t.refreshTokenName),t.resServerHeaders&&(this.resServerHeaders=t.resServerHeaders),t.resServerMode&&(this.resServerMode=t.resServerMode),t.resServerCredentials&&(this.resServerCredentials=t.resServerCredentials),t.client_id&&T(this,$,t.client_id),t.client_secret&&T(this,q,t.client_secret),t.deviceAuthorizationUrl&&(this.deviceAuthorizationUrl=t.deviceAuthorizationUrl),this.autoRefresher=new ue({...t,autoRefreshUrl:this.authServerBaseUrl+"/token",tokenProvider:this}),this.deviceCodePoller=new fe({...t,oauthClient:this,deviceCodePollUrl:null});let o,s,n;if(this.idTokenResponseType=="sessionStorage"?o=sessionStorage.getItem(this.idTokenName):this.idTokenResponseType=="localStorage"&&(o=localStorage.getItem(this.idTokenName)),this.accessTokenResponseType=="sessionStorage"?s=sessionStorage.getItem(this.accessTokenName):this.accessTokenResponseType=="localStorage"&&(s=localStorage.getItem(this.accessTokenName)),this.refreshTokenResponseType=="sessionStorage"?n=sessionStorage.getItem(this.refreshTokenName):this.refreshTokenResponseType=="localStorage"&&(n=localStorage.getItem(this.refreshTokenName)),this.receiveTokens({access_token:s,id_token:o,refresh_token:n}),s){const i=this.getTokenPayload(s);i&&(T(this,j,s),T(this,D,i))}if(n){const i=this.getTokenPayload(n);i&&(T(this,W,n),T(this,J,i))}o?this.validateIdToken(o).then(i=>{T(this,N,i),t.autoRefresh&&this.startAutoRefresh(t.autoRefresh).then().catch(a=>{d.logger.debug(l({err:a,msg:"Couldn't start auto refresh"}))})}).catch(i=>{d.logger.debug(l({err:i,msg:"Couldn't validate ID token"}))}):p(this,j)&&t.autoRefresh&&n?this.startAutoRefresh(t.autoRefresh).then().catch(i=>{d.logger.debug(l({err:i,msg:"Couldn't start auto refresh"}))}):n&&!s&&this.refreshTokenFlow(n).then(i=>{d.logger.debug(l({msg:"Refreshed tokens"})),t.autoRefresh&&this.startAutoRefresh(t.autoRefresh).then().catch(a=>{d.logger.debug(l({err:a,msg:"Couldn't start auto refresh"}))})}).catch(i=>{const a=g.asCrossauthError(i);d.logger.debug(l({err:a})),d.logger.error(l({msg:"failed refreshing tokens",cerr:a}))})}get idTokenPayload(){return p(this,N)}async handleRedirectUri(){const t=new URL(window.location.href);if(t.origin+t.pathname!=this.redirect_uri)return;const o=new URLSearchParams(window.location.search);let s,n,i,a;for(const[h,y]of o)h=="code"&&(s=y),h=="state"&&(n=y),h=="error"&&(i=y),h=="error_description"&&(a=y);if(!i&&!s)return;if(i){const h=g.fromOAuthError(i,a);throw d.logger.debug(l({err:h})),d.logger.error(l({cerr:h,msg:"Error from authorize endpoint: "+i})),h}if(p(this,V)&&n!=p(this,V))return{error:"access_denied",error_description:"Invalid state"};const c=await this.redirectEndpoint(s,this.scope,p(this,ee),i,a);if(c.error){const h=g.fromOAuthError(c.error,a);throw d.logger.debug(l({err:h})),d.logger.error(l({cerr:h,msg:"Error from redirect endpoint: "+c.error})),h}return await this.receiveTokens(c),c}async startAutoRefresh(t=["access","id"],o){return this.autoRefresher.startAutoRefresh(t,o)}stopAutoRefresh(){return this.autoRefresher.stopAutoRefresh()}async startDeviceCodePolling(t,o,s=5){return this.deviceCodePoller.startPolling(t,o,s)}stopDeviceCodePolling(){return this.deviceCodePoller.stopPolling()}getIdToken(){return p(this,N)}randomValue(t){const o=new Uint8Array(t);return self.crypto.getRandomValues(o),btoa(o.reduce((s,n)=>s+String.fromCharCode(n),"")).replace(/\//g,"_").replace(/\+/g,"-").replace(/=+$/,"")}async sha256(t){const s=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",s),i=Array.from(new Uint8Array(n));return btoa(i.reduce((a,c)=>a+String.fromCharCode(c),"")).replace(/\//g,"_").replace(/\+/g,"-").replace(/=+$/,"")}async api(t,o,s){let n={...this.resServerHeaders};o.startsWith("/")&&(o=o.substring(1));let i={};s&&(i.body=JSON.stringify(s));let a;this.accessTokenResponseType=="sessionStorage"?a=sessionStorage.getItem(this.accessTokenName):this.accessTokenResponseType=="localStorage"&&(a=localStorage.getItem(this.accessTokenName)),n.authorization="Bearer "+a;const c=await fetch(this.resServerBaseUrl+o,{headers:n,method:t,mode:this.resServerMode,credentials:this.resServerCredentials,...i});let h=null;return c.body&&(h=await c.json()),{status:c.status,body:h}}async getTokenExpiries(t,o){let s,n,i;return p(this,N)&&(s=p(this,N).exp?p(this,N).exp:null),p(this,D)&&(n=p(this,D).exp?p(this,D).exp:null),p(this,J)&&(i=p(this,J).exp?p(this,J).exp:null),{id:s,access:n,refresh:i}}async jsonFetchWithToken(t,o,s){if(s=="access"){if(!p(this,j))throw new g(m.InvalidToken,"Cannot make fetch with access token - no access token defined");o.headers||(o.headers={}),o.headers.authorization="Bearer "+p(this,j)}else{if(o.body||(o.body={}),!p(this,W))throw new g(m.InvalidToken,"Cannot make fetch with refresh token - no refresh token defined");o.body.refresh_token=p(this,W),o.body.grant_type="refresh_token"}return p(this,$)&&(o.body||(o.body={}),o.body.client_id=p(this,$),p(this,q)&&(o.body.client_secret=p(this,q))),typeof o.body!="string"&&(o.body=JSON.stringify(o.body)),await fetch(t,o)}async getCsrfToken(){}async receiveTokens(t){if(t.access_token){const o=this.getTokenPayload(t.access_token);o&&(T(this,j,t.access_token),T(this,D,o)),this.accessTokenResponseType=="localStorage"?localStorage.setItem(this.accessTokenName,t.access_token):this.accessTokenResponseType=="sessionStorage"&&sessionStorage.setItem(this.accessTokenName,t.access_token)}if(t.refresh_token){const o=this.getTokenPayload(t.refresh_token);o&&(T(this,W,t.refresh_token),T(this,J,o)),this.refreshTokenResponseType=="localStorage"?localStorage.setItem(this.refreshTokenName,t.refresh_token):this.accessTokenResponseType=="sessionStorage"&&sessionStorage.setItem(this.refreshTokenName,t.refresh_token)}if(t.id_token){const o=await this.validateIdToken(t.id_token);T(this,N,o),this.idTokenResponseType=="localStorage"?localStorage.setItem(this.idTokenName,t.id_token):this.idTokenResponseType=="sessionStorage"&&sessionStorage.setItem(this.idTokenName,t.id_token)}}async clientCredentialsFlow(t){const o=await super.clientCredentialsFlow(t);return await this.receiveTokens(o),o}async passwordFlow(t,o,s){const n=await super.passwordFlow(t,o,s);return await this.receiveTokens(n),n}async deviceCodeFlow(t){let o=this.authServerBaseUrl;return o.endsWith("/")||(o+="/"),o+=this.deviceAuthorizationUrl,await super.startDeviceCodeFlow(o,t)}async mfaOtpComplete(t,o){const s=await super.mfaOtpComplete(t,o);return await this.receiveTokens(s),s}async mfaOobComplete(t,o,s){const n=await super.mfaOobComplete(t,o,s);return await this.receiveTokens(n),n}async refreshTokenFlow(t){if(!t)if(p(this,W))t=p(this,W);else throw new g(m.InvalidToken,"Cannot refresh tokens: no refresh token present");const o=await super.refreshTokenFlow(t);return await this.receiveTokens(o),o}async authorizationCodeFlow(t,o=!1){const s=this.randomValue(this.stateLength);if(this.scope=t,o){const i=await this.codeChallengeAndVerifier();T(this,Z,i.codeChallenge),T(this,ee,i.codeVerifier),T(this,V,s)}const n=await super.startAuthorizationCodeFlow(s,t,p(this,Z),o);if(n.error||!n.url){const i=g.fromOAuthError(n.error??"Couldn't create URL for authorization code flow",n.error_description);throw d.logger.debug(l({err:i})),i}location.href=n.url}}j=new WeakMap,W=new WeakMap,N=new WeakMap,D=new WeakMap,J=new WeakMap,$=new WeakMap,q=new WeakMap,Z=new WeakMap,ee=new WeakMap,V=new WeakMap;exports.CrossauthError=g;exports.CrossauthLogger=d;exports.OAuthAutoRefresher=ue;exports.OAuthBffClient=Ar;exports.OAuthClient=Pr;exports.OAuthDeviceCodePoller=fe;exports.OAuthTokenConsumer=xe;exports.OAuthTokenProvider=Rr;exports.j=l;
1
+ "use strict";var De=Object.defineProperty;var ge=r=>{throw TypeError(r)};var He=(r,e,t)=>e in r?De(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var f=(r,e,t)=>He(r,typeof e!="symbol"?e+"":e,t),pe=(r,e,t)=>e.has(r)||ge("Cannot "+t);var y=(r,e,t)=>(pe(r,e,"read from private field"),t?t.call(r):e.get(r)),R=(r,e,t)=>e.has(r)?ge("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),T=(r,e,t,o)=>(pe(r,e,"write to private field"),o?o.call(r,t):e.set(r,t),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var je=Object.defineProperty,Ce=r=>{throw TypeError(r)},Je=(r,e,t)=>e in r?je(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,u=(r,e,t)=>Je(r,typeof e!="symbol"?e+"":e,t),Se=(r,e,t)=>e.has(r)||Ce("Cannot "+t),w=(r,e,t)=>(Se(r,e,"read from private field"),e.get(r)),ye=(r,e,t)=>e.has(r)?Ce("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),te=(r,e,t,o)=>(Se(r,e,"write to private field"),e.set(r,t),t);class K{}u(K,"active","active"),u(K,"disabled","disabled"),u(K,"awaitingTwoFactorSetup","awaitingtwofactorsetup"),u(K,"awaitingTwoFactorSetupAndEmailVerification","awaitingtwofactorsetupandemailverification"),u(K,"awaitingEmailVerification","awaitingemailverification"),u(K,"passwordChangeNeeded","passwordchangeneeded"),u(K,"passwordResetNeeded","passwordresetneeded"),u(K,"factor2ResetNeeded","factor2resetneeded"),u(K,"passwordAndFactor2ResetNeeded","passwordandfactor2resetneeded");class O{}u(O,"session","s:"),u(O,"passwordResetToken","p:"),u(O,"emailVerificationToken","e:"),u(O,"apiKey","api:"),u(O,"authorizationCode","authz:"),u(O,"accessToken","access:"),u(O,"refreshToken","refresh:"),u(O,"mfaToken","omfa:"),u(O,"deviceCode","dc:"),u(O,"userCode","uc:");var m=(r=>(r[r.UserNotExist=0]="UserNotExist",r[r.PasswordInvalid=1]="PasswordInvalid",r[r.EmailNotExist=2]="EmailNotExist",r[r.UsernameOrPasswordInvalid=3]="UsernameOrPasswordInvalid",r[r.InvalidClientId=4]="InvalidClientId",r[r.ClientExists=5]="ClientExists",r[r.InvalidClientSecret=6]="InvalidClientSecret",r[r.InvalidClientIdOrSecret=7]="InvalidClientIdOrSecret",r[r.InvalidRedirectUri=8]="InvalidRedirectUri",r[r.InvalidOAuthFlow=9]="InvalidOAuthFlow",r[r.UserNotActive=10]="UserNotActive",r[r.EmailNotVerified=11]="EmailNotVerified",r[r.TwoFactorIncomplete=12]="TwoFactorIncomplete",r[r.Unauthorized=13]="Unauthorized",r[r.UnauthorizedClient=14]="UnauthorizedClient",r[r.InvalidScope=15]="InvalidScope",r[r.InsufficientScope=16]="InsufficientScope",r[r.InsufficientPriviledges=17]="InsufficientPriviledges",r[r.Forbidden=18]="Forbidden",r[r.InvalidKey=19]="InvalidKey",r[r.InvalidCsrf=20]="InvalidCsrf",r[r.InvalidSession=21]="InvalidSession",r[r.Expired=22]="Expired",r[r.Connection=23]="Connection",r[r.InvalidHash=24]="InvalidHash",r[r.UnsupportedAlgorithm=25]="UnsupportedAlgorithm",r[r.KeyExists=26]="KeyExists",r[r.PasswordChangeNeeded=27]="PasswordChangeNeeded",r[r.PasswordResetNeeded=28]="PasswordResetNeeded",r[r.Factor2ResetNeeded=29]="Factor2ResetNeeded",r[r.Configuration=30]="Configuration",r[r.InvalidEmail=31]="InvalidEmail",r[r.InvalidPhoneNumber=32]="InvalidPhoneNumber",r[r.InvalidUsername=33]="InvalidUsername",r[r.PasswordMatch=34]="PasswordMatch",r[r.InvalidToken=35]="InvalidToken",r[r.MfaRequired=36]="MfaRequired",r[r.PasswordFormat=37]="PasswordFormat",r[r.DataFormat=38]="DataFormat",r[r.FetchError=39]="FetchError",r[r.UserExists=40]="UserExists",r[r.FormEntry=41]="FormEntry",r[r.BadRequest=42]="BadRequest",r[r.AuthorizationPending=43]="AuthorizationPending",r[r.SlowDown=44]="SlowDown",r[r.ExpiredToken=45]="ExpiredToken",r[r.ConstraintViolation=46]="ConstraintViolation",r[r.NotImplemented=47]="NotImplemented",r[r.UnknownError=48]="UnknownError",r))(m||{});class g extends Error{constructor(e,t=void 0){let o,s=500;e==0?(o="User does not exist",s=401):e==1?(o="Password doesn't match",s=401):e==3?(o="Username or password incorrect",s=401):e==4?(o="Client id is invalid",s=401):e==5?(o="Client ID or name already exists",s=500):e==6?(o="Client secret is invalid",s=401):e==7?(o="Client id or secret is invalid",s=401):e==8?(o="Redirect Uri is not registered",s=401):e==9?(o="Invalid OAuth flow type",s=500):e==2?(o="No user exists with that email address",s=401):e==10?(o="Account is not active",s=403):e==33?(o="Username is not in an allowed format",s=400):e==31?(o="Email is not in an allowed format",s=400):e==32?(o="Phone number is not in an allowed format",s=400):e==11?(o="Email address has not been verified",s=403):e==12?(o="Two-factor setup is not complete",s=403):e==13?(o="Not authorized",s=401):e==14?(o="Client not authorized",s=401):e==15?(o="Invalid scope",s=403):e==16?(o="Insufficient scope",s=403):e==23?o="Connection failure":e==22?(o="Token has expired",s=401):e==24?o="Hash is not in a valid format":e==19?(o="Key is invalid",s=401):e==18?(o="You do not have permission to access this resource",s=403):e==17?(o="You do not have the right privileges to access this resource",s=401):e==20?(o="CSRF token is invalid",s=401):e==21?(o="Session cookie is invalid",s=401):e==25?o="Algorithm not supported":e==26?o="Attempt to create a key that already exists":e==27?(o="User must change password",s=403):e==28?(o="User must reset password",s=403):e==29?(o="User must reset 2FA",s=403):e==30?o="There was an error in the configuration":e==34?(o="Passwords do not match",s=401):e==35?(o="Token is not valid",s=401):e==36?(o="MFA is required",s=401):e==37?(o="Password format was incorrect",s=401):e==40?(o="User already exists",s=400):e==42?(o="The request is invalid",s=400):e==38?(o="Session data has unexpected format",s=500):e==39?(o="Couldn't execute a fetch",s=500):e==43?(o="Waiting for authorization",s=200):e==44?(o="Slow polling down by 5 seconds",s=200):e==45?(o="Token has expired",s=401):e==46?(o="Database update/insert caused a constraint violation",s=500):e==47?(o="This method has not been implemented",s=500):(o="Unknown error",s=500),t!=null&&!Array.isArray(t)?o=t:Array.isArray(t)&&(o=t.join(". ")),super(o),u(this,"isCrossauthError",!0),u(this,"httpStatus"),u(this,"code"),u(this,"codeName"),u(this,"messages"),this.code=e,this.codeName=m[e],this.httpStatus=s,this.name="CrossauthError",Array.isArray(t)?this.messages=t:this.messages=[o],Object.setPrototypeOf(this,g.prototype)}static fromOAuthError(e,t){let o;switch(e){case"invalid_request":o=42;break;case"unauthorized_client":o=14;break;case"access_denied":o=13;break;case"unsupported_response_type":o=42;break;case"invalid_scope":o=15;break;case"server_error":o=48;break;case"temporarily_unavailable":o=23;break;case"invalid_token":o=35;break;case"expired_token":o=45;break;case"insufficient_scope":o=35;break;case"mfa_required":o=36;break;case"authorization_pending":o=43;break;case"slow_down":o=44;break;default:o=48}return new g(o,t)}get oauthErrorCode(){switch(this.code){case 42:return"invalid_request";case 14:return"unauthorized_client";case 13:return"access_denied";case 15:return"invalid_scope";case 23:return"temporarily_unavailable";case 35:return"invalid_token";case 36:return"mfa_required";case 43:return"authorization_pending";case 44:return"slow_down";case 45:return"expired_token";case 22:return"expired_token";default:return"server_error"}}static asCrossauthError(e,t){if(e instanceof Error)return"isCrossauthError"in e?e:new g(48,e.message);if("errorCode"in e){let s=48;try{s=Number(e.errorCode)??48}catch{}let n=t??m[s];return"errorMessage"in e?n=e.errorMessage:"message"in e&&(n=e.message),new g(s,n)}let o=t??m[48];return"message"in e&&(o=e.message),new g(48,o)}}const L=class P{constructor(e){if(u(this,"level"),e)this.level=e;else if(typeof process<"u"&&"CROSSAUTH_LOG_LEVEL"in process.env){const t=(process.env.CROSSAUTH_LOG_LEVEL??"ERROR").toUpperCase();P.levelName.includes(t)?this.level=P.levelName.indexOf(t):this.level=P.Error}else this.level=P.Error}static get logger(){return globalThis.crossauthLogger}setLevel(e){this.level=e}log(e,t){e<=this.level&&(typeof t=="string"?console.log("Crossauth "+P.levelName[e]+" "+new Date().toISOString(),t):console.log(JSON.stringify({level:P.levelName[e],time:new Date().toISOString(),...t})))}error(e){this.log(P.Error,e)}warn(e){this.log(P.Warn,e)}info(e){this.log(P.Info,e)}debug(e){this.log(P.Debug,e)}static setLogger(e,t){globalThis.crossauthLogger=e,globalThis.crossauthLoggerAcceptsJson=t}};u(L,"None",0),u(L,"Error",1),u(L,"Warn",2),u(L,"Info",3),u(L,"Debug",4),u(L,"levelName",["NONE","ERROR","WARN","INFO","DEBUG"]);let d=L;function l(r){let e;typeof r=="object"&&"err"in r&&typeof r.err=="object"&&(e=r.err.stack);try{typeof r=="object"&&"err"in r&&typeof r.err=="object"&&r.err&&"message"in r.err&&!("msg"in r)&&(r.msg=r.err.message)}catch{}try{typeof r=="object"&&"err"in r&&typeof r.err=="object"&&(r.err={...r.err,stack:e})}catch{}try{typeof r=="object"&&"err"in r&&!("msg"in r)&&(r.msg=r.msg="An unknown error occurred")}catch{}try{typeof r=="object"&&"cerr"in r&&"isCrossauthError"in r.cerr&&r.cerr&&(r.errorCode=r.cerr.code,r.errorCodeName=r.cerr.codeName,r.httpStatus=r.cerr.httpStatus,"msg"in r||(r.msg=r.cerr.message),delete r.cerr)}catch{}return typeof r=="string"||globalThis.crossauthLoggerAcceptsJson?r:JSON.stringify(r)}globalThis.crossauthLogger=new d;globalThis.crossauthLoggerAcceptsJson=!0;const Te={issuer:"",authorization_endpoint:"",token_endpoint:"",jwks_uri:"",response_types_supported:[],subject_types_supported:[],response_modes_supported:["query","fragment"],grant_types_supported:["authorization_code","implicit"],id_token_signing_alg_values_supported:[],claim_types_supported:["normal"],claims_parameter_supported:!1,request_parameter_supported:!1,request_uri_parameter_supported:!0,require_request_uri_registration:!1},ae=crypto,Ee=r=>r instanceof CryptoKey,oe=new TextEncoder,re=new TextDecoder;function ze(...r){const e=r.reduce((s,{length:n})=>s+n,0),t=new Uint8Array(e);let o=0;for(const s of r)t.set(s,o),o+=s.length;return t}const Le=r=>{const e=atob(r),t=new Uint8Array(e.length);for(let o=0;o<e.length;o++)t[o]=e.charCodeAt(o);return t},z=r=>{let e=r;e instanceof Uint8Array&&(e=re.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return Le(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class E extends Error{constructor(e,t){var o;super(e,t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(o=Error.captureStackTrace)==null||o.call(Error,this,this.constructor)}}E.code="ERR_JOSE_GENERIC";class Fe extends E{constructor(e,t,o="unspecified",s="unspecified"){super(e,{cause:{claim:o,reason:s,payload:t}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=o,this.reason=s,this.payload=t}}Fe.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class Me extends E{constructor(e,t,o="unspecified",s="unspecified"){super(e,{cause:{claim:o,reason:s,payload:t}}),this.code="ERR_JWT_EXPIRED",this.claim=o,this.reason=s,this.payload=t}}Me.code="ERR_JWT_EXPIRED";class Be extends E{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}Be.code="ERR_JOSE_ALG_NOT_ALLOWED";class I extends E{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}I.code="ERR_JOSE_NOT_SUPPORTED";class $e extends E{constructor(e="decryption operation failed",t){super(e,t),this.code="ERR_JWE_DECRYPTION_FAILED"}}$e.code="ERR_JWE_DECRYPTION_FAILED";class qe extends E{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}qe.code="ERR_JWE_INVALID";class C extends E{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}C.code="ERR_JWS_INVALID";class x extends E{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}x.code="ERR_JWT_INVALID";class Ve extends E{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}Ve.code="ERR_JWK_INVALID";class Ge extends E{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}Ge.code="ERR_JWKS_INVALID";class Ye extends E{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_NO_MATCHING_KEY"}}Ye.code="ERR_JWKS_NO_MATCHING_KEY";class Xe extends E{constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}Xe.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class Qe extends E{constructor(e="request timed out",t){super(e,t),this.code="ERR_JWKS_TIMEOUT"}}Qe.code="ERR_JWKS_TIMEOUT";class be extends E{constructor(e="signature verification failed",t){super(e,t),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}be.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function U(r,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${r}`)}function Q(r,e){return r.name===e}function ce(r){return parseInt(r.name.slice(4),10)}function Ze(r){switch(r){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function er(r,e){if(e.length&&!e.some(t=>r.usages.includes(t))){let t="CryptoKey does not support this operation, its usages must include ";if(e.length>2){const o=e.pop();t+=`one of ${e.join(", ")}, or ${o}.`}else e.length===2?t+=`one of ${e[0]} or ${e[1]}.`:t+=`${e[0]}.`;throw new TypeError(t)}}function rr(r,e,...t){switch(e){case"HS256":case"HS384":case"HS512":{if(!Q(r.algorithm,"HMAC"))throw U("HMAC");const o=parseInt(e.slice(2),10);if(ce(r.algorithm.hash)!==o)throw U(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!Q(r.algorithm,"RSASSA-PKCS1-v1_5"))throw U("RSASSA-PKCS1-v1_5");const o=parseInt(e.slice(2),10);if(ce(r.algorithm.hash)!==o)throw U(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!Q(r.algorithm,"RSA-PSS"))throw U("RSA-PSS");const o=parseInt(e.slice(2),10);if(ce(r.algorithm.hash)!==o)throw U(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(r.algorithm.name!=="Ed25519"&&r.algorithm.name!=="Ed448")throw U("Ed25519 or Ed448");break}case"Ed25519":{if(!Q(r.algorithm,"Ed25519"))throw U("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!Q(r.algorithm,"ECDSA"))throw U("ECDSA");const o=Ze(e);if(r.algorithm.namedCurve!==o)throw U(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}er(r,t)}function Ae(r,e,...t){var o;if(t=t.filter(Boolean),t.length>2){const s=t.pop();r+=`one of type ${t.join(", ")}, or ${s}.`}else t.length===2?r+=`one of type ${t[0]} or ${t[1]}.`:r+=`of type ${t[0]}.`;return e==null?r+=` Received ${e}`:typeof e=="function"&&e.name?r+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&(o=e.constructor)!=null&&o.name&&(r+=` Received an instance of ${e.constructor.name}`),r}const we=(r,...e)=>Ae("Key must be ",r,...e);function Re(r,e,...t){return Ae(`Key for the ${r} algorithm must be `,e,...t)}const Pe=r=>Ee(r)?!0:(r==null?void 0:r[Symbol.toStringTag])==="KeyObject",ie=["CryptoKey"],tr=(...r)=>{const e=r.filter(Boolean);if(e.length===0||e.length===1)return!0;let t;for(const o of e){const s=Object.keys(o);if(!t||t.size===0){t=new Set(s);continue}for(const n of s){if(t.has(n))return!1;t.add(n)}}return!0};function or(r){return typeof r=="object"&&r!==null}function G(r){if(!or(r)||Object.prototype.toString.call(r)!=="[object Object]")return!1;if(Object.getPrototypeOf(r)===null)return!0;let e=r;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(r)===e}const sr=(r,e)=>{if(r.startsWith("RS")||r.startsWith("PS")){const{modulusLength:t}=e.algorithm;if(typeof t!="number"||t<2048)throw new TypeError(`${r} requires key modulusLength to be 2048 bits or larger`)}};function Y(r){return G(r)&&typeof r.kty=="string"}function ir(r){return r.kty!=="oct"&&typeof r.d=="string"}function nr(r){return r.kty!=="oct"&&typeof r.d>"u"}function ar(r){return Y(r)&&r.kty==="oct"&&typeof r.k=="string"}function cr(r){let e,t;switch(r.kty){case"RSA":{switch(r.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${r.alg.slice(-3)}`},t=r.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${r.alg.slice(-3)}`},t=r.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(r.alg.slice(-3),10)||1}`},t=r.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new I('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(r.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},t=r.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},t=r.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},t=r.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:r.crv},t=r.d?["deriveBits"]:[];break;default:throw new I('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(r.alg){case"Ed25519":e={name:"Ed25519"},t=r.d?["sign"]:["verify"];break;case"EdDSA":e={name:r.crv},t=r.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:r.crv},t=r.d?["deriveBits"]:[];break;default:throw new I('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new I('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:t}}const Ie=async r=>{if(!r.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:e,keyUsages:t}=cr(r),o=[e,r.ext??!1,r.key_ops??t],s={...r};return delete s.alg,delete s.use,ae.subtle.importKey("jwk",s,...o)},Oe=r=>z(r);let F,M;const Ue=r=>(r==null?void 0:r[Symbol.toStringTag])==="KeyObject",ne=async(r,e,t,o,s=!1)=>{let n=r.get(e);if(n!=null&&n[o])return n[o];const i=await Ie({...t,alg:o});return s&&Object.freeze(e),n?n[o]=i:r.set(e,{[o]:i}),i},dr=(r,e)=>{if(Ue(r)){let t=r.export({format:"jwk"});return delete t.d,delete t.dp,delete t.dq,delete t.p,delete t.q,delete t.qi,t.k?Oe(t.k):(M||(M=new WeakMap),ne(M,r,t,e))}return Y(r)?r.k?z(r.k):(M||(M=new WeakMap),ne(M,r,r,e,!0)):r},lr=(r,e)=>{if(Ue(r)){let t=r.export({format:"jwk"});return t.k?Oe(t.k):(F||(F=new WeakMap),ne(F,r,t,e))}return Y(r)?r.k?z(r.k):(F||(F=new WeakMap),ne(F,r,r,e,!0)):r},hr={normalizePublicKey:dr,normalizePrivateKey:lr},D=(r,e,t=0)=>{t===0&&(e.unshift(e.length),e.unshift(6));const o=r.indexOf(e[0],t);if(o===-1)return!1;const s=r.subarray(o,o+e.length);return s.length!==e.length?!1:s.every((n,i)=>n===e[i])||D(r,e,o+1)},me=r=>{switch(!0){case D(r,[42,134,72,206,61,3,1,7]):return"P-256";case D(r,[43,129,4,0,34]):return"P-384";case D(r,[43,129,4,0,35]):return"P-521";case D(r,[43,101,110]):return"X25519";case D(r,[43,101,111]):return"X448";case D(r,[43,101,112]):return"Ed25519";case D(r,[43,101,113]):return"Ed448";default:throw new I("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},Ne=async(r,e,t,o,s)=>{let n,i;const a=new Uint8Array(atob(t.replace(r,"")).split("").map(h=>h.charCodeAt(0))),c=e==="spki";switch(o){case"PS256":case"PS384":case"PS512":n={name:"RSA-PSS",hash:`SHA-${o.slice(-3)}`},i=c?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":n={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${o.slice(-3)}`},i=c?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":n={name:"RSA-OAEP",hash:`SHA-${parseInt(o.slice(-3),10)||1}`},i=c?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":n={name:"ECDSA",namedCurve:"P-256"},i=c?["verify"]:["sign"];break;case"ES384":n={name:"ECDSA",namedCurve:"P-384"},i=c?["verify"]:["sign"];break;case"ES512":n={name:"ECDSA",namedCurve:"P-521"},i=c?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{const h=me(a);n=h.startsWith("P-")?{name:"ECDH",namedCurve:h}:{name:h},i=c?[]:["deriveBits"];break}case"Ed25519":n={name:"Ed25519"},i=c?["verify"]:["sign"];break;case"EdDSA":n={name:me(a)},i=c?["verify"]:["sign"];break;default:throw new I('Invalid or unsupported "alg" (Algorithm) value')}return ae.subtle.importKey(e,a,n,!1,i)},ur=(r,e,t)=>Ne(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",r,e),fr=(r,e,t)=>Ne(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",r,e);async function gr(r,e,t){if(typeof r!="string"||r.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return fr(r,e)}async function pr(r,e,t){if(typeof r!="string"||r.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return ur(r,e)}async function le(r,e){if(!G(r))throw new TypeError("JWK must be an object");switch(e||(e=r.alg),r.kty){case"oct":if(typeof r.k!="string"||!r.k)throw new TypeError('missing "k" (Key Value) Parameter value');return z(r.k);case"RSA":if("oth"in r&&r.oth!==void 0)throw new I('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return Ie({...r,alg:e});default:throw new I('Unsupported "kty" (Key Type) Parameter value')}}const B=r=>r==null?void 0:r[Symbol.toStringTag],he=(r,e,t)=>{var o,s;if(e.use!==void 0&&e.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(e.key_ops!==void 0&&((s=(o=e.key_ops).includes)==null?void 0:s.call(o,t))!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${t}`);if(e.alg!==void 0&&e.alg!==r)throw new TypeError(`Invalid key for this operation, when present its alg must be ${r}`);return!0},yr=(r,e,t,o)=>{if(!(e instanceof Uint8Array)){if(o&&Y(e)){if(ar(e)&&he(r,e,t))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!Pe(e))throw new TypeError(Re(r,e,...ie,"Uint8Array",o?"JSON Web Key":null));if(e.type!=="secret")throw new TypeError(`${B(e)} instances for symmetric algorithms must be of type "secret"`)}},wr=(r,e,t,o)=>{if(o&&Y(e))switch(t){case"sign":if(ir(e)&&he(r,e,t))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(nr(e)&&he(r,e,t))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Pe(e))throw new TypeError(Re(r,e,...ie,o?"JSON Web Key":null));if(e.type==="secret")throw new TypeError(`${B(e)} instances for asymmetric algorithms must not be of type "secret"`);if(t==="sign"&&e.type==="public")throw new TypeError(`${B(e)} instances for asymmetric algorithm signing must be of type "private"`);if(t==="decrypt"&&e.type==="public")throw new TypeError(`${B(e)} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&t==="verify"&&e.type==="private")throw new TypeError(`${B(e)} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&t==="encrypt"&&e.type==="private")throw new TypeError(`${B(e)} instances for asymmetric algorithm encryption must be of type "public"`)};function Ke(r,e,t,o){e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?yr(e,t,o,r):wr(e,t,o,r)}Ke.bind(void 0,!1);const ve=Ke.bind(void 0,!0);function mr(r,e,t,o,s){if(s.crit!==void 0&&(o==null?void 0:o.crit)===void 0)throw new r('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||o.crit===void 0)return new Set;if(!Array.isArray(o.crit)||o.crit.length===0||o.crit.some(i=>typeof i!="string"||i.length===0))throw new r('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let n;n=e;for(const i of o.crit){if(!n.has(i))throw new I(`Extension Header Parameter "${i}" is not recognized`);if(s[i]===void 0)throw new r(`Extension Header Parameter "${i}" is missing`);if(n.get(i)&&o[i]===void 0)throw new r(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(o.crit)}function vr(r,e){const t=`SHA-${r.slice(-3)}`;switch(r){case"HS256":case"HS384":case"HS512":return{hash:t,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:t,name:"RSA-PSS",saltLength:r.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:t,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:t,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:e.name};default:throw new I(`alg ${r} is not supported either by JOSE or your javascript runtime`)}}async function _r(r,e,t){if(e=await hr.normalizePublicKey(e,r),Ee(e))return rr(e,r,t),e;if(e instanceof Uint8Array){if(!r.startsWith("HS"))throw new TypeError(we(e,...ie));return ae.subtle.importKey("raw",e,{hash:`SHA-${r.slice(-3)}`,name:"HMAC"},!1,[t])}throw new TypeError(we(e,...ie,"Uint8Array","JSON Web Key"))}const kr=async(r,e,t,o)=>{const s=await _r(r,e,"verify");sr(r,s);const n=vr(r,s.algorithm);try{return await ae.subtle.verify(n,s,t,o)}catch{return!1}};async function Cr(r,e,t){if(!G(r))throw new C("Flattened JWS must be an object");if(r.protected===void 0&&r.header===void 0)throw new C('Flattened JWS must have either of the "protected" or "header" members');if(r.protected!==void 0&&typeof r.protected!="string")throw new C("JWS Protected Header incorrect type");if(r.payload===void 0)throw new C("JWS Payload missing");if(typeof r.signature!="string")throw new C("JWS Signature missing or incorrect type");if(r.header!==void 0&&!G(r.header))throw new C("JWS Unprotected Header incorrect type");let o={};if(r.protected)try{const X=z(r.protected);o=JSON.parse(re.decode(X))}catch{throw new C("JWS Protected Header is invalid")}if(!tr(o,r.header))throw new C("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const s={...o,...r.header},n=mr(C,new Map([["b64",!0]]),void 0,o,s);let i=!0;if(n.has("b64")&&(i=o.b64,typeof i!="boolean"))throw new C('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=s;if(typeof a!="string"||!a)throw new C('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(i){if(typeof r.payload!="string")throw new C("JWS Payload must be a string")}else if(typeof r.payload!="string"&&!(r.payload instanceof Uint8Array))throw new C("JWS Payload must be a string or an Uint8Array instance");let c=!1;typeof e=="function"?(e=await e(o,r),c=!0,ve(a,e,"verify"),Y(e)&&(e=await le(e,a))):ve(a,e,"verify");const h=ze(oe.encode(r.protected??""),oe.encode("."),typeof r.payload=="string"?oe.encode(r.payload):r.payload);let p;try{p=z(r.signature)}catch{throw new C("Failed to base64url decode the signature")}if(!await kr(a,e,p,h))throw new be;let _;if(i)try{_=z(r.payload)}catch{throw new C("Failed to base64url decode the payload")}else typeof r.payload=="string"?_=oe.encode(r.payload):_=r.payload;const b={payload:_};return r.protected!==void 0&&(b.protectedHeader=o),r.header!==void 0&&(b.unprotectedHeader=r.header),c?{...b,key:e}:b}async function Sr(r,e,t){if(r instanceof Uint8Array&&(r=re.decode(r)),typeof r!="string")throw new C("Compact JWS must be a string or Uint8Array");const{0:o,1:s,2:n,length:i}=r.split(".");if(i!==3)throw new C("Invalid Compact JWS");const a=await Cr({payload:s,protected:o,signature:n},e),c={payload:a.payload,protectedHeader:a.protectedHeader};return typeof e=="function"?{...c,key:a.key}:c}const We=z;function _e(r){let e;if(typeof r=="string"){const t=r.split(".");(t.length===3||t.length===5)&&([e]=t)}else if(typeof r=="object"&&r)if("protected"in r)e=r.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof e!="string"||!e)throw new Error;const t=JSON.parse(re.decode(We(e)));if(!G(t))throw new Error;return t}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}function Tr(r){if(typeof r!="string")throw new x("JWTs must use Compact JWS serialization, JWT must be a string");const{1:e,length:t}=r.split(".");if(t===5)throw new x("Only JWTs using Compact JWS serialization can be decoded");if(t!==3)throw new x("Invalid JWT");if(!e)throw new x("JWTs must contain a payload");let o;try{o=We(e)}catch{throw new x("Failed to base64url decode the payload")}let s;try{s=JSON.parse(re.decode(o))}catch{throw new x("Failed to parse the decoded payload as JSON")}if(!G(s))throw new x("Invalid JWT Claims Set");return s}const k=class v{static flowNames(e){let t={};return e.forEach(o=>{o in v.flowName&&(t[o]=v.flowName[o])}),t}static isValidFlow(e){return v.allFlows().includes(e)}static areAllValidFlows(e){let t=!0;return e.forEach(o=>{v.isValidFlow(o)||(t=!1)}),t}static allFlows(){return[v.AuthorizationCode,v.AuthorizationCodeWithPKCE,v.ClientCredentials,v.RefreshToken,v.DeviceCode,v.Password,v.PasswordMfa,v.OidcAuthorizationCode]}static grantType(e){switch(e){case v.AuthorizationCode:case v.AuthorizationCodeWithPKCE:case v.OidcAuthorizationCode:return["authorization_code"];case v.ClientCredentials:return["client_credentials"];case v.RefreshToken:return["refresh_token"];case v.Password:return["password"];case v.PasswordMfa:return["http://auth0.com/oauth/grant-type/mfa-otp","http://auth0.com/oauth/grant-type/mfa-oob"];case v.DeviceCode:return["urn:ietf:params:oauth:grant-type:device_code"]}}};u(k,"All","all"),u(k,"AuthorizationCode","authorizationCode"),u(k,"AuthorizationCodeWithPKCE","authorizationCodeWithPKCE"),u(k,"ClientCredentials","clientCredentials"),u(k,"RefreshToken","refreshToken"),u(k,"DeviceCode","deviceCode"),u(k,"Password","password"),u(k,"PasswordMfa","passwordMfa"),u(k,"OidcAuthorizationCode","oidcAuthorizationCode"),u(k,"flowName",{[k.AuthorizationCode]:"Authorization Code",[k.AuthorizationCodeWithPKCE]:"Authorization Code with PKCE",[k.ClientCredentials]:"Client Credentials",[k.RefreshToken]:"Refresh Token",[k.DeviceCode]:"Device Code",[k.Password]:"Password",[k.PasswordMfa]:"Password MFA",[k.OidcAuthorizationCode]:"OIDC Authorization Code"});var S,A;class Er{constructor({authServerBaseUrl:e,client_id:t,client_secret:o,redirect_uri:s,codeChallengeMethod:n,stateLength:i,verifierLength:a,tokenConsumer:c,authServerCredentials:h,authServerMode:p,authServerHeaders:_}){u(this,"authServerBaseUrl",""),ye(this,S),ye(this,A),u(this,"codeChallengeMethod","S256"),u(this,"verifierLength",32),u(this,"redirect_uri"),u(this,"stateLength",32),u(this,"authzCode",""),u(this,"oidcConfig"),u(this,"tokenConsumer"),u(this,"authServerHeaders",{}),u(this,"authServerMode"),u(this,"authServerCredentials"),u(this,"oauthPostType","json"),u(this,"oauthLogFetch",!1),u(this,"oauthUseUserInfoEndpoint",!1),u(this,"oauthAuthorizeRedirect"),this.tokenConsumer=c,this.authServerBaseUrl=e,a&&(this.verifierLength=a),i&&(this.stateLength=i),t&&te(this,S,t),o&&te(this,A,o),s&&(this.redirect_uri=s),n&&(this.codeChallengeMethod=n),this.authServerBaseUrl=e,h&&(this.authServerCredentials=h),p&&(this.authServerMode=p),_&&(this.authServerHeaders=_)}set client_id(e){te(this,S,e)}set client_secret(e){te(this,A,e)}async loadConfig(e){if(e){d.logger.debug(l({msg:"Reading OIDC config locally"})),this.oidcConfig=e;return}let t;try{const o=new URL(this.authServerBaseUrl+"/.well-known/openid-configuration");d.logger.debug(l({msg:`Fetching OIDC config from ${o}`}));let s={headers:this.authServerHeaders};this.authServerMode&&(s.mode=this.authServerMode),this.authServerCredentials&&(s.credentials=this.authServerCredentials),t=await fetch(o,s)}catch(o){d.logger.error(l({err:o}))}if(!t||!t.ok)throw new g(m.Connection,"Couldn't get OIDC configuration from URL"+this.authServerBaseUrl+"/.well-known/openid-configuration");this.oidcConfig={...Te};try{const o=await t.json();for(const[s,n]of Object.entries(o))this.oidcConfig[s]=n}catch{throw new g(m.Connection,"Unrecognized response from OIDC configuration endpoint")}}getOidcConfig(){return this.oidcConfig}async startAuthorizationCodeFlow(e,{scope:t,codeChallenge:o,pkce:s=!1,upstream:n}){var i,a,c;if(d.logger.debug(l({msg:"Starting authorization code flow, scope "+t})),this.oidcConfig||await this.loadConfig(),!((i=this.oidcConfig)!=null&&i.response_types_supported.includes("code"))||!((a=this.oidcConfig)!=null&&a.response_modes_supported.includes("query")))return{error:"invalid_request",error_description:"Server does not support authorization code flow"};if(!((c=this.oidcConfig)!=null&&c.authorization_endpoint))return{error:"server_error",error_description:"Cannot get authorize endpoint"};if(!w(this,S))return{error:"invalid_request",error_description:"Cannot make authorization code flow without client id"};if(!this.redirect_uri)return{error:"invalid_request",error_description:"Cannot make authorization code flow without Redirect Uri"};let h=this.oidcConfig.authorization_endpoint;this.oauthAuthorizeRedirect&&(h=this.oauthAuthorizeRedirect);let p=h+"?response_type=code&client_id="+encodeURIComponent(w(this,S))+"&state="+encodeURIComponent(e)+"&redirect_uri="+encodeURIComponent(this.redirect_uri);return t&&(p+="&scope="+encodeURIComponent(t)),s&&o&&(p+="&code_challenge="+o),{url:p}}async codeChallengeAndVerifier(){const e=this.randomValue(this.verifierLength);return{codeChallenge:this.codeChallengeMethod=="plain"?e:await this.sha256(e),codeVerifier:e}}async getIdPayload(e,t){let o,s;try{let n;if(n=await this.validateIdToken(e),!n)return o="access_denied",s="Invalid ID token received",{error:o,error_description:s};if(t&&this.oauthUseUserInfoEndpoint){const i=await this.userInfoEndpoint(t);if(i.error)return o=i.error,s="Failed getting user info: "+(i.error_description??"unknown error"),{error:o,error_description:s};n={...n,...i}}return{payload:n}}catch(n){const i=g.asCrossauthError(n);return d.logger.debug(l({err:i})),d.logger.error(l({msg:"Couldn't get user info",cerr:i})),o=i.oauthErrorCode,s="Couldn't get user info: "+i.message,{error:o,error_description:s}}}async getAccessPayload(e,t){let o,s;try{let n;return n=await this.validateAccessToken(e,t),n?{payload:n}:(o="access_denied",s="Invalid access token received",{error:o,error_description:s})}catch(n){const i=g.asCrossauthError(n);return d.logger.debug(l({err:i})),d.logger.error(l({msg:"Couldn't get user info",cerr:i})),o=i.oauthErrorCode,s="Couldn't get user info: "+i.message,{error:o,error_description:s}}}async redirectEndpoint({code:e,scope:t,codeVerifier:o,error:s,errorDescription:n}){var i,a;if(this.oidcConfig||await this.loadConfig(),s||!e)return s||(s="server_error"),n||(n="Unknown error"),{error:s,error_description:n};if(this.authzCode=e,!((i=this.oidcConfig)!=null&&i.grant_types_supported.includes("authorization_code")))return{error:"invalid_request",error_description:"Server does not support authorization code grant"};if(!((a=this.oidcConfig)!=null&&a.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const c=this.oidcConfig.token_endpoint;let h,p;h="authorization_code",p=w(this,A);let _={grant_type:h,client_id:w(this,S),code:this.authzCode,redirect_uri:this.redirect_uri};t&&(_.scope=t),p&&(_.client_secret=p),o&&(_.code_verifier=o);try{let b=await this.post(c,_,this.authServerHeaders);if(b.id_token){const X=await this.getIdPayload(b.id_token,b.access_token);if(X.error)return X;b.id_payload=X.payload}return b}catch(b){return d.logger.error(l({err:b})),{error:"server_error",error_description:"Unable to get access token from server"}}}async clientCredentialsFlow(e){var t,o;if(d.logger.debug(l({msg:"Starting client credentials flow"})),this.oidcConfig||await this.loadConfig(),!((t=this.oidcConfig)!=null&&t.grant_types_supported.includes("client_credentials")))return{error:"invalid_request",error_description:"Server does not support client credentials grant"};if(!((o=this.oidcConfig)!=null&&o.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};if(!w(this,S))return{error:"invalid_request",error_description:"Cannot make client credentials flow without client id"};const s=this.oidcConfig.token_endpoint;let n={grant_type:"client_credentials",client_id:w(this,S),client_secret:w(this,A)};e&&(n.scope=e);try{let i=await this.post(s,n,this.authServerHeaders);if(i.id_token){const a=await this.getIdPayload(i.id_token,i.access_token);if(a.error)return a;i.id_payload=a.payload}return i}catch(i){return d.logger.error(l({err:i})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async passwordFlow(e,t,o){var s,n;if(d.logger.debug(l({msg:"Starting password flow"})),this.oidcConfig||await this.loadConfig(),!((s=this.oidcConfig)!=null&&s.grant_types_supported.includes("password")))return{error:"invalid_request",error_description:"Server does not support password grant"};if(!((n=this.oidcConfig)!=null&&n.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const i=this.oidcConfig.token_endpoint;let a={grant_type:"password",client_id:w(this,S),client_secret:w(this,A),username:e,password:t};o&&(a.scope=o);try{let c=await this.post(i,a,this.authServerHeaders);if(c.id_token){const h=await this.getIdPayload(c.id_token,c.access_token);if(h.error)return h;c.id_payload=h.payload}return c}catch(c){return d.logger.error(l({err:c})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async mfaAuthenticators(e){var t,o,s;if(d.logger.debug(l({msg:"Getting valid MFA authenticators"})),this.oidcConfig||await this.loadConfig(),!((t=this.oidcConfig)!=null&&t.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp"))&&(o=this.oidcConfig)!=null&&o.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-oob"))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((s=this.oidcConfig)!=null&&s.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const n=this.oidcConfig.issuer+(this.oidcConfig.issuer.endsWith("/")?"":"/")+"mfa/authenticators",i=await this.get(n,{authorization:"Bearer "+e,...this.authServerHeaders});if(!Array.isArray(i))return{error:"server_error",error_description:"Expected array of authenticators in mfa/authenticators response"};let a=[];for(let c=0;c<i.length;++c){const h=i[c];if(!h.id||!h.authenticator_type||!h.active)return{error:"server_error",error_description:"Invalid mfa/authenticators response"};a.push({id:h.id,authenticator_type:h.authenticator_type,active:h.active,name:h.name,oob_channel:h.oob_channel})}return{authenticators:a}}async mfaOtpRequest(e,t){var o,s;if(d.logger.debug(l({msg:"Making MFA OTB request"})),this.oidcConfig||await this.loadConfig(),!((o=this.oidcConfig)!=null&&o.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((s=this.oidcConfig)!=null&&s.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const n=this.oidcConfig.issuer+(this.oidcConfig.issuer.endsWith("/")?"":"/")+"mfa/challenge",i=await this.post(n,{client_id:w(this,S),client_secret:w(this,A),challenge_type:"otp",mfa_token:e,authenticator_id:t},this.authServerHeaders);return i.challenge_type!="otp"?{error:i.error??"server_error",error_description:i.error_description??"Invalid OTP challenge response"}:i}async mfaOtpComplete(e,t,o){var s,n;if(d.logger.debug(l({msg:"Completing MFA OTP request"})),this.oidcConfig||await this.loadConfig(),!((s=this.oidcConfig)!=null&&s.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((n=this.oidcConfig)!=null&&n.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const i=this.oidcConfig.token_endpoint,a=await this.post(i,{grant_type:"http://auth0.com/oauth/grant-type/mfa-otp",client_id:w(this,S),client_secret:w(this,A),challenge_type:"otp",mfa_token:e,otp:t,scope:o},this.authServerHeaders);if(a.id_token){const c=await this.getIdPayload(a.id_token,a.access_token);if(c.error)return c;a.id_payload=c.payload}return{id_token:a.id_token,access_token:a.access_token,refresh_token:a.refresh_token,expires_in:Number(a.expires_in),scope:a.scope,token_type:a.token_type,error:a.error,error_description:a.error_description}}async mfaOobRequest(e,t){var o,s;if(d.logger.debug(l({msg:"Making MFA OOB request"})),this.oidcConfig||await this.loadConfig(),!((o=this.oidcConfig)!=null&&o.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((s=this.oidcConfig)!=null&&s.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const n=this.oidcConfig.issuer+(this.oidcConfig.issuer.endsWith("/")?"":"/")+"mfa/challenge",i=await this.post(n,{client_id:w(this,S),client_secret:w(this,A),challenge_type:"oob",mfa_token:e,authenticator_id:t},this.authServerHeaders);return i.challenge_type!="oob"||!i.oob_code||!i.binding_method?{error:i.error??"server_error",error_description:i.error_description??"Invalid OOB challenge response"}:{challenge_type:i.challenge_type,oob_code:i.oob_code,binding_method:i.binding_method,error:i.error,error_description:i.error_description}}async mfaOobComplete(e,t,o,s){var n,i;if(d.logger.debug(l({msg:"Completing MFA OOB request"})),this.oidcConfig||await this.loadConfig(),!((n=this.oidcConfig)!=null&&n.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-oob")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((i=this.oidcConfig)!=null&&i.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const a=this.oidcConfig.token_endpoint,c=await this.post(a,{grant_type:"http://auth0.com/oauth/grant-type/mfa-oob",client_id:w(this,S),client_secret:w(this,A),challenge_type:"otp",mfa_token:e,oob_code:t,binding_code:o,scope:s},this.authServerHeaders);if(c.error)return{error:c.error,error_description:c.error_description};if(c.id_token){const h=await this.getIdPayload(c.id_token,c.access_token);if(h.error)return h;c.id_payload=h.payload}return{id_token:c.id_token,access_token:c.access_token,refresh_token:c.refresh_token,expires_in:"expires_in"in c?Number(c.expires_in):void 0,scope:c.scope,token_type:c.token_type}}async refreshTokenFlow(e){var t,o;if(d.logger.debug(l({msg:"Starting refresh token flow"})),this.oidcConfig||await this.loadConfig(),!((t=this.oidcConfig)!=null&&t.grant_types_supported.includes("refresh_token")))return{error:"invalid_request",error_description:"Server does not support refresh_token grant"};if(!((o=this.oidcConfig)!=null&&o.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const s=this.oidcConfig.token_endpoint;let n;n=w(this,A);let i={grant_type:"refresh_token",refresh_token:e,client_id:w(this,S)};n&&(i.client_secret=n);try{let a=await this.post(s,i,this.authServerHeaders);if(a.id_token){const c=await this.getIdPayload(a.id_token,a.access_token);if(c.error)return c;a.id_payload=c.payload}return a}catch(a){return d.logger.error(l({err:a})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async startDeviceCodeFlow(e,t){var o;if(d.logger.debug(l({msg:"Starting device code flow"})),this.oidcConfig||await this.loadConfig(),!((o=this.oidcConfig)!=null&&o.grant_types_supported.includes("urn:ietf:params:oauth:grant-type:device_code")))return{error:"invalid_request",error_description:"Server does not support device code grant"};let s={grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:w(this,S),client_secret:w(this,A)};t&&(s.scope=t);try{let n=await this.post(e,s,this.authServerHeaders);return n.id_token&&!await this.validateIdToken(n.id_token)?{error:"access_denied",error_description:"Invalid ID token"}:n}catch(n){return d.logger.error(l({err:n})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async pollDeviceCodeFlow(e){var t,o,s;if(d.logger.debug(l({msg:"Starting device code flow"})),this.oidcConfig||await this.loadConfig(),!((t=this.oidcConfig)!=null&&t.grant_types_supported.includes("urn:ietf:params:oauth:grant-type:device_code")))return{error:"invalid_request",error_description:"Server does not support device code grant"};if(!((o=this.oidcConfig)!=null&&o.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};let n={grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:w(this,S),client_secret:w(this,A),device_code:e};try{const i=await this.post((s=this.oidcConfig)==null?void 0:s.token_endpoint,n,this.authServerHeaders);if(i.error)return i;if(i.id_token){const a=await this.getIdPayload(i.id_token,i.access_token);if(a.error)return a;i.id_payload=a.payload}return i}catch(i){return d.logger.error(l({err:i})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async userInfoEndpoint(e){var t;if(!((t=this.oidcConfig)!=null&&t.userinfo_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const o=this.oidcConfig.userinfo_endpoint;return await this.post(o,{},{authorization:"Bearer "+e})}async post(e,t,o={},s){d.logger.debug(l({msg:"Fetch POST",url:e,params:Object.keys(t)}));let n={};this.authServerCredentials&&(n.credentials=this.authServerCredentials),this.authServerMode&&(n.mode=this.authServerMode);let i="",a="";if(this.oauthPostType=="json")i=JSON.stringify(t),a="application/json";else{i="";for(let p in t)i!=""&&(i+="&"),i+=encodeURIComponent(p)+"="+encodeURIComponent(t[p]);a="application/x-www-form-urlencoded"}this.oauthLogFetch&&d.logger.debug(l({msg:"OAuth fetch",method:"POST",url:e,body:i}));let c={};s&&(c=s);const h=await fetch(e,{method:"POST",...n,headers:{Accept:"application/json","Content-Type":a,...o},...c,body:i});try{const p=await h.clone().json();return this.oauthLogFetch&&d.logger.debug(l({msg:"OAuth fetch response",body:JSON.stringify(p)})),await h.json(),p}catch(p){let _=g.asCrossauthError(p);throw i=await h.text(),d.logger.debug(l({msg:"Response is not JSON",response:i})),_}}async get(e,t={}){d.logger.debug(l({msg:"Fetch GET",url:e}));let o={};this.authServerCredentials&&(o.credentials=this.authServerCredentials),this.authServerMode&&(o.mode=this.authServerMode),this.oauthLogFetch&&d.logger.debug(l({msg:"OAuth fetch",method:"GET",url:e}));const s=await(await fetch(e,{method:"GET",...o,headers:{Accept:"application/json",...t}})).json();return this.oauthLogFetch&&d.logger.debug(l({msg:"OAuth fetch response",body:JSON.stringify(s)})),s}async validateIdToken(e){try{return await this.tokenConsumer.tokenAuthorized(e,"id")}catch{return}}async validateAccessToken(e,t){try{return await this.tokenConsumer.tokenAuthorized(e,"access",t)}catch{return}}async idTokenAuthorized(e,t){try{return await this.tokenConsumer.tokenAuthorized(e,"id",t)}catch(o){d.logger.warn(l({err:o}));return}}getTokenPayload(e){return Tr(e)}}S=new WeakMap,A=new WeakMap;class br{constructor(e,t={}){if(u(this,"audience"),u(this,"jwtKeyType"),u(this,"jwtSecretKey"),u(this,"jwtPublicKey"),u(this,"clockTolerance",10),u(this,"authServerBaseUrl",""),u(this,"oidcConfig"),u(this,"keys",{}),this.audience=e,t.authServerBaseUrl&&(this.authServerBaseUrl=t.authServerBaseUrl),t.jwtKeyType&&(this.jwtKeyType=t.jwtKeyType),t.jwtSecretKey&&(this.jwtSecretKey=t.jwtSecretKey),t.jwtPublicKey&&(this.jwtPublicKey=t.jwtPublicKey),t.clockTolerance&&(this.clockTolerance=t.clockTolerance),t.oidcConfig&&(this.oidcConfig=t.oidcConfig),this.jwtPublicKey&&!this.jwtKeyType)throw new g(m.Configuration,"If specifying jwtPublic key, must also specify jwtKeyType")}async loadKeys(e){try{if(this.jwtSecretKey){if(!this.jwtKeyType)throw new g(m.Configuration,"Must specify jwtKeyType if setting jwtSecretKey");this.keys._default=await pr(this.jwtSecretKey,this.jwtKeyType)}else if(this.jwtPublicKey){if(!this.jwtKeyType)throw new g(m.Configuration,"Must specify jwtKeyType if setting jwtPublicKey");const t=await gr(this.jwtPublicKey,this.jwtKeyType);this.keys._default=t}else{if(this.oidcConfig||await this.loadConfig(),!this.oidcConfig)throw new g(m.Connection,"Load OIDC config before Jwks");await this.loadJwks(void 0,e)}}catch(t){throw d.logger.debug(l({err:t})),new g(m.Connection,"Couldn't load keys")}}async loadConfig(e){if(e){this.oidcConfig=e;return}if(!this.authServerBaseUrl)throw new g(m.Connection,"Couldn't get OIDC configuration. Either set authServerBaseUrl or set config manually");let t;try{let o=this.authServerBaseUrl;o.endsWith("/")||(o+="/"),t=await fetch(new URL(".well-known/openid-configuration",o))}catch(o){d.logger.error(l({err:o}))}if(!t||!t.ok)throw new g(m.Connection,"Couldn't get OIDC configuration");this.oidcConfig={...Te};try{const o=await t.json();for(const[s,n]of Object.entries(o))this.oidcConfig[s]=n}catch{throw new g(m.Connection,"Unrecognized response from OIDC configuration endpoint")}}async loadJwks(e,t){if(e){this.keys={};for(let o=0;o<e.keys.length;++o){const s=e.keys[o],n="kid"in s&&s.kid?s.kid:"_default";this.keys[n]=await le(e.keys[o])}}else{if(!this.oidcConfig)throw new g(m.Connection,"Load OIDC config before Jwks");let o;try{o=await fetch(new URL(this.oidcConfig.jwks_uri))}catch(s){d.logger.error(l({err:s}))}if(!o||!o.ok)throw new g(m.Connection,"Couldn't get OIDC configuration");this.keys={};try{const s=await o.json();if(!("keys"in s)||!Array.isArray(s.keys))throw new g(m.Connection,"Couldn't fetch keys");for(let n=0;n<s.keys.length;++n)try{let i="_default",a={...s.keys[n]};if("kid"in a&&typeof a.kid=="string"&&(i=String(a.kid)),a&&!a.alg&&!a.jwk_alg&&t)if(t.startsWith("RS")&&a.kty=="RSA")a.alg=t;else{d.logger.debug(l({msg:"Skipping key with "+a.kty}));continue}const c=await le(a);this.keys[i]=c}catch(i){throw d.logger.error(l({err:i})),new g(m.Connection,"Couldn't load keys")}}catch(s){throw d.logger.error(l({err:s})),new g(m.Connection,"Unrecognized response from OIDC jwks endpoint")}}}async tokenAuthorized(e,t,o){if(!this.keys||Object.keys(this.keys).length==0){const n=_e(e);await this.loadKeys(n.alg)}const s=await this.validateToken(e);if(s){if(s.iss!=this.authServerBaseUrl){const n=s.jti?s.jti:s.sid?s.sid:"";d.logger.error(l({msg:`Invalid issuer ${s.iss} ${t} token`,hashedAccessToken:await this.hash(n)}));return}if(o!=!1&&s.aud){const n=s.jti?s.jti:s.sid?s.sid:"";if(Array.isArray(s.aud)&&!s.aud.includes(this.audience)||!Array.isArray(s.aud)&&s.aud!=this.audience){d.logger.error(l({msg:`Invalid audience ${s.aud} in ${t} token`,hashedAccessToken:await this.hash(n)}));return}}return s}}async validateToken(e){(!this.keys||Object.keys(this.keys).length==0)&&d.logger.warn("No keys loaded so cannot validate tokens");let t;try{t=_e(e).kid}catch{d.logger.warn(l({msg:"Invalid access token format"}));return}let o;for(let s in this.keys)if(t==s){o=this.keys[s];break}if(!o&&"_default"in this.keys&&(o=this.keys._default),!o){d.logger.warn(l({msg:"No matching keys found for access token"}));return}try{const{payload:s}=await Sr(e,o),n=JSON.parse(new TextDecoder().decode(s));if(n.exp*1e3<Date.now()+this.clockTolerance){d.logger.warn(l({msg:"Access token has expired"}));return}return n}catch(s){const n=g.asCrossauthError(s);d.logger.debug(l({err:n})),d.logger.warn(l({msg:"Access token did not validate",cerr:n}));return}}}const ke=30,se=2,de=30;class ue{constructor(e){f(this,"autoRefreshUrl","/autorefresh");f(this,"csrfHeader","X-CROSSAUTH-CSRF");f(this,"headers",{});f(this,"autoRefreshActive",!1);f(this,"mode","cors");f(this,"credentials","same-origin");f(this,"tokenProvider");this.tokenProvider=e.tokenProvider,this.autoRefreshUrl=e.autoRefreshUrl,e.csrfHeader&&(this.csrfHeader=e.csrfHeader),e.headers&&(this.headers=e.headers),e.mode&&(this.mode=e.mode),e.credentials&&(this.credentials=e.credentials)}async startAutoRefresh(e=["access","id"],t){if(!this.autoRefreshActive){this.autoRefreshActive=!0,d.logger.debug(l({msg:"Starting auto refresh"}));try{await this.scheduleAutoRefresh(e,t)}catch(o){const s=g.asCrossauthError(o);d.logger.error(l({cerr:s})),d.logger.debug(l({err:s}))}}}stopAutoRefresh(){this.autoRefreshActive=!1,d.logger.debug(l({msg:"Stopping auto refresh"}))}async scheduleAutoRefresh(e,t){let o;const s=this.tokenProvider.getCsrfToken(),n=s?await s:void 0,i=await this.tokenProvider.getTokenExpiries([...e,"refresh"],n);if(i.refresh==null){d.logger.debug(l({msg:"No refresh token found"}));return}const a=Date.now();let c=i.id;if((!c||i.access&&i.access<c)&&(c=i.access),!c){d.logger.debug(l({msg:"No tokens expire"}));return}let h=c*1e3-a-ke;if(h<0&&o!=null&&o<=0){d.logger.debug(l({msg:"Expiry time has passed"}));return}if(h<0&&(h=0),i.refresh&&i.refresh-ke<h){d.logger.debug(l({msg:"Refresh token has expired"}));return}let p=_=>new Promise(b=>setTimeout(b,_));d.logger.debug(l({msg:`Waiting ${h} before refreshing tokens`})),o=h,await p(h),await this.autoRefresh(e,n,t)}async autoRefresh(e,t,o){if(this.autoRefreshActive){let s,n=!1,i=0;for(;!n&&i<=se;)try{let a={...this.headers};t&&(a[this.csrfHeader]=t),d.logger.debug(l({msg:"Initiating auto refresh"}));const c=await this.tokenProvider.jsonFetchWithToken(this.autoRefreshUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...a},mode:this.mode,credentials:this.credentials,body:{csrfToken:t}},"refresh");c.ok||d.logger.error(l({msg:"Failed auto refreshing tokens",status:c.status}));try{s=await c.json()}catch{try{d.logger.error(l({msg:"/refresh returned a non-JSON response "+(s?await s.text():void 0)}))}catch{d.logger.error(l({msg:"/refresh returned a with no body "}))}s={ok:!1,error:"Unknown"}}if(s!=null&&s.ok){await this.scheduleAutoRefresh(e,o),n=!0;try{await this.tokenProvider.receiveTokens(s)}catch(h){const p=g.asCrossauthError(h);o?o("Couldn't receive tokens",p):(d.logger.debug(l({err:h})),d.logger.error(l({msg:"Error receiving tokens",cerr:p})))}}else i<se?(d.logger.error(l({msg:`Failed auto refreshing tokens. Retrying in ${de} seconds`})),await(p=>new Promise(_=>setTimeout(_,p)))(de*1e3)):(d.logger.error(l({msg:"Failed auto refreshing tokens. Number of retries exceeded"})),o&&o("Failed auto refreshing tokens")),i++}catch(a){const c=g.asCrossauthError(a);d.logger.debug(l({err:c})),i<se?(d.logger.error(l({msg:`Failed auto refreshing tokens. Retrying in ${se} seconds`})),await(p=>new Promise(_=>setTimeout(_,p)))(de*1e3)):(d.logger.error(l({msg:"Failed auto refreshing tokens. Number of retries exceeded"})),o&&o(c.message,c)),i++}}}}class fe{constructor(e){f(this,"deviceCodePollUrl","/devicecodepoll");f(this,"headers",{});f(this,"pollingActive",!1);f(this,"mode","cors");f(this,"credentials","same-origin");f(this,"respectRedirect",!0);f(this,"oauthClient");this.oauthClient=e.oauthClient,e.deviceCodePollUrl!=null&&(this.deviceCodePollUrl=e.deviceCodePollUrl),e.headers&&(this.headers=e.headers),e.mode&&(this.mode=e.mode),e.credentials&&(this.credentials=e.credentials)}async startPolling(e,t,o=5){this.pollingActive||(this.pollingActive=!0,d.logger.debug(l({msg:"Starting auto refresh"})),await this.poll(e,o,t))}stopPolling(){this.pollingActive=!1,d.logger.debug(l({msg:"Stopping auto refresh"}))}async poll(e,t,o){var s;if(!e)d.logger.debug(l({msg:"device code poll: no device code provided"})),o("error","Error waiting for authorization");else try{if(d.logger.debug(l({msg:"device code poll: poll"})),!this.deviceCodePollUrl&&this.oauthClient){if(this.oauthClient.getOidcConfig()||await this.oauthClient.loadConfig(),!((s=this.oauthClient.getOidcConfig())!=null&&s.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-oob")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};let i=this.oauthClient.getOidcConfig();if(!(i!=null&&i.token_endpoint))return{error:"server_error",error_description:"Couldn't get OIDC configuration"};this.deviceCodePollUrl=i.token_endpoint}if(!this.deviceCodePollUrl)return{error:"server_error",error_description:"Must either provide deviceCodePollUrl or an oauthClient to fetch it from"};const n=await fetch(this.deviceCodePollUrl,{method:"POST",body:JSON.stringify({device_code:e}),headers:{"content-type":"application/json"}});if(n.redirected)this.pollingActive=!1,n.redirected&&o("completeAndRedirect",void 0,n.url);else if(!n.ok)this.pollingActive=!1,o("error","Received an error from the authorization server");else{const i=await n.json();if(d.logger.debug(l({msg:"device code poll: received"+JSON.stringify(i)})),i.error=="expired_token")this.pollingActive=!1,o("expired_token","Timeout waiting for authorization");else if(i.error=="authorization_pending"||i.error=="slow_down"){i.error=="slow_down"&&(t+=5);let a=i.interval??t,c=h=>new Promise(p=>setTimeout(p,h));d.logger.debug(l({msg:"device code poll: waiting "+String(a)+" seconds"})),await c(a*1e3),this.pollingActive&&this.poll(e,t,o)}else i.error?(this.pollingActive=!1,o("error",i.error_description??i.error)):(this.pollingActive=!1,o("complete"))}}catch(n){this.pollingActive=!1;const i=g.asCrossauthError(n);d.logger.debug(l({err:i})),d.logger.error(l({msg:"Polling failed",cerr:i})),o("error",i.message)}}}class Ar{constructor(e={}){f(this,"bffPrefix","/bff");f(this,"csrfHeader","X-CROSSAUTH-CSRF");f(this,"enableCsrfProtection",!0);f(this,"headers",{});f(this,"mode","cors");f(this,"credentials","same-origin");f(this,"autoRefresher");f(this,"deviceCodePoller");f(this,"getCsrfTokenUrl","/api/getcsrftoken");f(this,"autoRefreshUrl","/api/refreshtokens");f(this,"tokensUrl","/tokens");e.bffPrefix&&(this.bffPrefix=e.bffPrefix),e.csrfHeader&&(this.csrfHeader=e.csrfHeader),e.enableCsrfProtection!=null&&(this.enableCsrfProtection=e.enableCsrfProtection),e.getCsrfTokenUrl&&(this.getCsrfTokenUrl=e.getCsrfTokenUrl),e.tokensUrl&&(this.tokensUrl=e.tokensUrl),e.autoRefreshUrl&&(this.autoRefreshUrl=e.autoRefreshUrl),this.bffPrefix.endsWith("/")||(this.bffPrefix+="/"),e.headers&&(this.headers=e.headers),e.mode&&(this.mode=e.mode),e.credentials&&(this.credentials=e.credentials),this.autoRefresher=new ue({...e,autoRefreshUrl:this.autoRefreshUrl,tokenProvider:this}),this.deviceCodePoller=new fe({...e,oauthClient:void 0})}async getCsrfToken(){if(this.enableCsrfProtection)try{const t=await(await fetch(this.getCsrfTokenUrl,{headers:this.headers,credentials:this.credentials,mode:this.mode})).json();if(!t.ok)throw g.asCrossauthError(t);return t.csrfToken}catch(e){throw g.asCrossauthError(e)}}async getIdToken(e){const t=await this.getTokens(e);return(t==null?void 0:t.id_token)??null}async haveIdToken(e){const t=await this.getTokens(e);return t==null?!1:t.have_id_token!=null?t.have_id_token:"id_token"in t}async getAccessToken(e){const t=await this.getTokens(e);return(t==null?void 0:t.access_token)??null}async haveAccessToken(e){const t=await this.getTokens(e);return t==null?!1:t.have_access_token!=null?t.have_access_token:"access_token"in t}async getRefreshToken(e){const t=await this.getTokens(e);return(t==null?void 0:t.refresh_token)??null}async haveRefreshToken(e){const t=await this.getTokens(e);return t==null?!1:t.have_refresh_token!=null?t.have_refresh_token:"refresh_token"in t}async api(e,t,o,s){let n={...this.headers};!s&&!["GET","HEAD","OPTIONS"].includes(e)&&(s=await this.getCsrfToken(),s&&(n[this.csrfHeader]=s)),t.startsWith("/")&&(t=t.substring(1));let i={};o&&(i.body=JSON.stringify(o));const a=await fetch(this.bffPrefix+t,{headers:n,method:e,mode:this.mode,credentials:this.credentials,...i});let c=null;return a.body&&(c=await a.json()),{status:a.status,body:c}}async getTokens(e){e||(e=await this.getCsrfToken());let t={...this.headers};e&&(t[this.csrfHeader]=e);try{const o=await fetch(this.tokensUrl,{method:"POST",headers:t,mode:this.mode,credentials:this.credentials});return o.status==204?{}:await o.json()}catch(o){throw g.asCrossauthError(o)}}async startAutoRefresh(e=["access","id"],t){return this.autoRefresher.startAutoRefresh(e,t)}stopAutoRefresh(){return this.autoRefresher.stopAutoRefresh()}async startDeviceCodePolling(e,t,o=5){return this.deviceCodePoller.startPolling(e,t,o)}stopDeviceCodePolling(){return this.deviceCodePoller.stopPolling()}async getTokenExpiries(e,t){const o=await this.getTokens(t);try{const s=e.includes("id")?(o==null?void 0:o.id_token)??null:null,n=e.includes("access")?(o==null?void 0:o.access_token)??null:null,i=e.includes("refresh")?(o==null?void 0:o.refresh_token)??null:null;let a,c,h;return s&&(a=s.exp?s.exp:null),n&&(c=n.exp?n.exp:null),i&&(h=i.exp?i.exp:null),{id:a,access:c,refresh:h}}catch{return d.logger.error(l({msg:"getTokenExpiries received non JSON response "+o})),{id:0,access:0,refresh:0}}}async jsonFetchWithToken(e,t,o){return typeof t.body!="string"&&(t.body=JSON.stringify(t.body)),await fetch(e,t)}receiveTokens(e){return new Promise(t=>{})}}class Rr{getCsrfToken(){return new Promise(e=>{})}}class xe extends br{async hash(e){const o=new TextEncoder().encode(e),s=await crypto.subtle.digest("SHA-256",o),n=Array.from(new Uint8Array(s));return btoa(n.reduce((i,a)=>i+String.fromCharCode(a),"")).replace(/\//g,"_").replace(/\+/g,"-").replace(/=+$/,"")}}var H,W,N,j,J,$,q,Z,ee,V;class Pr extends Er{constructor(t){t.tokenConsumer||(t.tokenConsumer=new xe(t.client_id,{authServerBaseUrl:t.authServerBaseUrl}));super(t);f(this,"resServerBaseUrl","");f(this,"resServerHeaders",{});f(this,"resServerMode","cors");f(this,"resServerCredentials","same-origin");f(this,"accessTokenResponseType","memory");f(this,"refreshTokenResponseType","memory");f(this,"idTokenResponseType","memory");f(this,"accessTokenName","CROSSAUTH_AT");f(this,"refreshTokenName","CROSSAUTH_RT");f(this,"idTokenName","CROSSAUTH_IT");R(this,H);R(this,W);R(this,N);R(this,j);R(this,J);R(this,$);R(this,q);f(this,"autoRefresher");f(this,"deviceCodePoller");f(this,"deviceAuthorizationUrl","device_authorization");R(this,Z);R(this,ee);R(this,V);f(this,"scope");f(this,"logFetch",!1);this.resServerBaseUrl!=null&&(this.resServerBaseUrl=t.resServerBaseUrl??"",this.resServerBaseUrl.length>0&&!this.resServerBaseUrl.endsWith("/")&&(this.resServerBaseUrl+="/")),t.accessTokenResponseType&&(this.accessTokenResponseType=t.accessTokenResponseType),t.idTokenResponseType&&(this.idTokenResponseType=t.idTokenResponseType),t.refreshTokenResponseType&&(this.refreshTokenResponseType=t.refreshTokenResponseType),t.accessTokenName&&(this.accessTokenName=t.accessTokenName),t.idTokenName&&(this.idTokenName=t.idTokenName),t.refreshTokenName&&(this.refreshTokenName=t.refreshTokenName),t.resServerHeaders&&(this.resServerHeaders=t.resServerHeaders),t.resServerMode&&(this.resServerMode=t.resServerMode),t.resServerCredentials&&(this.resServerCredentials=t.resServerCredentials),t.client_id&&T(this,$,t.client_id),t.client_secret&&T(this,q,t.client_secret),t.deviceAuthorizationUrl&&(this.deviceAuthorizationUrl=t.deviceAuthorizationUrl),this.autoRefresher=new ue({...t,autoRefreshUrl:this.authServerBaseUrl+"/token",tokenProvider:this}),this.deviceCodePoller=new fe({...t,oauthClient:this,deviceCodePollUrl:null});let o,s,n;if(this.idTokenResponseType=="sessionStorage"?o=sessionStorage.getItem(this.idTokenName):this.idTokenResponseType=="localStorage"&&(o=localStorage.getItem(this.idTokenName)),this.accessTokenResponseType=="sessionStorage"?s=sessionStorage.getItem(this.accessTokenName):this.accessTokenResponseType=="localStorage"&&(s=localStorage.getItem(this.accessTokenName)),this.refreshTokenResponseType=="sessionStorage"?n=sessionStorage.getItem(this.refreshTokenName):this.refreshTokenResponseType=="localStorage"&&(n=localStorage.getItem(this.refreshTokenName)),this.receiveTokens({access_token:s,id_token:o,refresh_token:n}),s){const i=this.getTokenPayload(s);i&&(T(this,H,s),T(this,j,i))}if(n){const i=this.getTokenPayload(n);i&&(T(this,W,n),T(this,J,i))}o?this.validateIdToken(o).then(i=>{T(this,N,i),t.autoRefresh&&this.startAutoRefresh(t.autoRefresh).then().catch(a=>{d.logger.debug(l({err:a,msg:"Couldn't start auto refresh"}))})}).catch(i=>{d.logger.debug(l({err:i,msg:"Couldn't validate ID token"}))}):y(this,H)&&t.autoRefresh&&n?this.startAutoRefresh(t.autoRefresh).then().catch(i=>{d.logger.debug(l({err:i,msg:"Couldn't start auto refresh"}))}):n&&!s&&this.refreshTokenFlow(n).then(i=>{d.logger.debug(l({msg:"Refreshed tokens"})),t.autoRefresh&&this.startAutoRefresh(t.autoRefresh).then().catch(a=>{d.logger.debug(l({err:a,msg:"Couldn't start auto refresh"}))})}).catch(i=>{const a=g.asCrossauthError(i);d.logger.debug(l({err:a})),d.logger.error(l({msg:"failed refreshing tokens",cerr:a}))})}get idTokenPayload(){return y(this,N)}async handleRedirectUri(){const t=new URL(window.location.href);if(t.origin+t.pathname!=this.redirect_uri)return;const o=new URLSearchParams(window.location.search);let s,n,i,a;for(const[h,p]of o)h=="code"&&(s=p),h=="state"&&(n=p),h=="error"&&(i=p),h=="error_description"&&(a=p);if(!i&&!s)return;if(i){const h=g.fromOAuthError(i,a);throw d.logger.debug(l({err:h})),d.logger.error(l({cerr:h,msg:"Error from authorize endpoint: "+i})),h}if(y(this,V)&&n!=y(this,V))return{error:"access_denied",error_description:"Invalid state"};const c=await this.redirectEndpoint({code:s,scope:this.scope,codeVerifier:y(this,ee),error:i,errorDescription:a});if(c.error){const h=g.fromOAuthError(c.error,a);throw d.logger.debug(l({err:h})),d.logger.error(l({cerr:h,msg:"Error from redirect endpoint: "+c.error})),h}return await this.receiveTokens(c),c}async startAutoRefresh(t=["access","id"],o){return this.autoRefresher.startAutoRefresh(t,o)}stopAutoRefresh(){return this.autoRefresher.stopAutoRefresh()}async startDeviceCodePolling(t,o,s=5){return this.deviceCodePoller.startPolling(t,o,s)}stopDeviceCodePolling(){return this.deviceCodePoller.stopPolling()}getIdToken(){return y(this,N)}randomValue(t){const o=new Uint8Array(t);return self.crypto.getRandomValues(o),btoa(o.reduce((s,n)=>s+String.fromCharCode(n),"")).replace(/\//g,"_").replace(/\+/g,"-").replace(/=+$/,"")}async sha256(t){const s=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",s),i=Array.from(new Uint8Array(n));return btoa(i.reduce((a,c)=>a+String.fromCharCode(c),"")).replace(/\//g,"_").replace(/\+/g,"-").replace(/=+$/,"")}async api(t,o,s){let n={...this.resServerHeaders};o.startsWith("/")&&(o=o.substring(1));let i={};s&&(i.body=JSON.stringify(s));let a;this.accessTokenResponseType=="sessionStorage"?a=sessionStorage.getItem(this.accessTokenName):this.accessTokenResponseType=="localStorage"&&(a=localStorage.getItem(this.accessTokenName)),n.authorization="Bearer "+a;const c=await fetch(this.resServerBaseUrl+o,{headers:n,method:t,mode:this.resServerMode,credentials:this.resServerCredentials,...i});let h=null;return c.body&&(h=await c.json()),{status:c.status,body:h}}async getTokenExpiries(t,o){let s,n,i;return y(this,N)&&(s=y(this,N).exp?y(this,N).exp:null),y(this,j)&&(n=y(this,j).exp?y(this,j).exp:null),y(this,J)&&(i=y(this,J).exp?y(this,J).exp:null),{id:s,access:n,refresh:i}}async jsonFetchWithToken(t,o,s){if(s=="access"){if(!y(this,H))throw new g(m.InvalidToken,"Cannot make fetch with access token - no access token defined");o.headers||(o.headers={}),o.headers.authorization="Bearer "+y(this,H)}else{if(o.body||(o.body={}),!y(this,W))throw new g(m.InvalidToken,"Cannot make fetch with refresh token - no refresh token defined");o.body.refresh_token=y(this,W),o.body.grant_type="refresh_token"}return y(this,$)&&(o.body||(o.body={}),o.body.client_id=y(this,$),y(this,q)&&(o.body.client_secret=y(this,q))),typeof o.body!="string"&&(o.body=JSON.stringify(o.body)),await fetch(t,o)}async getCsrfToken(){}async receiveTokens(t){if(t.access_token){const o=this.getTokenPayload(t.access_token);o&&(T(this,H,t.access_token),T(this,j,o)),this.accessTokenResponseType=="localStorage"?localStorage.setItem(this.accessTokenName,t.access_token):this.accessTokenResponseType=="sessionStorage"&&sessionStorage.setItem(this.accessTokenName,t.access_token)}if(t.refresh_token){const o=this.getTokenPayload(t.refresh_token);o&&(T(this,W,t.refresh_token),T(this,J,o)),this.refreshTokenResponseType=="localStorage"?localStorage.setItem(this.refreshTokenName,t.refresh_token):this.accessTokenResponseType=="sessionStorage"&&sessionStorage.setItem(this.refreshTokenName,t.refresh_token)}if(t.id_token){const o=await this.validateIdToken(t.id_token);T(this,N,o),this.idTokenResponseType=="localStorage"?localStorage.setItem(this.idTokenName,t.id_token):this.idTokenResponseType=="sessionStorage"&&sessionStorage.setItem(this.idTokenName,t.id_token)}}async clientCredentialsFlow(t){const o=await super.clientCredentialsFlow(t);return await this.receiveTokens(o),o}async passwordFlow(t,o,s){const n=await super.passwordFlow(t,o,s);return await this.receiveTokens(n),n}async deviceCodeFlow(t){let o=this.authServerBaseUrl;return o.endsWith("/")||(o+="/"),o+=this.deviceAuthorizationUrl,await super.startDeviceCodeFlow(o,t)}async mfaOtpComplete(t,o){const s=await super.mfaOtpComplete(t,o);return await this.receiveTokens(s),s}async mfaOobComplete(t,o,s){const n=await super.mfaOobComplete(t,o,s);return await this.receiveTokens(n),n}async refreshTokenFlow(t){if(!t)if(y(this,W))t=y(this,W);else throw new g(m.InvalidToken,"Cannot refresh tokens: no refresh token present");const o=await super.refreshTokenFlow(t);return await this.receiveTokens(o),o}async authorizationCodeFlow(t,o=!1){const s=this.randomValue(this.stateLength);if(this.scope=t,o){const i=await this.codeChallengeAndVerifier();T(this,Z,i.codeChallenge),T(this,ee,i.codeVerifier),T(this,V,s)}const n=await super.startAuthorizationCodeFlow(s,{scope:t,codeChallenge:y(this,Z),pkce:o});if(n.error||!n.url){const i=g.fromOAuthError(n.error??"Couldn't create URL for authorization code flow",n.error_description);throw d.logger.debug(l({err:i})),i}location.href=n.url}}H=new WeakMap,W=new WeakMap,N=new WeakMap,j=new WeakMap,J=new WeakMap,$=new WeakMap,q=new WeakMap,Z=new WeakMap,ee=new WeakMap,V=new WeakMap;exports.CrossauthError=g;exports.CrossauthLogger=d;exports.OAuthAutoRefresher=ue;exports.OAuthBffClient=Ar;exports.OAuthClient=Pr;exports.OAuthDeviceCodePoller=fe;exports.OAuthTokenConsumer=xe;exports.OAuthTokenProvider=Rr;exports.j=l;
@@ -1 +1 @@
1
- var crossauth_frontend=function(p){"use strict";var Pr=Object.defineProperty;var De=p=>{throw TypeError(p)};var Ir=(p,v,C)=>v in p?Pr(p,v,{enumerable:!0,configurable:!0,writable:!0,value:C}):p[v]=C;var f=(p,v,C)=>Ir(p,typeof v!="symbol"?v+"":v,C),xe=(p,v,C)=>v.has(p)||De("Cannot "+C);var y=(p,v,C)=>(xe(p,v,"read from private field"),C?C.call(p):v.get(p)),U=(p,v,C)=>v.has(p)?De("Cannot add the same private member more than once"):v instanceof WeakSet?v.add(p):v.set(p,C),A=(p,v,C,se)=>(xe(p,v,"write to private field"),se?se.call(p,C):v.set(p,C),C);var L,D,H,F,M,X,Q,te,oe,Z;var v=Object.defineProperty,C=r=>{throw TypeError(r)},se=(r,e,t)=>e in r?v(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,u=(r,e,t)=>se(r,typeof e!="symbol"?e+"":e,t),me=(r,e,t)=>e.has(r)||C("Cannot "+t),m=(r,e,t)=>(me(r,e,"read from private field"),e.get(r)),ve=(r,e,t)=>e.has(r)?C("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),ne=(r,e,t,o)=>(me(r,e,"write to private field"),e.set(r,t),t);class j{}u(j,"active","active"),u(j,"disabled","disabled"),u(j,"awaitingTwoFactorSetup","awaitingtwofactorsetup"),u(j,"awaitingTwoFactorSetupAndEmailVerification","awaitingtwofactorsetupandemailverification"),u(j,"awaitingEmailVerification","awaitingemailverification"),u(j,"passwordChangeNeeded","passwordchangeneeded"),u(j,"passwordResetNeeded","passwordresetneeded"),u(j,"factor2ResetNeeded","factor2resetneeded"),u(j,"passwordAndFactor2ResetNeeded","passwordandfactor2resetneeded");class K{}u(K,"session","s:"),u(K,"passwordResetToken","p:"),u(K,"emailVerificationToken","e:"),u(K,"apiKey","api:"),u(K,"authorizationCode","authz:"),u(K,"accessToken","access:"),u(K,"refreshToken","refresh:"),u(K,"mfaToken","omfa:"),u(K,"deviceCode","dc:"),u(K,"userCode","uc:");var _=(r=>(r[r.UserNotExist=0]="UserNotExist",r[r.PasswordInvalid=1]="PasswordInvalid",r[r.EmailNotExist=2]="EmailNotExist",r[r.UsernameOrPasswordInvalid=3]="UsernameOrPasswordInvalid",r[r.InvalidClientId=4]="InvalidClientId",r[r.ClientExists=5]="ClientExists",r[r.InvalidClientSecret=6]="InvalidClientSecret",r[r.InvalidClientIdOrSecret=7]="InvalidClientIdOrSecret",r[r.InvalidRedirectUri=8]="InvalidRedirectUri",r[r.InvalidOAuthFlow=9]="InvalidOAuthFlow",r[r.UserNotActive=10]="UserNotActive",r[r.EmailNotVerified=11]="EmailNotVerified",r[r.TwoFactorIncomplete=12]="TwoFactorIncomplete",r[r.Unauthorized=13]="Unauthorized",r[r.UnauthorizedClient=14]="UnauthorizedClient",r[r.InvalidScope=15]="InvalidScope",r[r.InsufficientScope=16]="InsufficientScope",r[r.InsufficientPriviledges=17]="InsufficientPriviledges",r[r.Forbidden=18]="Forbidden",r[r.InvalidKey=19]="InvalidKey",r[r.InvalidCsrf=20]="InvalidCsrf",r[r.InvalidSession=21]="InvalidSession",r[r.Expired=22]="Expired",r[r.Connection=23]="Connection",r[r.InvalidHash=24]="InvalidHash",r[r.UnsupportedAlgorithm=25]="UnsupportedAlgorithm",r[r.KeyExists=26]="KeyExists",r[r.PasswordChangeNeeded=27]="PasswordChangeNeeded",r[r.PasswordResetNeeded=28]="PasswordResetNeeded",r[r.Factor2ResetNeeded=29]="Factor2ResetNeeded",r[r.Configuration=30]="Configuration",r[r.InvalidEmail=31]="InvalidEmail",r[r.InvalidPhoneNumber=32]="InvalidPhoneNumber",r[r.InvalidUsername=33]="InvalidUsername",r[r.PasswordMatch=34]="PasswordMatch",r[r.InvalidToken=35]="InvalidToken",r[r.MfaRequired=36]="MfaRequired",r[r.PasswordFormat=37]="PasswordFormat",r[r.DataFormat=38]="DataFormat",r[r.FetchError=39]="FetchError",r[r.UserExists=40]="UserExists",r[r.FormEntry=41]="FormEntry",r[r.BadRequest=42]="BadRequest",r[r.AuthorizationPending=43]="AuthorizationPending",r[r.SlowDown=44]="SlowDown",r[r.ExpiredToken=45]="ExpiredToken",r[r.ConstraintViolation=46]="ConstraintViolation",r[r.NotImplemented=47]="NotImplemented",r[r.UnknownError=48]="UnknownError",r))(_||{});class g extends Error{constructor(e,t=void 0){let o,i=500;e==0?(o="User does not exist",i=401):e==1?(o="Password doesn't match",i=401):e==3?(o="Username or password incorrect",i=401):e==4?(o="Client id is invalid",i=401):e==5?(o="Client ID or name already exists",i=500):e==6?(o="Client secret is invalid",i=401):e==7?(o="Client id or secret is invalid",i=401):e==8?(o="Redirect Uri is not registered",i=401):e==9?(o="Invalid OAuth flow type",i=500):e==2?(o="No user exists with that email address",i=401):e==10?(o="Account is not active",i=403):e==33?(o="Username is not in an allowed format",i=400):e==31?(o="Email is not in an allowed format",i=400):e==32?(o="Phone number is not in an allowed format",i=400):e==11?(o="Email address has not been verified",i=403):e==12?(o="Two-factor setup is not complete",i=403):e==13?(o="Not authorized",i=401):e==14?(o="Client not authorized",i=401):e==15?(o="Invalid scope",i=403):e==16?(o="Insufficient scope",i=403):e==23?o="Connection failure":e==22?(o="Token has expired",i=401):e==24?o="Hash is not in a valid format":e==19?(o="Key is invalid",i=401):e==18?(o="You do not have permission to access this resource",i=403):e==17?(o="You do not have the right privileges to access this resource",i=401):e==20?(o="CSRF token is invalid",i=401):e==21?(o="Session cookie is invalid",i=401):e==25?o="Algorithm not supported":e==26?o="Attempt to create a key that already exists":e==27?(o="User must change password",i=403):e==28?(o="User must reset password",i=403):e==29?(o="User must reset 2FA",i=403):e==30?o="There was an error in the configuration":e==34?(o="Passwords do not match",i=401):e==35?(o="Token is not valid",i=401):e==36?(o="MFA is required",i=401):e==37?(o="Password format was incorrect",i=401):e==40?(o="User already exists",i=400):e==42?(o="The request is invalid",i=400):e==38?(o="Session data has unexpected format",i=500):e==39?(o="Couldn't execute a fetch",i=500):e==43?(o="Waiting for authorization",i=200):e==44?(o="Slow polling down by 5 seconds",i=200):e==45?(o="Token has expired",i=401):e==46?(o="Database update/insert caused a constraint violation",i=500):e==47?(o="This method has not been implemented",i=500):(o="Unknown error",i=500),t!=null&&!Array.isArray(t)?o=t:Array.isArray(t)&&(o=t.join(". ")),super(o),u(this,"isCrossauthError",!0),u(this,"httpStatus"),u(this,"code"),u(this,"codeName"),u(this,"messages"),this.code=e,this.codeName=_[e],this.httpStatus=i,this.name="CrossauthError",Array.isArray(t)?this.messages=t:this.messages=[o],Object.setPrototypeOf(this,g.prototype)}static fromOAuthError(e,t){let o;switch(e){case"invalid_request":o=42;break;case"unauthorized_client":o=14;break;case"access_denied":o=13;break;case"unsupported_response_type":o=42;break;case"invalid_scope":o=15;break;case"server_error":o=48;break;case"temporarily_unavailable":o=23;break;case"invalid_token":o=35;break;case"expired_token":o=45;break;case"insufficient_scope":o=35;break;case"mfa_required":o=36;break;case"authorization_pending":o=43;break;case"slow_down":o=44;break;default:o=48}return new g(o,t)}get oauthErrorCode(){switch(this.code){case 42:return"invalid_request";case 14:return"unauthorized_client";case 13:return"access_denied";case 15:return"invalid_scope";case 23:return"temporarily_unavailable";case 35:return"invalid_token";case 36:return"mfa_required";case 43:return"authorization_pending";case 44:return"slow_down";case 45:return"expired_token";case 22:return"expired_token";default:return"server_error"}}static asCrossauthError(e,t){if(e instanceof Error)return"isCrossauthError"in e?e:new g(48,e.message);if("errorCode"in e){let i=48;try{i=Number(e.errorCode)??48}catch{}let n=t??_[i];return"errorMessage"in e?n=e.errorMessage:"message"in e&&(n=e.message),new g(i,n)}let o=t??_[48];return"message"in e&&(o=e.message),new g(48,o)}}const B=class N{constructor(e){if(u(this,"level"),e)this.level=e;else if(typeof process<"u"&&"CROSSAUTH_LOG_LEVEL"in process.env){const t=(process.env.CROSSAUTH_LOG_LEVEL??"ERROR").toUpperCase();N.levelName.includes(t)?this.level=N.levelName.indexOf(t):this.level=N.Error}else this.level=N.Error}static get logger(){return globalThis.crossauthLogger}setLevel(e){this.level=e}log(e,t){e<=this.level&&(typeof t=="string"?console.log("Crossauth "+N.levelName[e]+" "+new Date().toISOString(),t):console.log(JSON.stringify({level:N.levelName[e],time:new Date().toISOString(),...t})))}error(e){this.log(N.Error,e)}warn(e){this.log(N.Warn,e)}info(e){this.log(N.Info,e)}debug(e){this.log(N.Debug,e)}static setLogger(e,t){globalThis.crossauthLogger=e,globalThis.crossauthLoggerAcceptsJson=t}};u(B,"None",0),u(B,"Error",1),u(B,"Warn",2),u(B,"Info",3),u(B,"Debug",4),u(B,"levelName",["NONE","ERROR","WARN","INFO","DEBUG"]);let d=B;function l(r){let e;typeof r=="object"&&"err"in r&&typeof r.err=="object"&&(e=r.err.stack);try{typeof r=="object"&&"err"in r&&typeof r.err=="object"&&r.err&&"message"in r.err&&!("msg"in r)&&(r.msg=r.err.message)}catch{}try{typeof r=="object"&&"err"in r&&typeof r.err=="object"&&(r.err={...r.err,stack:e})}catch{}try{typeof r=="object"&&"err"in r&&!("msg"in r)&&(r.msg=r.msg="An unknown error occurred")}catch{}try{typeof r=="object"&&"cerr"in r&&"isCrossauthError"in r.cerr&&r.cerr&&(r.errorCode=r.cerr.code,r.errorCodeName=r.cerr.codeName,r.httpStatus=r.cerr.httpStatus,"msg"in r||(r.msg=r.cerr.message),delete r.cerr)}catch{}return typeof r=="string"||globalThis.crossauthLoggerAcceptsJson?r:JSON.stringify(r)}globalThis.crossauthLogger=new d,globalThis.crossauthLoggerAcceptsJson=!0;const _e={issuer:"",authorization_endpoint:"",token_endpoint:"",jwks_uri:"",response_types_supported:[],subject_types_supported:[],response_modes_supported:["query","fragment"],grant_types_supported:["authorization_code","implicit"],id_token_signing_alg_values_supported:[],claim_types_supported:["normal"],claims_parameter_supported:!1,request_parameter_supported:!1,request_uri_parameter_supported:!0,require_request_uri_registration:!1},ae=crypto,ke=r=>r instanceof CryptoKey,ce=new TextEncoder,ee=new TextDecoder;function Je(...r){const e=r.reduce((i,{length:n})=>i+n,0),t=new Uint8Array(e);let o=0;for(const i of r)t.set(i,o),o+=i.length;return t}const ze=r=>{const e=atob(r),t=new Uint8Array(e.length);for(let o=0;o<e.length;o++)t[o]=e.charCodeAt(o);return t},x=r=>{let e=r;e instanceof Uint8Array&&(e=ee.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return ze(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class R extends Error{constructor(e,t){var o;super(e,t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(o=Error.captureStackTrace)==null||o.call(Error,this,this.constructor)}}R.code="ERR_JOSE_GENERIC";class Le extends R{constructor(e,t,o="unspecified",i="unspecified"){super(e,{cause:{claim:o,reason:i,payload:t}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=o,this.reason=i,this.payload=t}}Le.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class Fe extends R{constructor(e,t,o="unspecified",i="unspecified"){super(e,{cause:{claim:o,reason:i,payload:t}}),this.code="ERR_JWT_EXPIRED",this.claim=o,this.reason=i,this.payload=t}}Fe.code="ERR_JWT_EXPIRED";class Me extends R{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}Me.code="ERR_JOSE_ALG_NOT_ALLOWED";class O extends R{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}O.code="ERR_JOSE_NOT_SUPPORTED";class Be extends R{constructor(e="decryption operation failed",t){super(e,t),this.code="ERR_JWE_DECRYPTION_FAILED"}}Be.code="ERR_JWE_DECRYPTION_FAILED";class $e extends R{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}$e.code="ERR_JWE_INVALID";class S extends R{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}S.code="ERR_JWS_INVALID";class J extends R{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}J.code="ERR_JWT_INVALID";class qe extends R{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}qe.code="ERR_JWK_INVALID";class Ve extends R{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}Ve.code="ERR_JWKS_INVALID";class Ge extends R{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_NO_MATCHING_KEY"}}Ge.code="ERR_JWKS_NO_MATCHING_KEY";class Ye extends R{constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}Ye.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class Xe extends R{constructor(e="request timed out",t){super(e,t),this.code="ERR_JWKS_TIMEOUT"}}Xe.code="ERR_JWKS_TIMEOUT";class Ce extends R{constructor(e="signature verification failed",t){super(e,t),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}Ce.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function W(r,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${r}`)}function re(r,e){return r.name===e}function ue(r){return parseInt(r.name.slice(4),10)}function Qe(r){switch(r){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Ze(r,e){if(e.length&&!e.some(t=>r.usages.includes(t))){let t="CryptoKey does not support this operation, its usages must include ";if(e.length>2){const o=e.pop();t+=`one of ${e.join(", ")}, or ${o}.`}else e.length===2?t+=`one of ${e[0]} or ${e[1]}.`:t+=`${e[0]}.`;throw new TypeError(t)}}function er(r,e,...t){switch(e){case"HS256":case"HS384":case"HS512":{if(!re(r.algorithm,"HMAC"))throw W("HMAC");const o=parseInt(e.slice(2),10);if(ue(r.algorithm.hash)!==o)throw W(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!re(r.algorithm,"RSASSA-PKCS1-v1_5"))throw W("RSASSA-PKCS1-v1_5");const o=parseInt(e.slice(2),10);if(ue(r.algorithm.hash)!==o)throw W(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!re(r.algorithm,"RSA-PSS"))throw W("RSA-PSS");const o=parseInt(e.slice(2),10);if(ue(r.algorithm.hash)!==o)throw W(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(r.algorithm.name!=="Ed25519"&&r.algorithm.name!=="Ed448")throw W("Ed25519 or Ed448");break}case"Ed25519":{if(!re(r.algorithm,"Ed25519"))throw W("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!re(r.algorithm,"ECDSA"))throw W("ECDSA");const o=Qe(e);if(r.algorithm.namedCurve!==o)throw W(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Ze(r,t)}function Se(r,e,...t){var o;if(t=t.filter(Boolean),t.length>2){const i=t.pop();r+=`one of type ${t.join(", ")}, or ${i}.`}else t.length===2?r+=`one of type ${t[0]} or ${t[1]}.`:r+=`of type ${t[0]}.`;return e==null?r+=` Received ${e}`:typeof e=="function"&&e.name?r+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&(o=e.constructor)!=null&&o.name&&(r+=` Received an instance of ${e.constructor.name}`),r}const Te=(r,...e)=>Se("Key must be ",r,...e);function Ee(r,e,...t){return Se(`Key for the ${r} algorithm must be `,e,...t)}const be=r=>ke(r)?!0:(r==null?void 0:r[Symbol.toStringTag])==="KeyObject",de=["CryptoKey"],rr=(...r)=>{const e=r.filter(Boolean);if(e.length===0||e.length===1)return!0;let t;for(const o of e){const i=Object.keys(o);if(!t||t.size===0){t=new Set(i);continue}for(const n of i){if(t.has(n))return!1;t.add(n)}}return!0};function tr(r){return typeof r=="object"&&r!==null}function $(r){if(!tr(r)||Object.prototype.toString.call(r)!=="[object Object]")return!1;if(Object.getPrototypeOf(r)===null)return!0;let e=r;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(r)===e}const or=(r,e)=>{if(r.startsWith("RS")||r.startsWith("PS")){const{modulusLength:t}=e.algorithm;if(typeof t!="number"||t<2048)throw new TypeError(`${r} requires key modulusLength to be 2048 bits or larger`)}};function q(r){return $(r)&&typeof r.kty=="string"}function ir(r){return r.kty!=="oct"&&typeof r.d=="string"}function sr(r){return r.kty!=="oct"&&typeof r.d>"u"}function nr(r){return q(r)&&r.kty==="oct"&&typeof r.k=="string"}function ar(r){let e,t;switch(r.kty){case"RSA":{switch(r.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${r.alg.slice(-3)}`},t=r.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${r.alg.slice(-3)}`},t=r.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(r.alg.slice(-3),10)||1}`},t=r.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new O('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(r.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},t=r.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},t=r.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},t=r.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:r.crv},t=r.d?["deriveBits"]:[];break;default:throw new O('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(r.alg){case"Ed25519":e={name:"Ed25519"},t=r.d?["sign"]:["verify"];break;case"EdDSA":e={name:r.crv},t=r.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:r.crv},t=r.d?["deriveBits"]:[];break;default:throw new O('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new O('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:t}}const Ae=async r=>{if(!r.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:e,keyUsages:t}=ar(r),o=[e,r.ext??!1,r.key_ops??t],i={...r};return delete i.alg,delete i.use,ae.subtle.importKey("jwk",i,...o)},Re=r=>x(r);let V,G;const Pe=r=>(r==null?void 0:r[Symbol.toStringTag])==="KeyObject",le=async(r,e,t,o,i=!1)=>{let n=r.get(e);if(n!=null&&n[o])return n[o];const s=await Ae({...t,alg:o});return i&&Object.freeze(e),n?n[o]=s:r.set(e,{[o]:s}),s},cr=(r,e)=>{if(Pe(r)){let t=r.export({format:"jwk"});return delete t.d,delete t.dp,delete t.dq,delete t.p,delete t.q,delete t.qi,t.k?Re(t.k):(G||(G=new WeakMap),le(G,r,t,e))}return q(r)?r.k?x(r.k):(G||(G=new WeakMap),le(G,r,r,e,!0)):r},dr=(r,e)=>{if(Pe(r)){let t=r.export({format:"jwk"});return t.k?Re(t.k):(V||(V=new WeakMap),le(V,r,t,e))}return q(r)?r.k?x(r.k):(V||(V=new WeakMap),le(V,r,r,e,!0)):r},lr={normalizePublicKey:cr,normalizePrivateKey:dr},z=(r,e,t=0)=>{t===0&&(e.unshift(e.length),e.unshift(6));const o=r.indexOf(e[0],t);if(o===-1)return!1;const i=r.subarray(o,o+e.length);return i.length!==e.length?!1:i.every((n,s)=>n===e[s])||z(r,e,o+1)},Ie=r=>{switch(!0){case z(r,[42,134,72,206,61,3,1,7]):return"P-256";case z(r,[43,129,4,0,34]):return"P-384";case z(r,[43,129,4,0,35]):return"P-521";case z(r,[43,101,110]):return"X25519";case z(r,[43,101,111]):return"X448";case z(r,[43,101,112]):return"Ed25519";case z(r,[43,101,113]):return"Ed448";default:throw new O("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},Oe=async(r,e,t,o,i)=>{let n,s;const a=new Uint8Array(atob(t.replace(r,"")).split("").map(h=>h.charCodeAt(0))),c=e==="spki";switch(o){case"PS256":case"PS384":case"PS512":n={name:"RSA-PSS",hash:`SHA-${o.slice(-3)}`},s=c?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":n={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${o.slice(-3)}`},s=c?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":n={name:"RSA-OAEP",hash:`SHA-${parseInt(o.slice(-3),10)||1}`},s=c?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":n={name:"ECDSA",namedCurve:"P-256"},s=c?["verify"]:["sign"];break;case"ES384":n={name:"ECDSA",namedCurve:"P-384"},s=c?["verify"]:["sign"];break;case"ES512":n={name:"ECDSA",namedCurve:"P-521"},s=c?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{const h=Ie(a);n=h.startsWith("P-")?{name:"ECDH",namedCurve:h}:{name:h},s=c?[]:["deriveBits"];break}case"Ed25519":n={name:"Ed25519"},s=c?["verify"]:["sign"];break;case"EdDSA":n={name:Ie(a)},s=c?["verify"]:["sign"];break;default:throw new O('Invalid or unsupported "alg" (Algorithm) value')}return ae.subtle.importKey(e,a,n,!1,s)},hr=(r,e,t)=>Oe(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",r,e),ur=(r,e,t)=>Oe(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",r,e);async function fr(r,e,t){if(typeof r!="string"||r.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return ur(r,e)}async function gr(r,e,t){if(typeof r!="string"||r.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return hr(r,e)}async function fe(r,e){if(!$(r))throw new TypeError("JWK must be an object");switch(e||(e=r.alg),r.kty){case"oct":if(typeof r.k!="string"||!r.k)throw new TypeError('missing "k" (Key Value) Parameter value');return x(r.k);case"RSA":if("oth"in r&&r.oth!==void 0)throw new O('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return Ae({...r,alg:e});default:throw new O('Unsupported "kty" (Key Type) Parameter value')}}const Y=r=>r==null?void 0:r[Symbol.toStringTag],ge=(r,e,t)=>{var o,i;if(e.use!==void 0&&e.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(e.key_ops!==void 0&&((i=(o=e.key_ops).includes)==null?void 0:i.call(o,t))!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${t}`);if(e.alg!==void 0&&e.alg!==r)throw new TypeError(`Invalid key for this operation, when present its alg must be ${r}`);return!0},pr=(r,e,t,o)=>{if(!(e instanceof Uint8Array)){if(o&&q(e)){if(nr(e)&&ge(r,e,t))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!be(e))throw new TypeError(Ee(r,e,...de,"Uint8Array",o?"JSON Web Key":null));if(e.type!=="secret")throw new TypeError(`${Y(e)} instances for symmetric algorithms must be of type "secret"`)}},yr=(r,e,t,o)=>{if(o&&q(e))switch(t){case"sign":if(ir(e)&&ge(r,e,t))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(sr(e)&&ge(r,e,t))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!be(e))throw new TypeError(Ee(r,e,...de,o?"JSON Web Key":null));if(e.type==="secret")throw new TypeError(`${Y(e)} instances for asymmetric algorithms must not be of type "secret"`);if(t==="sign"&&e.type==="public")throw new TypeError(`${Y(e)} instances for asymmetric algorithm signing must be of type "private"`);if(t==="decrypt"&&e.type==="public")throw new TypeError(`${Y(e)} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&t==="verify"&&e.type==="private")throw new TypeError(`${Y(e)} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&t==="encrypt"&&e.type==="private")throw new TypeError(`${Y(e)} instances for asymmetric algorithm encryption must be of type "public"`)};function Ue(r,e,t,o){e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?pr(e,t,o,r):yr(e,t,o,r)}Ue.bind(void 0,!1);const Ne=Ue.bind(void 0,!0);function wr(r,e,t,o,i){if(i.crit!==void 0&&(o==null?void 0:o.crit)===void 0)throw new r('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||o.crit===void 0)return new Set;if(!Array.isArray(o.crit)||o.crit.length===0||o.crit.some(s=>typeof s!="string"||s.length===0))throw new r('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let n;n=e;for(const s of o.crit){if(!n.has(s))throw new O(`Extension Header Parameter "${s}" is not recognized`);if(i[s]===void 0)throw new r(`Extension Header Parameter "${s}" is missing`);if(n.get(s)&&o[s]===void 0)throw new r(`Extension Header Parameter "${s}" MUST be integrity protected`)}return new Set(o.crit)}function mr(r,e){const t=`SHA-${r.slice(-3)}`;switch(r){case"HS256":case"HS384":case"HS512":return{hash:t,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:t,name:"RSA-PSS",saltLength:r.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:t,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:t,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:e.name};default:throw new O(`alg ${r} is not supported either by JOSE or your javascript runtime`)}}async function vr(r,e,t){if(e=await lr.normalizePublicKey(e,r),ke(e))return er(e,r,t),e;if(e instanceof Uint8Array){if(!r.startsWith("HS"))throw new TypeError(Te(e,...de));return ae.subtle.importKey("raw",e,{hash:`SHA-${r.slice(-3)}`,name:"HMAC"},!1,[t])}throw new TypeError(Te(e,...de,"Uint8Array","JSON Web Key"))}const _r=async(r,e,t,o)=>{const i=await vr(r,e,"verify");or(r,i);const n=mr(r,i.algorithm);try{return await ae.subtle.verify(n,i,t,o)}catch{return!1}};async function kr(r,e,t){if(!$(r))throw new S("Flattened JWS must be an object");if(r.protected===void 0&&r.header===void 0)throw new S('Flattened JWS must have either of the "protected" or "header" members');if(r.protected!==void 0&&typeof r.protected!="string")throw new S("JWS Protected Header incorrect type");if(r.payload===void 0)throw new S("JWS Payload missing");if(typeof r.signature!="string")throw new S("JWS Signature missing or incorrect type");if(r.header!==void 0&&!$(r.header))throw new S("JWS Unprotected Header incorrect type");let o={};if(r.protected)try{const ie=x(r.protected);o=JSON.parse(ee.decode(ie))}catch{throw new S("JWS Protected Header is invalid")}if(!rr(o,r.header))throw new S("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const i={...o,...r.header},n=wr(S,new Map([["b64",!0]]),void 0,o,i);let s=!0;if(n.has("b64")&&(s=o.b64,typeof s!="boolean"))throw new S('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=i;if(typeof a!="string"||!a)throw new S('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(s){if(typeof r.payload!="string")throw new S("JWS Payload must be a string")}else if(typeof r.payload!="string"&&!(r.payload instanceof Uint8Array))throw new S("JWS Payload must be a string or an Uint8Array instance");let c=!1;typeof e=="function"?(e=await e(o,r),c=!0,Ne(a,e,"verify"),q(e)&&(e=await fe(e,a))):Ne(a,e,"verify");const h=Je(ce.encode(r.protected??""),ce.encode("."),typeof r.payload=="string"?ce.encode(r.payload):r.payload);let w;try{w=x(r.signature)}catch{throw new S("Failed to base64url decode the signature")}if(!await _r(a,e,w,h))throw new Ce;let E;if(s)try{E=x(r.payload)}catch{throw new S("Failed to base64url decode the payload")}else typeof r.payload=="string"?E=ce.encode(r.payload):E=r.payload;const I={payload:E};return r.protected!==void 0&&(I.protectedHeader=o),r.header!==void 0&&(I.unprotectedHeader=r.header),c?{...I,key:e}:I}async function Cr(r,e,t){if(r instanceof Uint8Array&&(r=ee.decode(r)),typeof r!="string")throw new S("Compact JWS must be a string or Uint8Array");const{0:o,1:i,2:n,length:s}=r.split(".");if(s!==3)throw new S("Invalid Compact JWS");const a=await kr({payload:i,protected:o,signature:n},e),c={payload:a.payload,protectedHeader:a.protectedHeader};return typeof e=="function"?{...c,key:a.key}:c}const Ke=x;function We(r){let e;if(typeof r=="string"){const t=r.split(".");(t.length===3||t.length===5)&&([e]=t)}else if(typeof r=="object"&&r)if("protected"in r)e=r.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof e!="string"||!e)throw new Error;const t=JSON.parse(ee.decode(Ke(e)));if(!$(t))throw new Error;return t}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}function Sr(r){if(typeof r!="string")throw new J("JWTs must use Compact JWS serialization, JWT must be a string");const{1:e,length:t}=r.split(".");if(t===5)throw new J("Only JWTs using Compact JWS serialization can be decoded");if(t!==3)throw new J("Invalid JWT");if(!e)throw new J("JWTs must contain a payload");let o;try{o=Ke(e)}catch{throw new J("Failed to base64url decode the payload")}let i;try{i=JSON.parse(ee.decode(o))}catch{throw new J("Failed to parse the decoded payload as JSON")}if(!$(i))throw new J("Invalid JWT Claims Set");return i}const T=class k{static flowNames(e){let t={};return e.forEach(o=>{o in k.flowName&&(t[o]=k.flowName[o])}),t}static isValidFlow(e){return k.allFlows().includes(e)}static areAllValidFlows(e){let t=!0;return e.forEach(o=>{k.isValidFlow(o)||(t=!1)}),t}static allFlows(){return[k.AuthorizationCode,k.AuthorizationCodeWithPKCE,k.ClientCredentials,k.RefreshToken,k.DeviceCode,k.Password,k.PasswordMfa,k.OidcAuthorizationCode]}static grantType(e){switch(e){case k.AuthorizationCode:case k.AuthorizationCodeWithPKCE:case k.OidcAuthorizationCode:return["authorization_code"];case k.ClientCredentials:return["client_credentials"];case k.RefreshToken:return["refresh_token"];case k.Password:return["password"];case k.PasswordMfa:return["http://auth0.com/oauth/grant-type/mfa-otp","http://auth0.com/oauth/grant-type/mfa-oob"];case k.DeviceCode:return["urn:ietf:params:oauth:grant-type:device_code"]}}};u(T,"All","all"),u(T,"AuthorizationCode","authorizationCode"),u(T,"AuthorizationCodeWithPKCE","authorizationCodeWithPKCE"),u(T,"ClientCredentials","clientCredentials"),u(T,"RefreshToken","refreshToken"),u(T,"DeviceCode","deviceCode"),u(T,"Password","password"),u(T,"PasswordMfa","passwordMfa"),u(T,"OidcAuthorizationCode","oidcAuthorizationCode"),u(T,"flowName",{[T.AuthorizationCode]:"Authorization Code",[T.AuthorizationCodeWithPKCE]:"Authorization Code with PKCE",[T.ClientCredentials]:"Client Credentials",[T.RefreshToken]:"Refresh Token",[T.DeviceCode]:"Device Code",[T.Password]:"Password",[T.PasswordMfa]:"Password MFA",[T.OidcAuthorizationCode]:"OIDC Authorization Code"});var b,P;class Tr{constructor({authServerBaseUrl:e,client_id:t,client_secret:o,redirect_uri:i,codeChallengeMethod:n,stateLength:s,verifierLength:a,tokenConsumer:c,authServerCredentials:h,authServerMode:w,authServerHeaders:E}){u(this,"authServerBaseUrl",""),ve(this,b),ve(this,P),u(this,"codeChallengeMethod","S256"),u(this,"verifierLength",32),u(this,"redirect_uri"),u(this,"stateLength",32),u(this,"authzCode",""),u(this,"oidcConfig"),u(this,"tokenConsumer"),u(this,"authServerHeaders",{}),u(this,"authServerMode"),u(this,"authServerCredentials"),u(this,"oauthPostType","json"),u(this,"oauthLogFetch",!1),u(this,"oauthUseUserInfoEndpoint",!1),u(this,"oauthAuthorizeRedirect"),this.tokenConsumer=c,this.authServerBaseUrl=e,a&&(this.verifierLength=a),s&&(this.stateLength=s),t&&ne(this,b,t),o&&ne(this,P,o),i&&(this.redirect_uri=i),n&&(this.codeChallengeMethod=n),this.authServerBaseUrl=e,h&&(this.authServerCredentials=h),w&&(this.authServerMode=w),E&&(this.authServerHeaders=E)}set client_id(e){ne(this,b,e)}set client_secret(e){ne(this,P,e)}async loadConfig(e){if(e){d.logger.debug(l({msg:"Reading OIDC config locally"})),this.oidcConfig=e;return}let t;try{const o=new URL(this.authServerBaseUrl+"/.well-known/openid-configuration");d.logger.debug(l({msg:`Fetching OIDC config from ${o}`}));let i={headers:this.authServerHeaders};this.authServerMode&&(i.mode=this.authServerMode),this.authServerCredentials&&(i.credentials=this.authServerCredentials),t=await fetch(o,i)}catch(o){d.logger.error(l({err:o}))}if(!t||!t.ok)throw new g(_.Connection,"Couldn't get OIDC configuration from URL"+this.authServerBaseUrl+"/.well-known/openid-configuration");this.oidcConfig={..._e};try{const o=await t.json();for(const[i,n]of Object.entries(o))this.oidcConfig[i]=n}catch{throw new g(_.Connection,"Unrecognized response from OIDC configuration endpoint")}}getOidcConfig(){return this.oidcConfig}async startAuthorizationCodeFlow(e,t,o,i=!1){var n,s,a;if(d.logger.debug(l({msg:"Starting authorization code flow"})),this.oidcConfig||await this.loadConfig(),!((n=this.oidcConfig)!=null&&n.response_types_supported.includes("code"))||!((s=this.oidcConfig)!=null&&s.response_modes_supported.includes("query")))return{error:"invalid_request",error_description:"Server does not support authorization code flow"};if(!((a=this.oidcConfig)!=null&&a.authorization_endpoint))return{error:"server_error",error_description:"Cannot get authorize endpoint"};if(!m(this,b))return{error:"invalid_request",error_description:"Cannot make authorization code flow without client id"};if(!this.redirect_uri)return{error:"invalid_request",error_description:"Cannot make authorization code flow without Redirect Uri"};let c=this.oidcConfig.authorization_endpoint;this.oauthAuthorizeRedirect&&(c=this.oauthAuthorizeRedirect);let h=c+"?response_type=code&client_id="+encodeURIComponent(m(this,b))+"&state="+encodeURIComponent(e)+"&redirect_uri="+encodeURIComponent(this.redirect_uri);return t&&(h+="&scope="+encodeURIComponent(t)),i&&o&&(h+="&code_challenge="+o),{url:h}}async codeChallengeAndVerifier(){const e=this.randomValue(this.verifierLength);return{codeChallenge:this.codeChallengeMethod=="plain"?e:await this.sha256(e),codeVerifier:e}}async getIdPayload(e,t){let o,i;try{let n;if(n=await this.validateIdToken(e),!n)return o="access_denied",i="Invalid ID token received",{error:o,error_description:i};if(t&&this.oauthUseUserInfoEndpoint){const s=await this.userInfoEndpoint(t);if(s.error)return o=s.error,i="Failed getting user info: "+(s.error_description??"unknown error"),{error:o,error_description:i};n={...n,...s}}return{payload:n}}catch(n){const s=g.asCrossauthError(n);return d.logger.debug(l({err:s})),d.logger.error(l({msg:"Couldn't get user info",cerr:s})),o=s.oauthErrorCode,i="Couldn't get user info: "+s.message,{error:o,error_description:i}}}async getAccessPayload(e,t){let o,i;try{let n;return n=await this.validateAccessToken(e,t),n?{payload:n}:(o="access_denied",i="Invalid access token received",{error:o,error_description:i})}catch(n){const s=g.asCrossauthError(n);return d.logger.debug(l({err:s})),d.logger.error(l({msg:"Couldn't get user info",cerr:s})),o=s.oauthErrorCode,i="Couldn't get user info: "+s.message,{error:o,error_description:i}}}async redirectEndpoint(e,t,o,i,n){var s,a;if(this.oidcConfig||await this.loadConfig(),i||!e)return i||(i="server_error"),n||(n="Unknown error"),{error:i,error_description:n};if(this.authzCode=e,!((s=this.oidcConfig)!=null&&s.grant_types_supported.includes("authorization_code")))return{error:"invalid_request",error_description:"Server does not support authorization code grant"};if(!((a=this.oidcConfig)!=null&&a.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const c=this.oidcConfig.token_endpoint;let h,w;h="authorization_code",w=m(this,P);let E={grant_type:h,client_id:m(this,b),code:this.authzCode,redirect_uri:this.redirect_uri};t&&(E.scope=t),w&&(E.client_secret=w),o&&(E.code_verifier=o);try{let I=await this.post(c,E,this.authServerHeaders);if(I.id_token){const ie=await this.getIdPayload(I.id_token,I.access_token);if(ie.error)return ie;I.id_payload=ie.payload}return I}catch(I){return d.logger.error(l({err:I})),{error:"server_error",error_description:"Unable to get access token from server"}}}async clientCredentialsFlow(e){var t,o;if(d.logger.debug(l({msg:"Starting client credentials flow"})),this.oidcConfig||await this.loadConfig(),!((t=this.oidcConfig)!=null&&t.grant_types_supported.includes("client_credentials")))return{error:"invalid_request",error_description:"Server does not support client credentials grant"};if(!((o=this.oidcConfig)!=null&&o.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};if(!m(this,b))return{error:"invalid_request",error_description:"Cannot make client credentials flow without client id"};const i=this.oidcConfig.token_endpoint;let n={grant_type:"client_credentials",client_id:m(this,b),client_secret:m(this,P)};e&&(n.scope=e);try{let s=await this.post(i,n,this.authServerHeaders);if(s.id_token){const a=await this.getIdPayload(s.id_token,s.access_token);if(a.error)return a;s.id_payload=a.payload}return s}catch(s){return d.logger.error(l({err:s})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async passwordFlow(e,t,o){var i,n;if(d.logger.debug(l({msg:"Starting password flow"})),this.oidcConfig||await this.loadConfig(),!((i=this.oidcConfig)!=null&&i.grant_types_supported.includes("password")))return{error:"invalid_request",error_description:"Server does not support password grant"};if(!((n=this.oidcConfig)!=null&&n.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const s=this.oidcConfig.token_endpoint;let a={grant_type:"password",client_id:m(this,b),client_secret:m(this,P),username:e,password:t};o&&(a.scope=o);try{let c=await this.post(s,a,this.authServerHeaders);if(c.id_token){const h=await this.getIdPayload(c.id_token,c.access_token);if(h.error)return h;c.id_payload=h.payload}return c}catch(c){return d.logger.error(l({err:c})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async mfaAuthenticators(e){var t,o,i;if(d.logger.debug(l({msg:"Getting valid MFA authenticators"})),this.oidcConfig||await this.loadConfig(),!((t=this.oidcConfig)!=null&&t.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp"))&&(o=this.oidcConfig)!=null&&o.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-oob"))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((i=this.oidcConfig)!=null&&i.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const n=this.oidcConfig.issuer+(this.oidcConfig.issuer.endsWith("/")?"":"/")+"mfa/authenticators",s=await this.get(n,{authorization:"Bearer "+e,...this.authServerHeaders});if(!Array.isArray(s))return{error:"server_error",error_description:"Expected array of authenticators in mfa/authenticators response"};let a=[];for(let c=0;c<s.length;++c){const h=s[c];if(!h.id||!h.authenticator_type||!h.active)return{error:"server_error",error_description:"Invalid mfa/authenticators response"};a.push({id:h.id,authenticator_type:h.authenticator_type,active:h.active,name:h.name,oob_channel:h.oob_channel})}return{authenticators:a}}async mfaOtpRequest(e,t){var o,i;if(d.logger.debug(l({msg:"Making MFA OTB request"})),this.oidcConfig||await this.loadConfig(),!((o=this.oidcConfig)!=null&&o.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((i=this.oidcConfig)!=null&&i.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const n=this.oidcConfig.issuer+(this.oidcConfig.issuer.endsWith("/")?"":"/")+"mfa/challenge",s=await this.post(n,{client_id:m(this,b),client_secret:m(this,P),challenge_type:"otp",mfa_token:e,authenticator_id:t},this.authServerHeaders);return s.challenge_type!="otp"?{error:s.error??"server_error",error_description:s.error_description??"Invalid OTP challenge response"}:s}async mfaOtpComplete(e,t,o){var i,n;if(d.logger.debug(l({msg:"Completing MFA OTP request"})),this.oidcConfig||await this.loadConfig(),!((i=this.oidcConfig)!=null&&i.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((n=this.oidcConfig)!=null&&n.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const s=this.oidcConfig.token_endpoint,a=await this.post(s,{grant_type:"http://auth0.com/oauth/grant-type/mfa-otp",client_id:m(this,b),client_secret:m(this,P),challenge_type:"otp",mfa_token:e,otp:t,scope:o},this.authServerHeaders);if(a.id_token){const c=await this.getIdPayload(a.id_token,a.access_token);if(c.error)return c;a.id_payload=c.payload}return{id_token:a.id_token,access_token:a.access_token,refresh_token:a.refresh_token,expires_in:Number(a.expires_in),scope:a.scope,token_type:a.token_type,error:a.error,error_description:a.error_description}}async mfaOobRequest(e,t){var o,i;if(d.logger.debug(l({msg:"Making MFA OOB request"})),this.oidcConfig||await this.loadConfig(),!((o=this.oidcConfig)!=null&&o.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((i=this.oidcConfig)!=null&&i.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const n=this.oidcConfig.issuer+(this.oidcConfig.issuer.endsWith("/")?"":"/")+"mfa/challenge",s=await this.post(n,{client_id:m(this,b),client_secret:m(this,P),challenge_type:"oob",mfa_token:e,authenticator_id:t},this.authServerHeaders);return s.challenge_type!="oob"||!s.oob_code||!s.binding_method?{error:s.error??"server_error",error_description:s.error_description??"Invalid OOB challenge response"}:{challenge_type:s.challenge_type,oob_code:s.oob_code,binding_method:s.binding_method,error:s.error,error_description:s.error_description}}async mfaOobComplete(e,t,o,i){var n,s;if(d.logger.debug(l({msg:"Completing MFA OOB request"})),this.oidcConfig||await this.loadConfig(),!((n=this.oidcConfig)!=null&&n.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-oob")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((s=this.oidcConfig)!=null&&s.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const a=this.oidcConfig.token_endpoint,c=await this.post(a,{grant_type:"http://auth0.com/oauth/grant-type/mfa-oob",client_id:m(this,b),client_secret:m(this,P),challenge_type:"otp",mfa_token:e,oob_code:t,binding_code:o,scope:i},this.authServerHeaders);if(c.error)return{error:c.error,error_description:c.error_description};if(c.id_token){const h=await this.getIdPayload(c.id_token,c.access_token);if(h.error)return h;c.id_payload=h.payload}return{id_token:c.id_token,access_token:c.access_token,refresh_token:c.refresh_token,expires_in:"expires_in"in c?Number(c.expires_in):void 0,scope:c.scope,token_type:c.token_type}}async refreshTokenFlow(e){var t,o;if(d.logger.debug(l({msg:"Starting refresh token flow"})),this.oidcConfig||await this.loadConfig(),!((t=this.oidcConfig)!=null&&t.grant_types_supported.includes("refresh_token")))return{error:"invalid_request",error_description:"Server does not support refresh_token grant"};if(!((o=this.oidcConfig)!=null&&o.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const i=this.oidcConfig.token_endpoint;let n;n=m(this,P);let s={grant_type:"refresh_token",refresh_token:e,client_id:m(this,b)};n&&(s.client_secret=n);try{let a=await this.post(i,s,this.authServerHeaders);if(a.id_token){const c=await this.getIdPayload(a.id_token,a.access_token);if(c.error)return c;a.id_payload=c.payload}return a}catch(a){return d.logger.error(l({err:a})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async startDeviceCodeFlow(e,t){var o;if(d.logger.debug(l({msg:"Starting device code flow"})),this.oidcConfig||await this.loadConfig(),!((o=this.oidcConfig)!=null&&o.grant_types_supported.includes("urn:ietf:params:oauth:grant-type:device_code")))return{error:"invalid_request",error_description:"Server does not support device code grant"};let i={grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:m(this,b),client_secret:m(this,P)};t&&(i.scope=t);try{let n=await this.post(e,i,this.authServerHeaders);return n.id_token&&!await this.validateIdToken(n.id_token)?{error:"access_denied",error_description:"Invalid ID token"}:n}catch(n){return d.logger.error(l({err:n})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async pollDeviceCodeFlow(e){var t,o,i;if(d.logger.debug(l({msg:"Starting device code flow"})),this.oidcConfig||await this.loadConfig(),!((t=this.oidcConfig)!=null&&t.grant_types_supported.includes("urn:ietf:params:oauth:grant-type:device_code")))return{error:"invalid_request",error_description:"Server does not support device code grant"};if(!((o=this.oidcConfig)!=null&&o.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};let n={grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:m(this,b),client_secret:m(this,P),device_code:e};try{const s=await this.post((i=this.oidcConfig)==null?void 0:i.token_endpoint,n,this.authServerHeaders);if(s.error)return s;if(s.id_token){const a=await this.getIdPayload(s.id_token,s.access_token);if(a.error)return a;s.id_payload=a.payload}return s}catch(s){return d.logger.error(l({err:s})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async userInfoEndpoint(e){var t;if(!((t=this.oidcConfig)!=null&&t.userinfo_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const o=this.oidcConfig.userinfo_endpoint;return await this.post(o,{},{authorization:"Bearer "+e})}async post(e,t,o={}){d.logger.debug(l({msg:"Fetch POST",url:e,params:Object.keys(t)}));let i={};this.authServerCredentials&&(i.credentials=this.authServerCredentials),this.authServerMode&&(i.mode=this.authServerMode);let n="",s="";if(this.oauthPostType=="json")n=JSON.stringify(t),s="application/json";else{n="";for(let c in t)n!=""&&(n+="&"),n+=encodeURIComponent(c)+"="+encodeURIComponent(t[c]);s="application/x-www-form-urlencoded"}this.oauthLogFetch&&d.logger.debug(l({msg:"OAuth fetch",method:"POST",url:e,body:n}));const a=await(await fetch(e,{method:"POST",...i,headers:{Accept:"application/json","Content-Type":s,...o},body:n})).json();return this.oauthLogFetch&&d.logger.debug(l({msg:"OAuth fetch response",body:JSON.stringify(a)})),a}async get(e,t={}){d.logger.debug(l({msg:"Fetch GET",url:e}));let o={};this.authServerCredentials&&(o.credentials=this.authServerCredentials),this.authServerMode&&(o.mode=this.authServerMode),this.oauthLogFetch&&d.logger.debug(l({msg:"OAuth fetch",method:"GET",url:e}));const i=await(await fetch(e,{method:"GET",...o,headers:{Accept:"application/json",...t}})).json();return this.oauthLogFetch&&d.logger.debug(l({msg:"OAuth fetch response",body:JSON.stringify(i)})),i}async validateIdToken(e){try{return await this.tokenConsumer.tokenAuthorized(e,"id")}catch{return}}async validateAccessToken(e,t){try{return await this.tokenConsumer.tokenAuthorized(e,"access",t)}catch{return}}async idTokenAuthorized(e,t){try{return await this.tokenConsumer.tokenAuthorized(e,"id",t)}catch(o){d.logger.warn(l({err:o}));return}}getTokenPayload(e){return Sr(e)}}b=new WeakMap,P=new WeakMap;class Er{constructor(e,t={}){if(u(this,"audience"),u(this,"jwtKeyType"),u(this,"jwtSecretKey"),u(this,"jwtPublicKey"),u(this,"clockTolerance",10),u(this,"authServerBaseUrl",""),u(this,"oidcConfig"),u(this,"keys",{}),this.audience=e,t.authServerBaseUrl&&(this.authServerBaseUrl=t.authServerBaseUrl),t.jwtKeyType&&(this.jwtKeyType=t.jwtKeyType),t.jwtSecretKey&&(this.jwtSecretKey=t.jwtSecretKey),t.jwtPublicKey&&(this.jwtPublicKey=t.jwtPublicKey),t.clockTolerance&&(this.clockTolerance=t.clockTolerance),t.oidcConfig&&(this.oidcConfig=t.oidcConfig),this.jwtPublicKey&&!this.jwtKeyType)throw new g(_.Configuration,"If specifying jwtPublic key, must also specify jwtKeyType")}async loadKeys(e){try{if(this.jwtSecretKey){if(!this.jwtKeyType)throw new g(_.Configuration,"Must specify jwtKeyType if setting jwtSecretKey");this.keys._default=await gr(this.jwtSecretKey,this.jwtKeyType)}else if(this.jwtPublicKey){if(!this.jwtKeyType)throw new g(_.Configuration,"Must specify jwtKeyType if setting jwtPublicKey");const t=await fr(this.jwtPublicKey,this.jwtKeyType);this.keys._default=t}else{if(this.oidcConfig||await this.loadConfig(),!this.oidcConfig)throw new g(_.Connection,"Load OIDC config before Jwks");await this.loadJwks(void 0,e)}}catch(t){throw d.logger.debug(l({err:t})),new g(_.Connection,"Couldn't load keys")}}async loadConfig(e){if(e){this.oidcConfig=e;return}if(!this.authServerBaseUrl)throw new g(_.Connection,"Couldn't get OIDC configuration. Either set authServerBaseUrl or set config manually");let t;try{let o=this.authServerBaseUrl;o.endsWith("/")||(o+="/"),t=await fetch(new URL(".well-known/openid-configuration",o))}catch(o){d.logger.error(l({err:o}))}if(!t||!t.ok)throw new g(_.Connection,"Couldn't get OIDC configuration");this.oidcConfig={..._e};try{const o=await t.json();for(const[i,n]of Object.entries(o))this.oidcConfig[i]=n}catch{throw new g(_.Connection,"Unrecognized response from OIDC configuration endpoint")}}async loadJwks(e,t){if(e){this.keys={};for(let o=0;o<e.keys.length;++o){const i=e.keys[o],n="kid"in i&&i.kid?i.kid:"_default";this.keys[n]=await fe(e.keys[o])}}else{if(!this.oidcConfig)throw new g(_.Connection,"Load OIDC config before Jwks");let o;try{o=await fetch(new URL(this.oidcConfig.jwks_uri))}catch(i){d.logger.error(l({err:i}))}if(!o||!o.ok)throw new g(_.Connection,"Couldn't get OIDC configuration");this.keys={};try{const i=await o.json();if(!("keys"in i)||!Array.isArray(i.keys))throw new g(_.Connection,"Couldn't fetch keys");for(let n=0;n<i.keys.length;++n)try{let s="_default",a={...i.keys[n]};if("kid"in a&&typeof a.kid=="string"&&(s=String(a.kid)),a&&!a.alg&&!a.jwk_alg&&t)if(t.startsWith("RS")&&a.kty=="RSA")a.alg=t;else{d.logger.debug(l({msg:"Skipping key with "+a.kty}));continue}const c=await fe(a);this.keys[s]=c}catch(s){throw d.logger.error(l({err:s})),new g(_.Connection,"Couldn't load keys")}}catch(i){throw d.logger.error(l({err:i})),new g(_.Connection,"Unrecognized response from OIDC jwks endpoint")}}}async tokenAuthorized(e,t,o){if(!this.keys||Object.keys(this.keys).length==0){const n=We(e);await this.loadKeys(n.alg)}const i=await this.validateToken(e);if(i){if(i.iss!=this.authServerBaseUrl){const n=i.jti?i.jti:i.sid?i.sid:"";d.logger.error(l({msg:`Invalid issuer ${i.iss} ${t} token`,hashedAccessToken:await this.hash(n)}));return}if(o!=!1&&i.aud){const n=i.jti?i.jti:i.sid?i.sid:"";if(Array.isArray(i.aud)&&!i.aud.includes(this.audience)||!Array.isArray(i.aud)&&i.aud!=this.audience){d.logger.error(l({msg:`Invalid audience ${i.aud} in ${t} token`,hashedAccessToken:await this.hash(n)}));return}}return i}}async validateToken(e){(!this.keys||Object.keys(this.keys).length==0)&&d.logger.warn("No keys loaded so cannot validate tokens");let t;try{t=We(e).kid}catch{d.logger.warn(l({msg:"Invalid access token format"}));return}let o;for(let i in this.keys)if(t==i){o=this.keys[i];break}if(!o&&"_default"in this.keys&&(o=this.keys._default),!o){d.logger.warn(l({msg:"No matching keys found for access token"}));return}try{const{payload:i}=await Cr(e,o),n=JSON.parse(new TextDecoder().decode(i));if(n.exp*1e3<Date.now()+this.clockTolerance){d.logger.warn(l({msg:"Access token has expired"}));return}return n}catch(i){const n=g.asCrossauthError(i);d.logger.debug(l({err:n})),d.logger.warn(l({msg:"Access token did not validate",cerr:n}));return}}}const He=30,he=2,pe=30;class ye{constructor(e){f(this,"autoRefreshUrl","/autorefresh");f(this,"csrfHeader","X-CROSSAUTH-CSRF");f(this,"headers",{});f(this,"autoRefreshActive",!1);f(this,"mode","cors");f(this,"credentials","same-origin");f(this,"tokenProvider");this.tokenProvider=e.tokenProvider,this.autoRefreshUrl=e.autoRefreshUrl,e.csrfHeader&&(this.csrfHeader=e.csrfHeader),e.headers&&(this.headers=e.headers),e.mode&&(this.mode=e.mode),e.credentials&&(this.credentials=e.credentials)}async startAutoRefresh(e=["access","id"],t){if(!this.autoRefreshActive){this.autoRefreshActive=!0,d.logger.debug(l({msg:"Starting auto refresh"}));try{await this.scheduleAutoRefresh(e,t)}catch(o){const i=g.asCrossauthError(o);d.logger.error(l({cerr:i})),d.logger.debug(l({err:i}))}}}stopAutoRefresh(){this.autoRefreshActive=!1,d.logger.debug(l({msg:"Stopping auto refresh"}))}async scheduleAutoRefresh(e,t){let o;const i=this.tokenProvider.getCsrfToken(),n=i?await i:void 0,s=await this.tokenProvider.getTokenExpiries([...e,"refresh"],n);if(s.refresh==null){d.logger.debug(l({msg:"No refresh token found"}));return}const a=Date.now();let c=s.id;if((!c||s.access&&s.access<c)&&(c=s.access),!c){d.logger.debug(l({msg:"No tokens expire"}));return}let h=c*1e3-a-He;if(h<0&&o!=null&&o<=0){d.logger.debug(l({msg:"Expiry time has passed"}));return}if(h<0&&(h=0),s.refresh&&s.refresh-He<h){d.logger.debug(l({msg:"Refresh token has expired"}));return}let w=E=>new Promise(I=>setTimeout(I,E));d.logger.debug(l({msg:`Waiting ${h} before refreshing tokens`})),o=h,await w(h),await this.autoRefresh(e,n,t)}async autoRefresh(e,t,o){if(this.autoRefreshActive){let i,n=!1,s=0;for(;!n&&s<=he;)try{let a={...this.headers};t&&(a[this.csrfHeader]=t),d.logger.debug(l({msg:"Initiating auto refresh"}));const c=await this.tokenProvider.jsonFetchWithToken(this.autoRefreshUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...a},mode:this.mode,credentials:this.credentials,body:{csrfToken:t}},"refresh");c.ok||d.logger.error(l({msg:"Failed auto refreshing tokens",status:c.status}));try{i=await c.json()}catch{try{d.logger.error(l({msg:"/refresh returned a non-JSON response "+(i?await i.text():void 0)}))}catch{d.logger.error(l({msg:"/refresh returned a with no body "}))}i={ok:!1,error:"Unknown"}}if(i!=null&&i.ok){await this.scheduleAutoRefresh(e,o),n=!0;try{await this.tokenProvider.receiveTokens(i)}catch(h){const w=g.asCrossauthError(h);o?o("Couldn't receive tokens",w):(d.logger.debug(l({err:h})),d.logger.error(l({msg:"Error receiving tokens",cerr:w})))}}else s<he?(d.logger.error(l({msg:`Failed auto refreshing tokens. Retrying in ${pe} seconds`})),await(w=>new Promise(E=>setTimeout(E,w)))(pe*1e3)):(d.logger.error(l({msg:"Failed auto refreshing tokens. Number of retries exceeded"})),o&&o("Failed auto refreshing tokens")),s++}catch(a){const c=g.asCrossauthError(a);d.logger.debug(l({err:c})),s<he?(d.logger.error(l({msg:`Failed auto refreshing tokens. Retrying in ${he} seconds`})),await(w=>new Promise(E=>setTimeout(E,w)))(pe*1e3)):(d.logger.error(l({msg:"Failed auto refreshing tokens. Number of retries exceeded"})),o&&o(c.message,c)),s++}}}}class we{constructor(e){f(this,"deviceCodePollUrl","/devicecodepoll");f(this,"headers",{});f(this,"pollingActive",!1);f(this,"mode","cors");f(this,"credentials","same-origin");f(this,"respectRedirect",!0);f(this,"oauthClient");this.oauthClient=e.oauthClient,e.deviceCodePollUrl!=null&&(this.deviceCodePollUrl=e.deviceCodePollUrl),e.headers&&(this.headers=e.headers),e.mode&&(this.mode=e.mode),e.credentials&&(this.credentials=e.credentials)}async startPolling(e,t,o=5){this.pollingActive||(this.pollingActive=!0,d.logger.debug(l({msg:"Starting auto refresh"})),await this.poll(e,o,t))}stopPolling(){this.pollingActive=!1,d.logger.debug(l({msg:"Stopping auto refresh"}))}async poll(e,t,o){var i;if(!e)d.logger.debug(l({msg:"device code poll: no device code provided"})),o("error","Error waiting for authorization");else try{if(d.logger.debug(l({msg:"device code poll: poll"})),!this.deviceCodePollUrl&&this.oauthClient){if(this.oauthClient.getOidcConfig()||await this.oauthClient.loadConfig(),!((i=this.oauthClient.getOidcConfig())!=null&&i.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-oob")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};let s=this.oauthClient.getOidcConfig();if(!(s!=null&&s.token_endpoint))return{error:"server_error",error_description:"Couldn't get OIDC configuration"};this.deviceCodePollUrl=s.token_endpoint}if(!this.deviceCodePollUrl)return{error:"server_error",error_description:"Must either provide deviceCodePollUrl or an oauthClient to fetch it from"};const n=await fetch(this.deviceCodePollUrl,{method:"POST",body:JSON.stringify({device_code:e}),headers:{"content-type":"application/json"}});if(n.redirected)this.pollingActive=!1,n.redirected&&o("completeAndRedirect",void 0,n.url);else if(!n.ok)this.pollingActive=!1,o("error","Received an error from the authorization server");else{const s=await n.json();if(d.logger.debug(l({msg:"device code poll: received"+JSON.stringify(s)})),s.error=="expired_token")this.pollingActive=!1,o("expired_token","Timeout waiting for authorization");else if(s.error=="authorization_pending"||s.error=="slow_down"){s.error=="slow_down"&&(t+=5);let a=s.interval??t,c=h=>new Promise(w=>setTimeout(w,h));d.logger.debug(l({msg:"device code poll: waiting "+String(a)+" seconds"})),await c(a*1e3),this.pollingActive&&this.poll(e,t,o)}else s.error?(this.pollingActive=!1,o("error",s.error_description??s.error)):(this.pollingActive=!1,o("complete"))}}catch(n){this.pollingActive=!1;const s=g.asCrossauthError(n);d.logger.debug(l({err:s})),d.logger.error(l({msg:"Polling failed",cerr:s})),o("error",s.message)}}}class br{constructor(e={}){f(this,"bffPrefix","/bff");f(this,"csrfHeader","X-CROSSAUTH-CSRF");f(this,"enableCsrfProtection",!0);f(this,"headers",{});f(this,"mode","cors");f(this,"credentials","same-origin");f(this,"autoRefresher");f(this,"deviceCodePoller");f(this,"getCsrfTokenUrl","/api/getcsrftoken");f(this,"autoRefreshUrl","/api/refreshtokens");f(this,"tokensUrl","/tokens");e.bffPrefix&&(this.bffPrefix=e.bffPrefix),e.csrfHeader&&(this.csrfHeader=e.csrfHeader),e.enableCsrfProtection!=null&&(this.enableCsrfProtection=e.enableCsrfProtection),e.getCsrfTokenUrl&&(this.getCsrfTokenUrl=e.getCsrfTokenUrl),e.tokensUrl&&(this.tokensUrl=e.tokensUrl),e.autoRefreshUrl&&(this.autoRefreshUrl=e.autoRefreshUrl),this.bffPrefix.endsWith("/")||(this.bffPrefix+="/"),e.headers&&(this.headers=e.headers),e.mode&&(this.mode=e.mode),e.credentials&&(this.credentials=e.credentials),this.autoRefresher=new ye({...e,autoRefreshUrl:this.autoRefreshUrl,tokenProvider:this}),this.deviceCodePoller=new we({...e,oauthClient:void 0})}async getCsrfToken(){if(this.enableCsrfProtection)try{const t=await(await fetch(this.getCsrfTokenUrl,{headers:this.headers,credentials:this.credentials,mode:this.mode})).json();if(!t.ok)throw g.asCrossauthError(t);return t.csrfToken}catch(e){throw g.asCrossauthError(e)}}async getIdToken(e){const t=await this.getTokens(e);return(t==null?void 0:t.id_token)??null}async haveIdToken(e){const t=await this.getTokens(e);return t==null?!1:t.have_id_token!=null?t.have_id_token:"id_token"in t}async getAccessToken(e){const t=await this.getTokens(e);return(t==null?void 0:t.access_token)??null}async haveAccessToken(e){const t=await this.getTokens(e);return t==null?!1:t.have_access_token!=null?t.have_access_token:"access_token"in t}async getRefreshToken(e){const t=await this.getTokens(e);return(t==null?void 0:t.refresh_token)??null}async haveRefreshToken(e){const t=await this.getTokens(e);return t==null?!1:t.have_refresh_token!=null?t.have_refresh_token:"refresh_token"in t}async api(e,t,o,i){let n={...this.headers};!i&&!["GET","HEAD","OPTIONS"].includes(e)&&(i=await this.getCsrfToken(),i&&(n[this.csrfHeader]=i)),t.startsWith("/")&&(t=t.substring(1));let s={};o&&(s.body=JSON.stringify(o));const a=await fetch(this.bffPrefix+t,{headers:n,method:e,mode:this.mode,credentials:this.credentials,...s});let c=null;return a.body&&(c=await a.json()),{status:a.status,body:c}}async getTokens(e){e||(e=await this.getCsrfToken());let t={...this.headers};e&&(t[this.csrfHeader]=e);try{const o=await fetch(this.tokensUrl,{method:"POST",headers:t,mode:this.mode,credentials:this.credentials});return o.status==204?{}:await o.json()}catch(o){throw g.asCrossauthError(o)}}async startAutoRefresh(e=["access","id"],t){return this.autoRefresher.startAutoRefresh(e,t)}stopAutoRefresh(){return this.autoRefresher.stopAutoRefresh()}async startDeviceCodePolling(e,t,o=5){return this.deviceCodePoller.startPolling(e,t,o)}stopDeviceCodePolling(){return this.deviceCodePoller.stopPolling()}async getTokenExpiries(e,t){const o=await this.getTokens(t);try{const i=e.includes("id")?(o==null?void 0:o.id_token)??null:null,n=e.includes("access")?(o==null?void 0:o.access_token)??null:null,s=e.includes("refresh")?(o==null?void 0:o.refresh_token)??null:null;let a,c,h;return i&&(a=i.exp?i.exp:null),n&&(c=n.exp?n.exp:null),s&&(h=s.exp?s.exp:null),{id:a,access:c,refresh:h}}catch{return d.logger.error(l({msg:"getTokenExpiries received non JSON response "+o})),{id:0,access:0,refresh:0}}}async jsonFetchWithToken(e,t,o){return typeof t.body!="string"&&(t.body=JSON.stringify(t.body)),await fetch(e,t)}receiveTokens(e){return new Promise(t=>{})}}class Ar{getCsrfToken(){return new Promise(e=>{})}}class je extends Er{async hash(e){const o=new TextEncoder().encode(e),i=await crypto.subtle.digest("SHA-256",o),n=Array.from(new Uint8Array(i));return btoa(n.reduce((s,a)=>s+String.fromCharCode(a),"")).replace(/\//g,"_").replace(/\+/g,"-").replace(/=+$/,"")}}class Rr extends Tr{constructor(t){t.tokenConsumer||(t.tokenConsumer=new je(t.client_id,{authServerBaseUrl:t.authServerBaseUrl}));super(t);f(this,"resServerBaseUrl","");f(this,"resServerHeaders",{});f(this,"resServerMode","cors");f(this,"resServerCredentials","same-origin");f(this,"accessTokenResponseType","memory");f(this,"refreshTokenResponseType","memory");f(this,"idTokenResponseType","memory");f(this,"accessTokenName","CROSSAUTH_AT");f(this,"refreshTokenName","CROSSAUTH_RT");f(this,"idTokenName","CROSSAUTH_IT");U(this,L);U(this,D);U(this,H);U(this,F);U(this,M);U(this,X);U(this,Q);f(this,"autoRefresher");f(this,"deviceCodePoller");f(this,"deviceAuthorizationUrl","device_authorization");U(this,te);U(this,oe);U(this,Z);f(this,"scope");f(this,"logFetch",!1);this.resServerBaseUrl!=null&&(this.resServerBaseUrl=t.resServerBaseUrl??"",this.resServerBaseUrl.length>0&&!this.resServerBaseUrl.endsWith("/")&&(this.resServerBaseUrl+="/")),t.accessTokenResponseType&&(this.accessTokenResponseType=t.accessTokenResponseType),t.idTokenResponseType&&(this.idTokenResponseType=t.idTokenResponseType),t.refreshTokenResponseType&&(this.refreshTokenResponseType=t.refreshTokenResponseType),t.accessTokenName&&(this.accessTokenName=t.accessTokenName),t.idTokenName&&(this.idTokenName=t.idTokenName),t.refreshTokenName&&(this.refreshTokenName=t.refreshTokenName),t.resServerHeaders&&(this.resServerHeaders=t.resServerHeaders),t.resServerMode&&(this.resServerMode=t.resServerMode),t.resServerCredentials&&(this.resServerCredentials=t.resServerCredentials),t.client_id&&A(this,X,t.client_id),t.client_secret&&A(this,Q,t.client_secret),t.deviceAuthorizationUrl&&(this.deviceAuthorizationUrl=t.deviceAuthorizationUrl),this.autoRefresher=new ye({...t,autoRefreshUrl:this.authServerBaseUrl+"/token",tokenProvider:this}),this.deviceCodePoller=new we({...t,oauthClient:this,deviceCodePollUrl:null});let o,i,n;if(this.idTokenResponseType=="sessionStorage"?o=sessionStorage.getItem(this.idTokenName):this.idTokenResponseType=="localStorage"&&(o=localStorage.getItem(this.idTokenName)),this.accessTokenResponseType=="sessionStorage"?i=sessionStorage.getItem(this.accessTokenName):this.accessTokenResponseType=="localStorage"&&(i=localStorage.getItem(this.accessTokenName)),this.refreshTokenResponseType=="sessionStorage"?n=sessionStorage.getItem(this.refreshTokenName):this.refreshTokenResponseType=="localStorage"&&(n=localStorage.getItem(this.refreshTokenName)),this.receiveTokens({access_token:i,id_token:o,refresh_token:n}),i){const s=this.getTokenPayload(i);s&&(A(this,L,i),A(this,F,s))}if(n){const s=this.getTokenPayload(n);s&&(A(this,D,n),A(this,M,s))}o?this.validateIdToken(o).then(s=>{A(this,H,s),t.autoRefresh&&this.startAutoRefresh(t.autoRefresh).then().catch(a=>{d.logger.debug(l({err:a,msg:"Couldn't start auto refresh"}))})}).catch(s=>{d.logger.debug(l({err:s,msg:"Couldn't validate ID token"}))}):y(this,L)&&t.autoRefresh&&n?this.startAutoRefresh(t.autoRefresh).then().catch(s=>{d.logger.debug(l({err:s,msg:"Couldn't start auto refresh"}))}):n&&!i&&this.refreshTokenFlow(n).then(s=>{d.logger.debug(l({msg:"Refreshed tokens"})),t.autoRefresh&&this.startAutoRefresh(t.autoRefresh).then().catch(a=>{d.logger.debug(l({err:a,msg:"Couldn't start auto refresh"}))})}).catch(s=>{const a=g.asCrossauthError(s);d.logger.debug(l({err:a})),d.logger.error(l({msg:"failed refreshing tokens",cerr:a}))})}get idTokenPayload(){return y(this,H)}async handleRedirectUri(){const t=new URL(window.location.href);if(t.origin+t.pathname!=this.redirect_uri)return;const o=new URLSearchParams(window.location.search);let i,n,s,a;for(const[h,w]of o)h=="code"&&(i=w),h=="state"&&(n=w),h=="error"&&(s=w),h=="error_description"&&(a=w);if(!s&&!i)return;if(s){const h=g.fromOAuthError(s,a);throw d.logger.debug(l({err:h})),d.logger.error(l({cerr:h,msg:"Error from authorize endpoint: "+s})),h}if(y(this,Z)&&n!=y(this,Z))return{error:"access_denied",error_description:"Invalid state"};const c=await this.redirectEndpoint(i,this.scope,y(this,oe),s,a);if(c.error){const h=g.fromOAuthError(c.error,a);throw d.logger.debug(l({err:h})),d.logger.error(l({cerr:h,msg:"Error from redirect endpoint: "+c.error})),h}return await this.receiveTokens(c),c}async startAutoRefresh(t=["access","id"],o){return this.autoRefresher.startAutoRefresh(t,o)}stopAutoRefresh(){return this.autoRefresher.stopAutoRefresh()}async startDeviceCodePolling(t,o,i=5){return this.deviceCodePoller.startPolling(t,o,i)}stopDeviceCodePolling(){return this.deviceCodePoller.stopPolling()}getIdToken(){return y(this,H)}randomValue(t){const o=new Uint8Array(t);return self.crypto.getRandomValues(o),btoa(o.reduce((i,n)=>i+String.fromCharCode(n),"")).replace(/\//g,"_").replace(/\+/g,"-").replace(/=+$/,"")}async sha256(t){const i=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",i),s=Array.from(new Uint8Array(n));return btoa(s.reduce((a,c)=>a+String.fromCharCode(c),"")).replace(/\//g,"_").replace(/\+/g,"-").replace(/=+$/,"")}async api(t,o,i){let n={...this.resServerHeaders};o.startsWith("/")&&(o=o.substring(1));let s={};i&&(s.body=JSON.stringify(i));let a;this.accessTokenResponseType=="sessionStorage"?a=sessionStorage.getItem(this.accessTokenName):this.accessTokenResponseType=="localStorage"&&(a=localStorage.getItem(this.accessTokenName)),n.authorization="Bearer "+a;const c=await fetch(this.resServerBaseUrl+o,{headers:n,method:t,mode:this.resServerMode,credentials:this.resServerCredentials,...s});let h=null;return c.body&&(h=await c.json()),{status:c.status,body:h}}async getTokenExpiries(t,o){let i,n,s;return y(this,H)&&(i=y(this,H).exp?y(this,H).exp:null),y(this,F)&&(n=y(this,F).exp?y(this,F).exp:null),y(this,M)&&(s=y(this,M).exp?y(this,M).exp:null),{id:i,access:n,refresh:s}}async jsonFetchWithToken(t,o,i){if(i=="access"){if(!y(this,L))throw new g(_.InvalidToken,"Cannot make fetch with access token - no access token defined");o.headers||(o.headers={}),o.headers.authorization="Bearer "+y(this,L)}else{if(o.body||(o.body={}),!y(this,D))throw new g(_.InvalidToken,"Cannot make fetch with refresh token - no refresh token defined");o.body.refresh_token=y(this,D),o.body.grant_type="refresh_token"}return y(this,X)&&(o.body||(o.body={}),o.body.client_id=y(this,X),y(this,Q)&&(o.body.client_secret=y(this,Q))),typeof o.body!="string"&&(o.body=JSON.stringify(o.body)),await fetch(t,o)}async getCsrfToken(){}async receiveTokens(t){if(t.access_token){const o=this.getTokenPayload(t.access_token);o&&(A(this,L,t.access_token),A(this,F,o)),this.accessTokenResponseType=="localStorage"?localStorage.setItem(this.accessTokenName,t.access_token):this.accessTokenResponseType=="sessionStorage"&&sessionStorage.setItem(this.accessTokenName,t.access_token)}if(t.refresh_token){const o=this.getTokenPayload(t.refresh_token);o&&(A(this,D,t.refresh_token),A(this,M,o)),this.refreshTokenResponseType=="localStorage"?localStorage.setItem(this.refreshTokenName,t.refresh_token):this.accessTokenResponseType=="sessionStorage"&&sessionStorage.setItem(this.refreshTokenName,t.refresh_token)}if(t.id_token){const o=await this.validateIdToken(t.id_token);A(this,H,o),this.idTokenResponseType=="localStorage"?localStorage.setItem(this.idTokenName,t.id_token):this.idTokenResponseType=="sessionStorage"&&sessionStorage.setItem(this.idTokenName,t.id_token)}}async clientCredentialsFlow(t){const o=await super.clientCredentialsFlow(t);return await this.receiveTokens(o),o}async passwordFlow(t,o,i){const n=await super.passwordFlow(t,o,i);return await this.receiveTokens(n),n}async deviceCodeFlow(t){let o=this.authServerBaseUrl;return o.endsWith("/")||(o+="/"),o+=this.deviceAuthorizationUrl,await super.startDeviceCodeFlow(o,t)}async mfaOtpComplete(t,o){const i=await super.mfaOtpComplete(t,o);return await this.receiveTokens(i),i}async mfaOobComplete(t,o,i){const n=await super.mfaOobComplete(t,o,i);return await this.receiveTokens(n),n}async refreshTokenFlow(t){if(!t)if(y(this,D))t=y(this,D);else throw new g(_.InvalidToken,"Cannot refresh tokens: no refresh token present");const o=await super.refreshTokenFlow(t);return await this.receiveTokens(o),o}async authorizationCodeFlow(t,o=!1){const i=this.randomValue(this.stateLength);if(this.scope=t,o){const s=await this.codeChallengeAndVerifier();A(this,te,s.codeChallenge),A(this,oe,s.codeVerifier),A(this,Z,i)}const n=await super.startAuthorizationCodeFlow(i,t,y(this,te),o);if(n.error||!n.url){const s=g.fromOAuthError(n.error??"Couldn't create URL for authorization code flow",n.error_description);throw d.logger.debug(l({err:s})),s}location.href=n.url}}return L=new WeakMap,D=new WeakMap,H=new WeakMap,F=new WeakMap,M=new WeakMap,X=new WeakMap,Q=new WeakMap,te=new WeakMap,oe=new WeakMap,Z=new WeakMap,p.CrossauthError=g,p.CrossauthLogger=d,p.OAuthAutoRefresher=ye,p.OAuthBffClient=br,p.OAuthClient=Rr,p.OAuthDeviceCodePoller=we,p.OAuthTokenConsumer=je,p.OAuthTokenProvider=Ar,p.j=l,Object.defineProperty(p,Symbol.toStringTag,{value:"Module"}),p}({});
1
+ var crossauth_frontend=function(y){"use strict";var Pr=Object.defineProperty;var je=y=>{throw TypeError(y)};var Ir=(y,v,S)=>v in y?Pr(y,v,{enumerable:!0,configurable:!0,writable:!0,value:S}):y[v]=S;var f=(y,v,S)=>Ir(y,typeof v!="symbol"?v+"":v,S),xe=(y,v,S)=>v.has(y)||je("Cannot "+S);var w=(y,v,S)=>(xe(y,v,"read from private field"),S?S.call(y):v.get(y)),U=(y,v,S)=>v.has(y)?je("Cannot add the same private member more than once"):v instanceof WeakSet?v.add(y):v.set(y,S),A=(y,v,S,ie)=>(xe(y,v,"write to private field"),ie?ie.call(y,S):v.set(y,S),S);var L,j,D,F,M,X,Q,te,oe,Z;var v=Object.defineProperty,S=r=>{throw TypeError(r)},ie=(r,e,t)=>e in r?v(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,u=(r,e,t)=>ie(r,typeof e!="symbol"?e+"":e,t),me=(r,e,t)=>e.has(r)||S("Cannot "+t),m=(r,e,t)=>(me(r,e,"read from private field"),e.get(r)),ve=(r,e,t)=>e.has(r)?S("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),ne=(r,e,t,o)=>(me(r,e,"write to private field"),e.set(r,t),t);class H{}u(H,"active","active"),u(H,"disabled","disabled"),u(H,"awaitingTwoFactorSetup","awaitingtwofactorsetup"),u(H,"awaitingTwoFactorSetupAndEmailVerification","awaitingtwofactorsetupandemailverification"),u(H,"awaitingEmailVerification","awaitingemailverification"),u(H,"passwordChangeNeeded","passwordchangeneeded"),u(H,"passwordResetNeeded","passwordresetneeded"),u(H,"factor2ResetNeeded","factor2resetneeded"),u(H,"passwordAndFactor2ResetNeeded","passwordandfactor2resetneeded");class K{}u(K,"session","s:"),u(K,"passwordResetToken","p:"),u(K,"emailVerificationToken","e:"),u(K,"apiKey","api:"),u(K,"authorizationCode","authz:"),u(K,"accessToken","access:"),u(K,"refreshToken","refresh:"),u(K,"mfaToken","omfa:"),u(K,"deviceCode","dc:"),u(K,"userCode","uc:");var _=(r=>(r[r.UserNotExist=0]="UserNotExist",r[r.PasswordInvalid=1]="PasswordInvalid",r[r.EmailNotExist=2]="EmailNotExist",r[r.UsernameOrPasswordInvalid=3]="UsernameOrPasswordInvalid",r[r.InvalidClientId=4]="InvalidClientId",r[r.ClientExists=5]="ClientExists",r[r.InvalidClientSecret=6]="InvalidClientSecret",r[r.InvalidClientIdOrSecret=7]="InvalidClientIdOrSecret",r[r.InvalidRedirectUri=8]="InvalidRedirectUri",r[r.InvalidOAuthFlow=9]="InvalidOAuthFlow",r[r.UserNotActive=10]="UserNotActive",r[r.EmailNotVerified=11]="EmailNotVerified",r[r.TwoFactorIncomplete=12]="TwoFactorIncomplete",r[r.Unauthorized=13]="Unauthorized",r[r.UnauthorizedClient=14]="UnauthorizedClient",r[r.InvalidScope=15]="InvalidScope",r[r.InsufficientScope=16]="InsufficientScope",r[r.InsufficientPriviledges=17]="InsufficientPriviledges",r[r.Forbidden=18]="Forbidden",r[r.InvalidKey=19]="InvalidKey",r[r.InvalidCsrf=20]="InvalidCsrf",r[r.InvalidSession=21]="InvalidSession",r[r.Expired=22]="Expired",r[r.Connection=23]="Connection",r[r.InvalidHash=24]="InvalidHash",r[r.UnsupportedAlgorithm=25]="UnsupportedAlgorithm",r[r.KeyExists=26]="KeyExists",r[r.PasswordChangeNeeded=27]="PasswordChangeNeeded",r[r.PasswordResetNeeded=28]="PasswordResetNeeded",r[r.Factor2ResetNeeded=29]="Factor2ResetNeeded",r[r.Configuration=30]="Configuration",r[r.InvalidEmail=31]="InvalidEmail",r[r.InvalidPhoneNumber=32]="InvalidPhoneNumber",r[r.InvalidUsername=33]="InvalidUsername",r[r.PasswordMatch=34]="PasswordMatch",r[r.InvalidToken=35]="InvalidToken",r[r.MfaRequired=36]="MfaRequired",r[r.PasswordFormat=37]="PasswordFormat",r[r.DataFormat=38]="DataFormat",r[r.FetchError=39]="FetchError",r[r.UserExists=40]="UserExists",r[r.FormEntry=41]="FormEntry",r[r.BadRequest=42]="BadRequest",r[r.AuthorizationPending=43]="AuthorizationPending",r[r.SlowDown=44]="SlowDown",r[r.ExpiredToken=45]="ExpiredToken",r[r.ConstraintViolation=46]="ConstraintViolation",r[r.NotImplemented=47]="NotImplemented",r[r.UnknownError=48]="UnknownError",r))(_||{});class g extends Error{constructor(e,t=void 0){let o,s=500;e==0?(o="User does not exist",s=401):e==1?(o="Password doesn't match",s=401):e==3?(o="Username or password incorrect",s=401):e==4?(o="Client id is invalid",s=401):e==5?(o="Client ID or name already exists",s=500):e==6?(o="Client secret is invalid",s=401):e==7?(o="Client id or secret is invalid",s=401):e==8?(o="Redirect Uri is not registered",s=401):e==9?(o="Invalid OAuth flow type",s=500):e==2?(o="No user exists with that email address",s=401):e==10?(o="Account is not active",s=403):e==33?(o="Username is not in an allowed format",s=400):e==31?(o="Email is not in an allowed format",s=400):e==32?(o="Phone number is not in an allowed format",s=400):e==11?(o="Email address has not been verified",s=403):e==12?(o="Two-factor setup is not complete",s=403):e==13?(o="Not authorized",s=401):e==14?(o="Client not authorized",s=401):e==15?(o="Invalid scope",s=403):e==16?(o="Insufficient scope",s=403):e==23?o="Connection failure":e==22?(o="Token has expired",s=401):e==24?o="Hash is not in a valid format":e==19?(o="Key is invalid",s=401):e==18?(o="You do not have permission to access this resource",s=403):e==17?(o="You do not have the right privileges to access this resource",s=401):e==20?(o="CSRF token is invalid",s=401):e==21?(o="Session cookie is invalid",s=401):e==25?o="Algorithm not supported":e==26?o="Attempt to create a key that already exists":e==27?(o="User must change password",s=403):e==28?(o="User must reset password",s=403):e==29?(o="User must reset 2FA",s=403):e==30?o="There was an error in the configuration":e==34?(o="Passwords do not match",s=401):e==35?(o="Token is not valid",s=401):e==36?(o="MFA is required",s=401):e==37?(o="Password format was incorrect",s=401):e==40?(o="User already exists",s=400):e==42?(o="The request is invalid",s=400):e==38?(o="Session data has unexpected format",s=500):e==39?(o="Couldn't execute a fetch",s=500):e==43?(o="Waiting for authorization",s=200):e==44?(o="Slow polling down by 5 seconds",s=200):e==45?(o="Token has expired",s=401):e==46?(o="Database update/insert caused a constraint violation",s=500):e==47?(o="This method has not been implemented",s=500):(o="Unknown error",s=500),t!=null&&!Array.isArray(t)?o=t:Array.isArray(t)&&(o=t.join(". ")),super(o),u(this,"isCrossauthError",!0),u(this,"httpStatus"),u(this,"code"),u(this,"codeName"),u(this,"messages"),this.code=e,this.codeName=_[e],this.httpStatus=s,this.name="CrossauthError",Array.isArray(t)?this.messages=t:this.messages=[o],Object.setPrototypeOf(this,g.prototype)}static fromOAuthError(e,t){let o;switch(e){case"invalid_request":o=42;break;case"unauthorized_client":o=14;break;case"access_denied":o=13;break;case"unsupported_response_type":o=42;break;case"invalid_scope":o=15;break;case"server_error":o=48;break;case"temporarily_unavailable":o=23;break;case"invalid_token":o=35;break;case"expired_token":o=45;break;case"insufficient_scope":o=35;break;case"mfa_required":o=36;break;case"authorization_pending":o=43;break;case"slow_down":o=44;break;default:o=48}return new g(o,t)}get oauthErrorCode(){switch(this.code){case 42:return"invalid_request";case 14:return"unauthorized_client";case 13:return"access_denied";case 15:return"invalid_scope";case 23:return"temporarily_unavailable";case 35:return"invalid_token";case 36:return"mfa_required";case 43:return"authorization_pending";case 44:return"slow_down";case 45:return"expired_token";case 22:return"expired_token";default:return"server_error"}}static asCrossauthError(e,t){if(e instanceof Error)return"isCrossauthError"in e?e:new g(48,e.message);if("errorCode"in e){let s=48;try{s=Number(e.errorCode)??48}catch{}let n=t??_[s];return"errorMessage"in e?n=e.errorMessage:"message"in e&&(n=e.message),new g(s,n)}let o=t??_[48];return"message"in e&&(o=e.message),new g(48,o)}}const B=class N{constructor(e){if(u(this,"level"),e)this.level=e;else if(typeof process<"u"&&"CROSSAUTH_LOG_LEVEL"in process.env){const t=(process.env.CROSSAUTH_LOG_LEVEL??"ERROR").toUpperCase();N.levelName.includes(t)?this.level=N.levelName.indexOf(t):this.level=N.Error}else this.level=N.Error}static get logger(){return globalThis.crossauthLogger}setLevel(e){this.level=e}log(e,t){e<=this.level&&(typeof t=="string"?console.log("Crossauth "+N.levelName[e]+" "+new Date().toISOString(),t):console.log(JSON.stringify({level:N.levelName[e],time:new Date().toISOString(),...t})))}error(e){this.log(N.Error,e)}warn(e){this.log(N.Warn,e)}info(e){this.log(N.Info,e)}debug(e){this.log(N.Debug,e)}static setLogger(e,t){globalThis.crossauthLogger=e,globalThis.crossauthLoggerAcceptsJson=t}};u(B,"None",0),u(B,"Error",1),u(B,"Warn",2),u(B,"Info",3),u(B,"Debug",4),u(B,"levelName",["NONE","ERROR","WARN","INFO","DEBUG"]);let d=B;function l(r){let e;typeof r=="object"&&"err"in r&&typeof r.err=="object"&&(e=r.err.stack);try{typeof r=="object"&&"err"in r&&typeof r.err=="object"&&r.err&&"message"in r.err&&!("msg"in r)&&(r.msg=r.err.message)}catch{}try{typeof r=="object"&&"err"in r&&typeof r.err=="object"&&(r.err={...r.err,stack:e})}catch{}try{typeof r=="object"&&"err"in r&&!("msg"in r)&&(r.msg=r.msg="An unknown error occurred")}catch{}try{typeof r=="object"&&"cerr"in r&&"isCrossauthError"in r.cerr&&r.cerr&&(r.errorCode=r.cerr.code,r.errorCodeName=r.cerr.codeName,r.httpStatus=r.cerr.httpStatus,"msg"in r||(r.msg=r.cerr.message),delete r.cerr)}catch{}return typeof r=="string"||globalThis.crossauthLoggerAcceptsJson?r:JSON.stringify(r)}globalThis.crossauthLogger=new d,globalThis.crossauthLoggerAcceptsJson=!0;const _e={issuer:"",authorization_endpoint:"",token_endpoint:"",jwks_uri:"",response_types_supported:[],subject_types_supported:[],response_modes_supported:["query","fragment"],grant_types_supported:["authorization_code","implicit"],id_token_signing_alg_values_supported:[],claim_types_supported:["normal"],claims_parameter_supported:!1,request_parameter_supported:!1,request_uri_parameter_supported:!0,require_request_uri_registration:!1},ae=crypto,ke=r=>r instanceof CryptoKey,ce=new TextEncoder,ee=new TextDecoder;function Je(...r){const e=r.reduce((s,{length:n})=>s+n,0),t=new Uint8Array(e);let o=0;for(const s of r)t.set(s,o),o+=s.length;return t}const ze=r=>{const e=atob(r),t=new Uint8Array(e.length);for(let o=0;o<e.length;o++)t[o]=e.charCodeAt(o);return t},x=r=>{let e=r;e instanceof Uint8Array&&(e=ee.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return ze(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class R extends Error{constructor(e,t){var o;super(e,t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(o=Error.captureStackTrace)==null||o.call(Error,this,this.constructor)}}R.code="ERR_JOSE_GENERIC";class Le extends R{constructor(e,t,o="unspecified",s="unspecified"){super(e,{cause:{claim:o,reason:s,payload:t}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=o,this.reason=s,this.payload=t}}Le.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class Fe extends R{constructor(e,t,o="unspecified",s="unspecified"){super(e,{cause:{claim:o,reason:s,payload:t}}),this.code="ERR_JWT_EXPIRED",this.claim=o,this.reason=s,this.payload=t}}Fe.code="ERR_JWT_EXPIRED";class Me extends R{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}Me.code="ERR_JOSE_ALG_NOT_ALLOWED";class O extends R{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}O.code="ERR_JOSE_NOT_SUPPORTED";class Be extends R{constructor(e="decryption operation failed",t){super(e,t),this.code="ERR_JWE_DECRYPTION_FAILED"}}Be.code="ERR_JWE_DECRYPTION_FAILED";class $e extends R{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}$e.code="ERR_JWE_INVALID";class T extends R{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}T.code="ERR_JWS_INVALID";class J extends R{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}J.code="ERR_JWT_INVALID";class qe extends R{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}qe.code="ERR_JWK_INVALID";class Ve extends R{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}Ve.code="ERR_JWKS_INVALID";class Ge extends R{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_NO_MATCHING_KEY"}}Ge.code="ERR_JWKS_NO_MATCHING_KEY";class Ye extends R{constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}Ye.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class Xe extends R{constructor(e="request timed out",t){super(e,t),this.code="ERR_JWKS_TIMEOUT"}}Xe.code="ERR_JWKS_TIMEOUT";class Ce extends R{constructor(e="signature verification failed",t){super(e,t),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}Ce.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function W(r,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${r}`)}function re(r,e){return r.name===e}function ue(r){return parseInt(r.name.slice(4),10)}function Qe(r){switch(r){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Ze(r,e){if(e.length&&!e.some(t=>r.usages.includes(t))){let t="CryptoKey does not support this operation, its usages must include ";if(e.length>2){const o=e.pop();t+=`one of ${e.join(", ")}, or ${o}.`}else e.length===2?t+=`one of ${e[0]} or ${e[1]}.`:t+=`${e[0]}.`;throw new TypeError(t)}}function er(r,e,...t){switch(e){case"HS256":case"HS384":case"HS512":{if(!re(r.algorithm,"HMAC"))throw W("HMAC");const o=parseInt(e.slice(2),10);if(ue(r.algorithm.hash)!==o)throw W(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!re(r.algorithm,"RSASSA-PKCS1-v1_5"))throw W("RSASSA-PKCS1-v1_5");const o=parseInt(e.slice(2),10);if(ue(r.algorithm.hash)!==o)throw W(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!re(r.algorithm,"RSA-PSS"))throw W("RSA-PSS");const o=parseInt(e.slice(2),10);if(ue(r.algorithm.hash)!==o)throw W(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(r.algorithm.name!=="Ed25519"&&r.algorithm.name!=="Ed448")throw W("Ed25519 or Ed448");break}case"Ed25519":{if(!re(r.algorithm,"Ed25519"))throw W("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!re(r.algorithm,"ECDSA"))throw W("ECDSA");const o=Qe(e);if(r.algorithm.namedCurve!==o)throw W(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Ze(r,t)}function Se(r,e,...t){var o;if(t=t.filter(Boolean),t.length>2){const s=t.pop();r+=`one of type ${t.join(", ")}, or ${s}.`}else t.length===2?r+=`one of type ${t[0]} or ${t[1]}.`:r+=`of type ${t[0]}.`;return e==null?r+=` Received ${e}`:typeof e=="function"&&e.name?r+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&(o=e.constructor)!=null&&o.name&&(r+=` Received an instance of ${e.constructor.name}`),r}const Te=(r,...e)=>Se("Key must be ",r,...e);function Ee(r,e,...t){return Se(`Key for the ${r} algorithm must be `,e,...t)}const be=r=>ke(r)?!0:(r==null?void 0:r[Symbol.toStringTag])==="KeyObject",de=["CryptoKey"],rr=(...r)=>{const e=r.filter(Boolean);if(e.length===0||e.length===1)return!0;let t;for(const o of e){const s=Object.keys(o);if(!t||t.size===0){t=new Set(s);continue}for(const n of s){if(t.has(n))return!1;t.add(n)}}return!0};function tr(r){return typeof r=="object"&&r!==null}function $(r){if(!tr(r)||Object.prototype.toString.call(r)!=="[object Object]")return!1;if(Object.getPrototypeOf(r)===null)return!0;let e=r;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(r)===e}const or=(r,e)=>{if(r.startsWith("RS")||r.startsWith("PS")){const{modulusLength:t}=e.algorithm;if(typeof t!="number"||t<2048)throw new TypeError(`${r} requires key modulusLength to be 2048 bits or larger`)}};function q(r){return $(r)&&typeof r.kty=="string"}function sr(r){return r.kty!=="oct"&&typeof r.d=="string"}function ir(r){return r.kty!=="oct"&&typeof r.d>"u"}function nr(r){return q(r)&&r.kty==="oct"&&typeof r.k=="string"}function ar(r){let e,t;switch(r.kty){case"RSA":{switch(r.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${r.alg.slice(-3)}`},t=r.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${r.alg.slice(-3)}`},t=r.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(r.alg.slice(-3),10)||1}`},t=r.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new O('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(r.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},t=r.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},t=r.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},t=r.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:r.crv},t=r.d?["deriveBits"]:[];break;default:throw new O('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(r.alg){case"Ed25519":e={name:"Ed25519"},t=r.d?["sign"]:["verify"];break;case"EdDSA":e={name:r.crv},t=r.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:r.crv},t=r.d?["deriveBits"]:[];break;default:throw new O('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new O('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:t}}const Ae=async r=>{if(!r.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:e,keyUsages:t}=ar(r),o=[e,r.ext??!1,r.key_ops??t],s={...r};return delete s.alg,delete s.use,ae.subtle.importKey("jwk",s,...o)},Re=r=>x(r);let V,G;const Pe=r=>(r==null?void 0:r[Symbol.toStringTag])==="KeyObject",le=async(r,e,t,o,s=!1)=>{let n=r.get(e);if(n!=null&&n[o])return n[o];const i=await Ae({...t,alg:o});return s&&Object.freeze(e),n?n[o]=i:r.set(e,{[o]:i}),i},cr=(r,e)=>{if(Pe(r)){let t=r.export({format:"jwk"});return delete t.d,delete t.dp,delete t.dq,delete t.p,delete t.q,delete t.qi,t.k?Re(t.k):(G||(G=new WeakMap),le(G,r,t,e))}return q(r)?r.k?x(r.k):(G||(G=new WeakMap),le(G,r,r,e,!0)):r},dr=(r,e)=>{if(Pe(r)){let t=r.export({format:"jwk"});return t.k?Re(t.k):(V||(V=new WeakMap),le(V,r,t,e))}return q(r)?r.k?x(r.k):(V||(V=new WeakMap),le(V,r,r,e,!0)):r},lr={normalizePublicKey:cr,normalizePrivateKey:dr},z=(r,e,t=0)=>{t===0&&(e.unshift(e.length),e.unshift(6));const o=r.indexOf(e[0],t);if(o===-1)return!1;const s=r.subarray(o,o+e.length);return s.length!==e.length?!1:s.every((n,i)=>n===e[i])||z(r,e,o+1)},Ie=r=>{switch(!0){case z(r,[42,134,72,206,61,3,1,7]):return"P-256";case z(r,[43,129,4,0,34]):return"P-384";case z(r,[43,129,4,0,35]):return"P-521";case z(r,[43,101,110]):return"X25519";case z(r,[43,101,111]):return"X448";case z(r,[43,101,112]):return"Ed25519";case z(r,[43,101,113]):return"Ed448";default:throw new O("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},Oe=async(r,e,t,o,s)=>{let n,i;const a=new Uint8Array(atob(t.replace(r,"")).split("").map(h=>h.charCodeAt(0))),c=e==="spki";switch(o){case"PS256":case"PS384":case"PS512":n={name:"RSA-PSS",hash:`SHA-${o.slice(-3)}`},i=c?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":n={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${o.slice(-3)}`},i=c?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":n={name:"RSA-OAEP",hash:`SHA-${parseInt(o.slice(-3),10)||1}`},i=c?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":n={name:"ECDSA",namedCurve:"P-256"},i=c?["verify"]:["sign"];break;case"ES384":n={name:"ECDSA",namedCurve:"P-384"},i=c?["verify"]:["sign"];break;case"ES512":n={name:"ECDSA",namedCurve:"P-521"},i=c?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{const h=Ie(a);n=h.startsWith("P-")?{name:"ECDH",namedCurve:h}:{name:h},i=c?[]:["deriveBits"];break}case"Ed25519":n={name:"Ed25519"},i=c?["verify"]:["sign"];break;case"EdDSA":n={name:Ie(a)},i=c?["verify"]:["sign"];break;default:throw new O('Invalid or unsupported "alg" (Algorithm) value')}return ae.subtle.importKey(e,a,n,!1,i)},hr=(r,e,t)=>Oe(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",r,e),ur=(r,e,t)=>Oe(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",r,e);async function fr(r,e,t){if(typeof r!="string"||r.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return ur(r,e)}async function gr(r,e,t){if(typeof r!="string"||r.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return hr(r,e)}async function fe(r,e){if(!$(r))throw new TypeError("JWK must be an object");switch(e||(e=r.alg),r.kty){case"oct":if(typeof r.k!="string"||!r.k)throw new TypeError('missing "k" (Key Value) Parameter value');return x(r.k);case"RSA":if("oth"in r&&r.oth!==void 0)throw new O('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return Ae({...r,alg:e});default:throw new O('Unsupported "kty" (Key Type) Parameter value')}}const Y=r=>r==null?void 0:r[Symbol.toStringTag],ge=(r,e,t)=>{var o,s;if(e.use!==void 0&&e.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(e.key_ops!==void 0&&((s=(o=e.key_ops).includes)==null?void 0:s.call(o,t))!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${t}`);if(e.alg!==void 0&&e.alg!==r)throw new TypeError(`Invalid key for this operation, when present its alg must be ${r}`);return!0},pr=(r,e,t,o)=>{if(!(e instanceof Uint8Array)){if(o&&q(e)){if(nr(e)&&ge(r,e,t))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!be(e))throw new TypeError(Ee(r,e,...de,"Uint8Array",o?"JSON Web Key":null));if(e.type!=="secret")throw new TypeError(`${Y(e)} instances for symmetric algorithms must be of type "secret"`)}},yr=(r,e,t,o)=>{if(o&&q(e))switch(t){case"sign":if(sr(e)&&ge(r,e,t))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(ir(e)&&ge(r,e,t))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!be(e))throw new TypeError(Ee(r,e,...de,o?"JSON Web Key":null));if(e.type==="secret")throw new TypeError(`${Y(e)} instances for asymmetric algorithms must not be of type "secret"`);if(t==="sign"&&e.type==="public")throw new TypeError(`${Y(e)} instances for asymmetric algorithm signing must be of type "private"`);if(t==="decrypt"&&e.type==="public")throw new TypeError(`${Y(e)} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&t==="verify"&&e.type==="private")throw new TypeError(`${Y(e)} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&t==="encrypt"&&e.type==="private")throw new TypeError(`${Y(e)} instances for asymmetric algorithm encryption must be of type "public"`)};function Ue(r,e,t,o){e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?pr(e,t,o,r):yr(e,t,o,r)}Ue.bind(void 0,!1);const Ne=Ue.bind(void 0,!0);function wr(r,e,t,o,s){if(s.crit!==void 0&&(o==null?void 0:o.crit)===void 0)throw new r('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||o.crit===void 0)return new Set;if(!Array.isArray(o.crit)||o.crit.length===0||o.crit.some(i=>typeof i!="string"||i.length===0))throw new r('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let n;n=e;for(const i of o.crit){if(!n.has(i))throw new O(`Extension Header Parameter "${i}" is not recognized`);if(s[i]===void 0)throw new r(`Extension Header Parameter "${i}" is missing`);if(n.get(i)&&o[i]===void 0)throw new r(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(o.crit)}function mr(r,e){const t=`SHA-${r.slice(-3)}`;switch(r){case"HS256":case"HS384":case"HS512":return{hash:t,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:t,name:"RSA-PSS",saltLength:r.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:t,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:t,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:e.name};default:throw new O(`alg ${r} is not supported either by JOSE or your javascript runtime`)}}async function vr(r,e,t){if(e=await lr.normalizePublicKey(e,r),ke(e))return er(e,r,t),e;if(e instanceof Uint8Array){if(!r.startsWith("HS"))throw new TypeError(Te(e,...de));return ae.subtle.importKey("raw",e,{hash:`SHA-${r.slice(-3)}`,name:"HMAC"},!1,[t])}throw new TypeError(Te(e,...de,"Uint8Array","JSON Web Key"))}const _r=async(r,e,t,o)=>{const s=await vr(r,e,"verify");or(r,s);const n=mr(r,s.algorithm);try{return await ae.subtle.verify(n,s,t,o)}catch{return!1}};async function kr(r,e,t){if(!$(r))throw new T("Flattened JWS must be an object");if(r.protected===void 0&&r.header===void 0)throw new T('Flattened JWS must have either of the "protected" or "header" members');if(r.protected!==void 0&&typeof r.protected!="string")throw new T("JWS Protected Header incorrect type");if(r.payload===void 0)throw new T("JWS Payload missing");if(typeof r.signature!="string")throw new T("JWS Signature missing or incorrect type");if(r.header!==void 0&&!$(r.header))throw new T("JWS Unprotected Header incorrect type");let o={};if(r.protected)try{const se=x(r.protected);o=JSON.parse(ee.decode(se))}catch{throw new T("JWS Protected Header is invalid")}if(!rr(o,r.header))throw new T("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const s={...o,...r.header},n=wr(T,new Map([["b64",!0]]),void 0,o,s);let i=!0;if(n.has("b64")&&(i=o.b64,typeof i!="boolean"))throw new T('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=s;if(typeof a!="string"||!a)throw new T('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(i){if(typeof r.payload!="string")throw new T("JWS Payload must be a string")}else if(typeof r.payload!="string"&&!(r.payload instanceof Uint8Array))throw new T("JWS Payload must be a string or an Uint8Array instance");let c=!1;typeof e=="function"?(e=await e(o,r),c=!0,Ne(a,e,"verify"),q(e)&&(e=await fe(e,a))):Ne(a,e,"verify");const h=Je(ce.encode(r.protected??""),ce.encode("."),typeof r.payload=="string"?ce.encode(r.payload):r.payload);let p;try{p=x(r.signature)}catch{throw new T("Failed to base64url decode the signature")}if(!await _r(a,e,p,h))throw new Ce;let C;if(i)try{C=x(r.payload)}catch{throw new T("Failed to base64url decode the payload")}else typeof r.payload=="string"?C=ce.encode(r.payload):C=r.payload;const I={payload:C};return r.protected!==void 0&&(I.protectedHeader=o),r.header!==void 0&&(I.unprotectedHeader=r.header),c?{...I,key:e}:I}async function Cr(r,e,t){if(r instanceof Uint8Array&&(r=ee.decode(r)),typeof r!="string")throw new T("Compact JWS must be a string or Uint8Array");const{0:o,1:s,2:n,length:i}=r.split(".");if(i!==3)throw new T("Invalid Compact JWS");const a=await kr({payload:s,protected:o,signature:n},e),c={payload:a.payload,protectedHeader:a.protectedHeader};return typeof e=="function"?{...c,key:a.key}:c}const Ke=x;function We(r){let e;if(typeof r=="string"){const t=r.split(".");(t.length===3||t.length===5)&&([e]=t)}else if(typeof r=="object"&&r)if("protected"in r)e=r.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof e!="string"||!e)throw new Error;const t=JSON.parse(ee.decode(Ke(e)));if(!$(t))throw new Error;return t}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}function Sr(r){if(typeof r!="string")throw new J("JWTs must use Compact JWS serialization, JWT must be a string");const{1:e,length:t}=r.split(".");if(t===5)throw new J("Only JWTs using Compact JWS serialization can be decoded");if(t!==3)throw new J("Invalid JWT");if(!e)throw new J("JWTs must contain a payload");let o;try{o=Ke(e)}catch{throw new J("Failed to base64url decode the payload")}let s;try{s=JSON.parse(ee.decode(o))}catch{throw new J("Failed to parse the decoded payload as JSON")}if(!$(s))throw new J("Invalid JWT Claims Set");return s}const E=class k{static flowNames(e){let t={};return e.forEach(o=>{o in k.flowName&&(t[o]=k.flowName[o])}),t}static isValidFlow(e){return k.allFlows().includes(e)}static areAllValidFlows(e){let t=!0;return e.forEach(o=>{k.isValidFlow(o)||(t=!1)}),t}static allFlows(){return[k.AuthorizationCode,k.AuthorizationCodeWithPKCE,k.ClientCredentials,k.RefreshToken,k.DeviceCode,k.Password,k.PasswordMfa,k.OidcAuthorizationCode]}static grantType(e){switch(e){case k.AuthorizationCode:case k.AuthorizationCodeWithPKCE:case k.OidcAuthorizationCode:return["authorization_code"];case k.ClientCredentials:return["client_credentials"];case k.RefreshToken:return["refresh_token"];case k.Password:return["password"];case k.PasswordMfa:return["http://auth0.com/oauth/grant-type/mfa-otp","http://auth0.com/oauth/grant-type/mfa-oob"];case k.DeviceCode:return["urn:ietf:params:oauth:grant-type:device_code"]}}};u(E,"All","all"),u(E,"AuthorizationCode","authorizationCode"),u(E,"AuthorizationCodeWithPKCE","authorizationCodeWithPKCE"),u(E,"ClientCredentials","clientCredentials"),u(E,"RefreshToken","refreshToken"),u(E,"DeviceCode","deviceCode"),u(E,"Password","password"),u(E,"PasswordMfa","passwordMfa"),u(E,"OidcAuthorizationCode","oidcAuthorizationCode"),u(E,"flowName",{[E.AuthorizationCode]:"Authorization Code",[E.AuthorizationCodeWithPKCE]:"Authorization Code with PKCE",[E.ClientCredentials]:"Client Credentials",[E.RefreshToken]:"Refresh Token",[E.DeviceCode]:"Device Code",[E.Password]:"Password",[E.PasswordMfa]:"Password MFA",[E.OidcAuthorizationCode]:"OIDC Authorization Code"});var b,P;class Tr{constructor({authServerBaseUrl:e,client_id:t,client_secret:o,redirect_uri:s,codeChallengeMethod:n,stateLength:i,verifierLength:a,tokenConsumer:c,authServerCredentials:h,authServerMode:p,authServerHeaders:C}){u(this,"authServerBaseUrl",""),ve(this,b),ve(this,P),u(this,"codeChallengeMethod","S256"),u(this,"verifierLength",32),u(this,"redirect_uri"),u(this,"stateLength",32),u(this,"authzCode",""),u(this,"oidcConfig"),u(this,"tokenConsumer"),u(this,"authServerHeaders",{}),u(this,"authServerMode"),u(this,"authServerCredentials"),u(this,"oauthPostType","json"),u(this,"oauthLogFetch",!1),u(this,"oauthUseUserInfoEndpoint",!1),u(this,"oauthAuthorizeRedirect"),this.tokenConsumer=c,this.authServerBaseUrl=e,a&&(this.verifierLength=a),i&&(this.stateLength=i),t&&ne(this,b,t),o&&ne(this,P,o),s&&(this.redirect_uri=s),n&&(this.codeChallengeMethod=n),this.authServerBaseUrl=e,h&&(this.authServerCredentials=h),p&&(this.authServerMode=p),C&&(this.authServerHeaders=C)}set client_id(e){ne(this,b,e)}set client_secret(e){ne(this,P,e)}async loadConfig(e){if(e){d.logger.debug(l({msg:"Reading OIDC config locally"})),this.oidcConfig=e;return}let t;try{const o=new URL(this.authServerBaseUrl+"/.well-known/openid-configuration");d.logger.debug(l({msg:`Fetching OIDC config from ${o}`}));let s={headers:this.authServerHeaders};this.authServerMode&&(s.mode=this.authServerMode),this.authServerCredentials&&(s.credentials=this.authServerCredentials),t=await fetch(o,s)}catch(o){d.logger.error(l({err:o}))}if(!t||!t.ok)throw new g(_.Connection,"Couldn't get OIDC configuration from URL"+this.authServerBaseUrl+"/.well-known/openid-configuration");this.oidcConfig={..._e};try{const o=await t.json();for(const[s,n]of Object.entries(o))this.oidcConfig[s]=n}catch{throw new g(_.Connection,"Unrecognized response from OIDC configuration endpoint")}}getOidcConfig(){return this.oidcConfig}async startAuthorizationCodeFlow(e,{scope:t,codeChallenge:o,pkce:s=!1,upstream:n}){var i,a,c;if(d.logger.debug(l({msg:"Starting authorization code flow, scope "+t})),this.oidcConfig||await this.loadConfig(),!((i=this.oidcConfig)!=null&&i.response_types_supported.includes("code"))||!((a=this.oidcConfig)!=null&&a.response_modes_supported.includes("query")))return{error:"invalid_request",error_description:"Server does not support authorization code flow"};if(!((c=this.oidcConfig)!=null&&c.authorization_endpoint))return{error:"server_error",error_description:"Cannot get authorize endpoint"};if(!m(this,b))return{error:"invalid_request",error_description:"Cannot make authorization code flow without client id"};if(!this.redirect_uri)return{error:"invalid_request",error_description:"Cannot make authorization code flow without Redirect Uri"};let h=this.oidcConfig.authorization_endpoint;this.oauthAuthorizeRedirect&&(h=this.oauthAuthorizeRedirect);let p=h+"?response_type=code&client_id="+encodeURIComponent(m(this,b))+"&state="+encodeURIComponent(e)+"&redirect_uri="+encodeURIComponent(this.redirect_uri);return t&&(p+="&scope="+encodeURIComponent(t)),s&&o&&(p+="&code_challenge="+o),{url:p}}async codeChallengeAndVerifier(){const e=this.randomValue(this.verifierLength);return{codeChallenge:this.codeChallengeMethod=="plain"?e:await this.sha256(e),codeVerifier:e}}async getIdPayload(e,t){let o,s;try{let n;if(n=await this.validateIdToken(e),!n)return o="access_denied",s="Invalid ID token received",{error:o,error_description:s};if(t&&this.oauthUseUserInfoEndpoint){const i=await this.userInfoEndpoint(t);if(i.error)return o=i.error,s="Failed getting user info: "+(i.error_description??"unknown error"),{error:o,error_description:s};n={...n,...i}}return{payload:n}}catch(n){const i=g.asCrossauthError(n);return d.logger.debug(l({err:i})),d.logger.error(l({msg:"Couldn't get user info",cerr:i})),o=i.oauthErrorCode,s="Couldn't get user info: "+i.message,{error:o,error_description:s}}}async getAccessPayload(e,t){let o,s;try{let n;return n=await this.validateAccessToken(e,t),n?{payload:n}:(o="access_denied",s="Invalid access token received",{error:o,error_description:s})}catch(n){const i=g.asCrossauthError(n);return d.logger.debug(l({err:i})),d.logger.error(l({msg:"Couldn't get user info",cerr:i})),o=i.oauthErrorCode,s="Couldn't get user info: "+i.message,{error:o,error_description:s}}}async redirectEndpoint({code:e,scope:t,codeVerifier:o,error:s,errorDescription:n}){var i,a;if(this.oidcConfig||await this.loadConfig(),s||!e)return s||(s="server_error"),n||(n="Unknown error"),{error:s,error_description:n};if(this.authzCode=e,!((i=this.oidcConfig)!=null&&i.grant_types_supported.includes("authorization_code")))return{error:"invalid_request",error_description:"Server does not support authorization code grant"};if(!((a=this.oidcConfig)!=null&&a.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const c=this.oidcConfig.token_endpoint;let h,p;h="authorization_code",p=m(this,P);let C={grant_type:h,client_id:m(this,b),code:this.authzCode,redirect_uri:this.redirect_uri};t&&(C.scope=t),p&&(C.client_secret=p),o&&(C.code_verifier=o);try{let I=await this.post(c,C,this.authServerHeaders);if(I.id_token){const se=await this.getIdPayload(I.id_token,I.access_token);if(se.error)return se;I.id_payload=se.payload}return I}catch(I){return d.logger.error(l({err:I})),{error:"server_error",error_description:"Unable to get access token from server"}}}async clientCredentialsFlow(e){var t,o;if(d.logger.debug(l({msg:"Starting client credentials flow"})),this.oidcConfig||await this.loadConfig(),!((t=this.oidcConfig)!=null&&t.grant_types_supported.includes("client_credentials")))return{error:"invalid_request",error_description:"Server does not support client credentials grant"};if(!((o=this.oidcConfig)!=null&&o.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};if(!m(this,b))return{error:"invalid_request",error_description:"Cannot make client credentials flow without client id"};const s=this.oidcConfig.token_endpoint;let n={grant_type:"client_credentials",client_id:m(this,b),client_secret:m(this,P)};e&&(n.scope=e);try{let i=await this.post(s,n,this.authServerHeaders);if(i.id_token){const a=await this.getIdPayload(i.id_token,i.access_token);if(a.error)return a;i.id_payload=a.payload}return i}catch(i){return d.logger.error(l({err:i})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async passwordFlow(e,t,o){var s,n;if(d.logger.debug(l({msg:"Starting password flow"})),this.oidcConfig||await this.loadConfig(),!((s=this.oidcConfig)!=null&&s.grant_types_supported.includes("password")))return{error:"invalid_request",error_description:"Server does not support password grant"};if(!((n=this.oidcConfig)!=null&&n.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const i=this.oidcConfig.token_endpoint;let a={grant_type:"password",client_id:m(this,b),client_secret:m(this,P),username:e,password:t};o&&(a.scope=o);try{let c=await this.post(i,a,this.authServerHeaders);if(c.id_token){const h=await this.getIdPayload(c.id_token,c.access_token);if(h.error)return h;c.id_payload=h.payload}return c}catch(c){return d.logger.error(l({err:c})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async mfaAuthenticators(e){var t,o,s;if(d.logger.debug(l({msg:"Getting valid MFA authenticators"})),this.oidcConfig||await this.loadConfig(),!((t=this.oidcConfig)!=null&&t.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp"))&&(o=this.oidcConfig)!=null&&o.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-oob"))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((s=this.oidcConfig)!=null&&s.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const n=this.oidcConfig.issuer+(this.oidcConfig.issuer.endsWith("/")?"":"/")+"mfa/authenticators",i=await this.get(n,{authorization:"Bearer "+e,...this.authServerHeaders});if(!Array.isArray(i))return{error:"server_error",error_description:"Expected array of authenticators in mfa/authenticators response"};let a=[];for(let c=0;c<i.length;++c){const h=i[c];if(!h.id||!h.authenticator_type||!h.active)return{error:"server_error",error_description:"Invalid mfa/authenticators response"};a.push({id:h.id,authenticator_type:h.authenticator_type,active:h.active,name:h.name,oob_channel:h.oob_channel})}return{authenticators:a}}async mfaOtpRequest(e,t){var o,s;if(d.logger.debug(l({msg:"Making MFA OTB request"})),this.oidcConfig||await this.loadConfig(),!((o=this.oidcConfig)!=null&&o.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((s=this.oidcConfig)!=null&&s.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const n=this.oidcConfig.issuer+(this.oidcConfig.issuer.endsWith("/")?"":"/")+"mfa/challenge",i=await this.post(n,{client_id:m(this,b),client_secret:m(this,P),challenge_type:"otp",mfa_token:e,authenticator_id:t},this.authServerHeaders);return i.challenge_type!="otp"?{error:i.error??"server_error",error_description:i.error_description??"Invalid OTP challenge response"}:i}async mfaOtpComplete(e,t,o){var s,n;if(d.logger.debug(l({msg:"Completing MFA OTP request"})),this.oidcConfig||await this.loadConfig(),!((s=this.oidcConfig)!=null&&s.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((n=this.oidcConfig)!=null&&n.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const i=this.oidcConfig.token_endpoint,a=await this.post(i,{grant_type:"http://auth0.com/oauth/grant-type/mfa-otp",client_id:m(this,b),client_secret:m(this,P),challenge_type:"otp",mfa_token:e,otp:t,scope:o},this.authServerHeaders);if(a.id_token){const c=await this.getIdPayload(a.id_token,a.access_token);if(c.error)return c;a.id_payload=c.payload}return{id_token:a.id_token,access_token:a.access_token,refresh_token:a.refresh_token,expires_in:Number(a.expires_in),scope:a.scope,token_type:a.token_type,error:a.error,error_description:a.error_description}}async mfaOobRequest(e,t){var o,s;if(d.logger.debug(l({msg:"Making MFA OOB request"})),this.oidcConfig||await this.loadConfig(),!((o=this.oidcConfig)!=null&&o.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((s=this.oidcConfig)!=null&&s.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const n=this.oidcConfig.issuer+(this.oidcConfig.issuer.endsWith("/")?"":"/")+"mfa/challenge",i=await this.post(n,{client_id:m(this,b),client_secret:m(this,P),challenge_type:"oob",mfa_token:e,authenticator_id:t},this.authServerHeaders);return i.challenge_type!="oob"||!i.oob_code||!i.binding_method?{error:i.error??"server_error",error_description:i.error_description??"Invalid OOB challenge response"}:{challenge_type:i.challenge_type,oob_code:i.oob_code,binding_method:i.binding_method,error:i.error,error_description:i.error_description}}async mfaOobComplete(e,t,o,s){var n,i;if(d.logger.debug(l({msg:"Completing MFA OOB request"})),this.oidcConfig||await this.loadConfig(),!((n=this.oidcConfig)!=null&&n.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-oob")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((i=this.oidcConfig)!=null&&i.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const a=this.oidcConfig.token_endpoint,c=await this.post(a,{grant_type:"http://auth0.com/oauth/grant-type/mfa-oob",client_id:m(this,b),client_secret:m(this,P),challenge_type:"otp",mfa_token:e,oob_code:t,binding_code:o,scope:s},this.authServerHeaders);if(c.error)return{error:c.error,error_description:c.error_description};if(c.id_token){const h=await this.getIdPayload(c.id_token,c.access_token);if(h.error)return h;c.id_payload=h.payload}return{id_token:c.id_token,access_token:c.access_token,refresh_token:c.refresh_token,expires_in:"expires_in"in c?Number(c.expires_in):void 0,scope:c.scope,token_type:c.token_type}}async refreshTokenFlow(e){var t,o;if(d.logger.debug(l({msg:"Starting refresh token flow"})),this.oidcConfig||await this.loadConfig(),!((t=this.oidcConfig)!=null&&t.grant_types_supported.includes("refresh_token")))return{error:"invalid_request",error_description:"Server does not support refresh_token grant"};if(!((o=this.oidcConfig)!=null&&o.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const s=this.oidcConfig.token_endpoint;let n;n=m(this,P);let i={grant_type:"refresh_token",refresh_token:e,client_id:m(this,b)};n&&(i.client_secret=n);try{let a=await this.post(s,i,this.authServerHeaders);if(a.id_token){const c=await this.getIdPayload(a.id_token,a.access_token);if(c.error)return c;a.id_payload=c.payload}return a}catch(a){return d.logger.error(l({err:a})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async startDeviceCodeFlow(e,t){var o;if(d.logger.debug(l({msg:"Starting device code flow"})),this.oidcConfig||await this.loadConfig(),!((o=this.oidcConfig)!=null&&o.grant_types_supported.includes("urn:ietf:params:oauth:grant-type:device_code")))return{error:"invalid_request",error_description:"Server does not support device code grant"};let s={grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:m(this,b),client_secret:m(this,P)};t&&(s.scope=t);try{let n=await this.post(e,s,this.authServerHeaders);return n.id_token&&!await this.validateIdToken(n.id_token)?{error:"access_denied",error_description:"Invalid ID token"}:n}catch(n){return d.logger.error(l({err:n})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async pollDeviceCodeFlow(e){var t,o,s;if(d.logger.debug(l({msg:"Starting device code flow"})),this.oidcConfig||await this.loadConfig(),!((t=this.oidcConfig)!=null&&t.grant_types_supported.includes("urn:ietf:params:oauth:grant-type:device_code")))return{error:"invalid_request",error_description:"Server does not support device code grant"};if(!((o=this.oidcConfig)!=null&&o.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};let n={grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:m(this,b),client_secret:m(this,P),device_code:e};try{const i=await this.post((s=this.oidcConfig)==null?void 0:s.token_endpoint,n,this.authServerHeaders);if(i.error)return i;if(i.id_token){const a=await this.getIdPayload(i.id_token,i.access_token);if(a.error)return a;i.id_payload=a.payload}return i}catch(i){return d.logger.error(l({err:i})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async userInfoEndpoint(e){var t;if(!((t=this.oidcConfig)!=null&&t.userinfo_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const o=this.oidcConfig.userinfo_endpoint;return await this.post(o,{},{authorization:"Bearer "+e})}async post(e,t,o={},s){d.logger.debug(l({msg:"Fetch POST",url:e,params:Object.keys(t)}));let n={};this.authServerCredentials&&(n.credentials=this.authServerCredentials),this.authServerMode&&(n.mode=this.authServerMode);let i="",a="";if(this.oauthPostType=="json")i=JSON.stringify(t),a="application/json";else{i="";for(let p in t)i!=""&&(i+="&"),i+=encodeURIComponent(p)+"="+encodeURIComponent(t[p]);a="application/x-www-form-urlencoded"}this.oauthLogFetch&&d.logger.debug(l({msg:"OAuth fetch",method:"POST",url:e,body:i}));let c={};s&&(c=s);const h=await fetch(e,{method:"POST",...n,headers:{Accept:"application/json","Content-Type":a,...o},...c,body:i});try{const p=await h.clone().json();return this.oauthLogFetch&&d.logger.debug(l({msg:"OAuth fetch response",body:JSON.stringify(p)})),await h.json(),p}catch(p){let C=g.asCrossauthError(p);throw i=await h.text(),d.logger.debug(l({msg:"Response is not JSON",response:i})),C}}async get(e,t={}){d.logger.debug(l({msg:"Fetch GET",url:e}));let o={};this.authServerCredentials&&(o.credentials=this.authServerCredentials),this.authServerMode&&(o.mode=this.authServerMode),this.oauthLogFetch&&d.logger.debug(l({msg:"OAuth fetch",method:"GET",url:e}));const s=await(await fetch(e,{method:"GET",...o,headers:{Accept:"application/json",...t}})).json();return this.oauthLogFetch&&d.logger.debug(l({msg:"OAuth fetch response",body:JSON.stringify(s)})),s}async validateIdToken(e){try{return await this.tokenConsumer.tokenAuthorized(e,"id")}catch{return}}async validateAccessToken(e,t){try{return await this.tokenConsumer.tokenAuthorized(e,"access",t)}catch{return}}async idTokenAuthorized(e,t){try{return await this.tokenConsumer.tokenAuthorized(e,"id",t)}catch(o){d.logger.warn(l({err:o}));return}}getTokenPayload(e){return Sr(e)}}b=new WeakMap,P=new WeakMap;class Er{constructor(e,t={}){if(u(this,"audience"),u(this,"jwtKeyType"),u(this,"jwtSecretKey"),u(this,"jwtPublicKey"),u(this,"clockTolerance",10),u(this,"authServerBaseUrl",""),u(this,"oidcConfig"),u(this,"keys",{}),this.audience=e,t.authServerBaseUrl&&(this.authServerBaseUrl=t.authServerBaseUrl),t.jwtKeyType&&(this.jwtKeyType=t.jwtKeyType),t.jwtSecretKey&&(this.jwtSecretKey=t.jwtSecretKey),t.jwtPublicKey&&(this.jwtPublicKey=t.jwtPublicKey),t.clockTolerance&&(this.clockTolerance=t.clockTolerance),t.oidcConfig&&(this.oidcConfig=t.oidcConfig),this.jwtPublicKey&&!this.jwtKeyType)throw new g(_.Configuration,"If specifying jwtPublic key, must also specify jwtKeyType")}async loadKeys(e){try{if(this.jwtSecretKey){if(!this.jwtKeyType)throw new g(_.Configuration,"Must specify jwtKeyType if setting jwtSecretKey");this.keys._default=await gr(this.jwtSecretKey,this.jwtKeyType)}else if(this.jwtPublicKey){if(!this.jwtKeyType)throw new g(_.Configuration,"Must specify jwtKeyType if setting jwtPublicKey");const t=await fr(this.jwtPublicKey,this.jwtKeyType);this.keys._default=t}else{if(this.oidcConfig||await this.loadConfig(),!this.oidcConfig)throw new g(_.Connection,"Load OIDC config before Jwks");await this.loadJwks(void 0,e)}}catch(t){throw d.logger.debug(l({err:t})),new g(_.Connection,"Couldn't load keys")}}async loadConfig(e){if(e){this.oidcConfig=e;return}if(!this.authServerBaseUrl)throw new g(_.Connection,"Couldn't get OIDC configuration. Either set authServerBaseUrl or set config manually");let t;try{let o=this.authServerBaseUrl;o.endsWith("/")||(o+="/"),t=await fetch(new URL(".well-known/openid-configuration",o))}catch(o){d.logger.error(l({err:o}))}if(!t||!t.ok)throw new g(_.Connection,"Couldn't get OIDC configuration");this.oidcConfig={..._e};try{const o=await t.json();for(const[s,n]of Object.entries(o))this.oidcConfig[s]=n}catch{throw new g(_.Connection,"Unrecognized response from OIDC configuration endpoint")}}async loadJwks(e,t){if(e){this.keys={};for(let o=0;o<e.keys.length;++o){const s=e.keys[o],n="kid"in s&&s.kid?s.kid:"_default";this.keys[n]=await fe(e.keys[o])}}else{if(!this.oidcConfig)throw new g(_.Connection,"Load OIDC config before Jwks");let o;try{o=await fetch(new URL(this.oidcConfig.jwks_uri))}catch(s){d.logger.error(l({err:s}))}if(!o||!o.ok)throw new g(_.Connection,"Couldn't get OIDC configuration");this.keys={};try{const s=await o.json();if(!("keys"in s)||!Array.isArray(s.keys))throw new g(_.Connection,"Couldn't fetch keys");for(let n=0;n<s.keys.length;++n)try{let i="_default",a={...s.keys[n]};if("kid"in a&&typeof a.kid=="string"&&(i=String(a.kid)),a&&!a.alg&&!a.jwk_alg&&t)if(t.startsWith("RS")&&a.kty=="RSA")a.alg=t;else{d.logger.debug(l({msg:"Skipping key with "+a.kty}));continue}const c=await fe(a);this.keys[i]=c}catch(i){throw d.logger.error(l({err:i})),new g(_.Connection,"Couldn't load keys")}}catch(s){throw d.logger.error(l({err:s})),new g(_.Connection,"Unrecognized response from OIDC jwks endpoint")}}}async tokenAuthorized(e,t,o){if(!this.keys||Object.keys(this.keys).length==0){const n=We(e);await this.loadKeys(n.alg)}const s=await this.validateToken(e);if(s){if(s.iss!=this.authServerBaseUrl){const n=s.jti?s.jti:s.sid?s.sid:"";d.logger.error(l({msg:`Invalid issuer ${s.iss} ${t} token`,hashedAccessToken:await this.hash(n)}));return}if(o!=!1&&s.aud){const n=s.jti?s.jti:s.sid?s.sid:"";if(Array.isArray(s.aud)&&!s.aud.includes(this.audience)||!Array.isArray(s.aud)&&s.aud!=this.audience){d.logger.error(l({msg:`Invalid audience ${s.aud} in ${t} token`,hashedAccessToken:await this.hash(n)}));return}}return s}}async validateToken(e){(!this.keys||Object.keys(this.keys).length==0)&&d.logger.warn("No keys loaded so cannot validate tokens");let t;try{t=We(e).kid}catch{d.logger.warn(l({msg:"Invalid access token format"}));return}let o;for(let s in this.keys)if(t==s){o=this.keys[s];break}if(!o&&"_default"in this.keys&&(o=this.keys._default),!o){d.logger.warn(l({msg:"No matching keys found for access token"}));return}try{const{payload:s}=await Cr(e,o),n=JSON.parse(new TextDecoder().decode(s));if(n.exp*1e3<Date.now()+this.clockTolerance){d.logger.warn(l({msg:"Access token has expired"}));return}return n}catch(s){const n=g.asCrossauthError(s);d.logger.debug(l({err:n})),d.logger.warn(l({msg:"Access token did not validate",cerr:n}));return}}}const De=30,he=2,pe=30;class ye{constructor(e){f(this,"autoRefreshUrl","/autorefresh");f(this,"csrfHeader","X-CROSSAUTH-CSRF");f(this,"headers",{});f(this,"autoRefreshActive",!1);f(this,"mode","cors");f(this,"credentials","same-origin");f(this,"tokenProvider");this.tokenProvider=e.tokenProvider,this.autoRefreshUrl=e.autoRefreshUrl,e.csrfHeader&&(this.csrfHeader=e.csrfHeader),e.headers&&(this.headers=e.headers),e.mode&&(this.mode=e.mode),e.credentials&&(this.credentials=e.credentials)}async startAutoRefresh(e=["access","id"],t){if(!this.autoRefreshActive){this.autoRefreshActive=!0,d.logger.debug(l({msg:"Starting auto refresh"}));try{await this.scheduleAutoRefresh(e,t)}catch(o){const s=g.asCrossauthError(o);d.logger.error(l({cerr:s})),d.logger.debug(l({err:s}))}}}stopAutoRefresh(){this.autoRefreshActive=!1,d.logger.debug(l({msg:"Stopping auto refresh"}))}async scheduleAutoRefresh(e,t){let o;const s=this.tokenProvider.getCsrfToken(),n=s?await s:void 0,i=await this.tokenProvider.getTokenExpiries([...e,"refresh"],n);if(i.refresh==null){d.logger.debug(l({msg:"No refresh token found"}));return}const a=Date.now();let c=i.id;if((!c||i.access&&i.access<c)&&(c=i.access),!c){d.logger.debug(l({msg:"No tokens expire"}));return}let h=c*1e3-a-De;if(h<0&&o!=null&&o<=0){d.logger.debug(l({msg:"Expiry time has passed"}));return}if(h<0&&(h=0),i.refresh&&i.refresh-De<h){d.logger.debug(l({msg:"Refresh token has expired"}));return}let p=C=>new Promise(I=>setTimeout(I,C));d.logger.debug(l({msg:`Waiting ${h} before refreshing tokens`})),o=h,await p(h),await this.autoRefresh(e,n,t)}async autoRefresh(e,t,o){if(this.autoRefreshActive){let s,n=!1,i=0;for(;!n&&i<=he;)try{let a={...this.headers};t&&(a[this.csrfHeader]=t),d.logger.debug(l({msg:"Initiating auto refresh"}));const c=await this.tokenProvider.jsonFetchWithToken(this.autoRefreshUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...a},mode:this.mode,credentials:this.credentials,body:{csrfToken:t}},"refresh");c.ok||d.logger.error(l({msg:"Failed auto refreshing tokens",status:c.status}));try{s=await c.json()}catch{try{d.logger.error(l({msg:"/refresh returned a non-JSON response "+(s?await s.text():void 0)}))}catch{d.logger.error(l({msg:"/refresh returned a with no body "}))}s={ok:!1,error:"Unknown"}}if(s!=null&&s.ok){await this.scheduleAutoRefresh(e,o),n=!0;try{await this.tokenProvider.receiveTokens(s)}catch(h){const p=g.asCrossauthError(h);o?o("Couldn't receive tokens",p):(d.logger.debug(l({err:h})),d.logger.error(l({msg:"Error receiving tokens",cerr:p})))}}else i<he?(d.logger.error(l({msg:`Failed auto refreshing tokens. Retrying in ${pe} seconds`})),await(p=>new Promise(C=>setTimeout(C,p)))(pe*1e3)):(d.logger.error(l({msg:"Failed auto refreshing tokens. Number of retries exceeded"})),o&&o("Failed auto refreshing tokens")),i++}catch(a){const c=g.asCrossauthError(a);d.logger.debug(l({err:c})),i<he?(d.logger.error(l({msg:`Failed auto refreshing tokens. Retrying in ${he} seconds`})),await(p=>new Promise(C=>setTimeout(C,p)))(pe*1e3)):(d.logger.error(l({msg:"Failed auto refreshing tokens. Number of retries exceeded"})),o&&o(c.message,c)),i++}}}}class we{constructor(e){f(this,"deviceCodePollUrl","/devicecodepoll");f(this,"headers",{});f(this,"pollingActive",!1);f(this,"mode","cors");f(this,"credentials","same-origin");f(this,"respectRedirect",!0);f(this,"oauthClient");this.oauthClient=e.oauthClient,e.deviceCodePollUrl!=null&&(this.deviceCodePollUrl=e.deviceCodePollUrl),e.headers&&(this.headers=e.headers),e.mode&&(this.mode=e.mode),e.credentials&&(this.credentials=e.credentials)}async startPolling(e,t,o=5){this.pollingActive||(this.pollingActive=!0,d.logger.debug(l({msg:"Starting auto refresh"})),await this.poll(e,o,t))}stopPolling(){this.pollingActive=!1,d.logger.debug(l({msg:"Stopping auto refresh"}))}async poll(e,t,o){var s;if(!e)d.logger.debug(l({msg:"device code poll: no device code provided"})),o("error","Error waiting for authorization");else try{if(d.logger.debug(l({msg:"device code poll: poll"})),!this.deviceCodePollUrl&&this.oauthClient){if(this.oauthClient.getOidcConfig()||await this.oauthClient.loadConfig(),!((s=this.oauthClient.getOidcConfig())!=null&&s.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-oob")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};let i=this.oauthClient.getOidcConfig();if(!(i!=null&&i.token_endpoint))return{error:"server_error",error_description:"Couldn't get OIDC configuration"};this.deviceCodePollUrl=i.token_endpoint}if(!this.deviceCodePollUrl)return{error:"server_error",error_description:"Must either provide deviceCodePollUrl or an oauthClient to fetch it from"};const n=await fetch(this.deviceCodePollUrl,{method:"POST",body:JSON.stringify({device_code:e}),headers:{"content-type":"application/json"}});if(n.redirected)this.pollingActive=!1,n.redirected&&o("completeAndRedirect",void 0,n.url);else if(!n.ok)this.pollingActive=!1,o("error","Received an error from the authorization server");else{const i=await n.json();if(d.logger.debug(l({msg:"device code poll: received"+JSON.stringify(i)})),i.error=="expired_token")this.pollingActive=!1,o("expired_token","Timeout waiting for authorization");else if(i.error=="authorization_pending"||i.error=="slow_down"){i.error=="slow_down"&&(t+=5);let a=i.interval??t,c=h=>new Promise(p=>setTimeout(p,h));d.logger.debug(l({msg:"device code poll: waiting "+String(a)+" seconds"})),await c(a*1e3),this.pollingActive&&this.poll(e,t,o)}else i.error?(this.pollingActive=!1,o("error",i.error_description??i.error)):(this.pollingActive=!1,o("complete"))}}catch(n){this.pollingActive=!1;const i=g.asCrossauthError(n);d.logger.debug(l({err:i})),d.logger.error(l({msg:"Polling failed",cerr:i})),o("error",i.message)}}}class br{constructor(e={}){f(this,"bffPrefix","/bff");f(this,"csrfHeader","X-CROSSAUTH-CSRF");f(this,"enableCsrfProtection",!0);f(this,"headers",{});f(this,"mode","cors");f(this,"credentials","same-origin");f(this,"autoRefresher");f(this,"deviceCodePoller");f(this,"getCsrfTokenUrl","/api/getcsrftoken");f(this,"autoRefreshUrl","/api/refreshtokens");f(this,"tokensUrl","/tokens");e.bffPrefix&&(this.bffPrefix=e.bffPrefix),e.csrfHeader&&(this.csrfHeader=e.csrfHeader),e.enableCsrfProtection!=null&&(this.enableCsrfProtection=e.enableCsrfProtection),e.getCsrfTokenUrl&&(this.getCsrfTokenUrl=e.getCsrfTokenUrl),e.tokensUrl&&(this.tokensUrl=e.tokensUrl),e.autoRefreshUrl&&(this.autoRefreshUrl=e.autoRefreshUrl),this.bffPrefix.endsWith("/")||(this.bffPrefix+="/"),e.headers&&(this.headers=e.headers),e.mode&&(this.mode=e.mode),e.credentials&&(this.credentials=e.credentials),this.autoRefresher=new ye({...e,autoRefreshUrl:this.autoRefreshUrl,tokenProvider:this}),this.deviceCodePoller=new we({...e,oauthClient:void 0})}async getCsrfToken(){if(this.enableCsrfProtection)try{const t=await(await fetch(this.getCsrfTokenUrl,{headers:this.headers,credentials:this.credentials,mode:this.mode})).json();if(!t.ok)throw g.asCrossauthError(t);return t.csrfToken}catch(e){throw g.asCrossauthError(e)}}async getIdToken(e){const t=await this.getTokens(e);return(t==null?void 0:t.id_token)??null}async haveIdToken(e){const t=await this.getTokens(e);return t==null?!1:t.have_id_token!=null?t.have_id_token:"id_token"in t}async getAccessToken(e){const t=await this.getTokens(e);return(t==null?void 0:t.access_token)??null}async haveAccessToken(e){const t=await this.getTokens(e);return t==null?!1:t.have_access_token!=null?t.have_access_token:"access_token"in t}async getRefreshToken(e){const t=await this.getTokens(e);return(t==null?void 0:t.refresh_token)??null}async haveRefreshToken(e){const t=await this.getTokens(e);return t==null?!1:t.have_refresh_token!=null?t.have_refresh_token:"refresh_token"in t}async api(e,t,o,s){let n={...this.headers};!s&&!["GET","HEAD","OPTIONS"].includes(e)&&(s=await this.getCsrfToken(),s&&(n[this.csrfHeader]=s)),t.startsWith("/")&&(t=t.substring(1));let i={};o&&(i.body=JSON.stringify(o));const a=await fetch(this.bffPrefix+t,{headers:n,method:e,mode:this.mode,credentials:this.credentials,...i});let c=null;return a.body&&(c=await a.json()),{status:a.status,body:c}}async getTokens(e){e||(e=await this.getCsrfToken());let t={...this.headers};e&&(t[this.csrfHeader]=e);try{const o=await fetch(this.tokensUrl,{method:"POST",headers:t,mode:this.mode,credentials:this.credentials});return o.status==204?{}:await o.json()}catch(o){throw g.asCrossauthError(o)}}async startAutoRefresh(e=["access","id"],t){return this.autoRefresher.startAutoRefresh(e,t)}stopAutoRefresh(){return this.autoRefresher.stopAutoRefresh()}async startDeviceCodePolling(e,t,o=5){return this.deviceCodePoller.startPolling(e,t,o)}stopDeviceCodePolling(){return this.deviceCodePoller.stopPolling()}async getTokenExpiries(e,t){const o=await this.getTokens(t);try{const s=e.includes("id")?(o==null?void 0:o.id_token)??null:null,n=e.includes("access")?(o==null?void 0:o.access_token)??null:null,i=e.includes("refresh")?(o==null?void 0:o.refresh_token)??null:null;let a,c,h;return s&&(a=s.exp?s.exp:null),n&&(c=n.exp?n.exp:null),i&&(h=i.exp?i.exp:null),{id:a,access:c,refresh:h}}catch{return d.logger.error(l({msg:"getTokenExpiries received non JSON response "+o})),{id:0,access:0,refresh:0}}}async jsonFetchWithToken(e,t,o){return typeof t.body!="string"&&(t.body=JSON.stringify(t.body)),await fetch(e,t)}receiveTokens(e){return new Promise(t=>{})}}class Ar{getCsrfToken(){return new Promise(e=>{})}}class He extends Er{async hash(e){const o=new TextEncoder().encode(e),s=await crypto.subtle.digest("SHA-256",o),n=Array.from(new Uint8Array(s));return btoa(n.reduce((i,a)=>i+String.fromCharCode(a),"")).replace(/\//g,"_").replace(/\+/g,"-").replace(/=+$/,"")}}class Rr extends Tr{constructor(t){t.tokenConsumer||(t.tokenConsumer=new He(t.client_id,{authServerBaseUrl:t.authServerBaseUrl}));super(t);f(this,"resServerBaseUrl","");f(this,"resServerHeaders",{});f(this,"resServerMode","cors");f(this,"resServerCredentials","same-origin");f(this,"accessTokenResponseType","memory");f(this,"refreshTokenResponseType","memory");f(this,"idTokenResponseType","memory");f(this,"accessTokenName","CROSSAUTH_AT");f(this,"refreshTokenName","CROSSAUTH_RT");f(this,"idTokenName","CROSSAUTH_IT");U(this,L);U(this,j);U(this,D);U(this,F);U(this,M);U(this,X);U(this,Q);f(this,"autoRefresher");f(this,"deviceCodePoller");f(this,"deviceAuthorizationUrl","device_authorization");U(this,te);U(this,oe);U(this,Z);f(this,"scope");f(this,"logFetch",!1);this.resServerBaseUrl!=null&&(this.resServerBaseUrl=t.resServerBaseUrl??"",this.resServerBaseUrl.length>0&&!this.resServerBaseUrl.endsWith("/")&&(this.resServerBaseUrl+="/")),t.accessTokenResponseType&&(this.accessTokenResponseType=t.accessTokenResponseType),t.idTokenResponseType&&(this.idTokenResponseType=t.idTokenResponseType),t.refreshTokenResponseType&&(this.refreshTokenResponseType=t.refreshTokenResponseType),t.accessTokenName&&(this.accessTokenName=t.accessTokenName),t.idTokenName&&(this.idTokenName=t.idTokenName),t.refreshTokenName&&(this.refreshTokenName=t.refreshTokenName),t.resServerHeaders&&(this.resServerHeaders=t.resServerHeaders),t.resServerMode&&(this.resServerMode=t.resServerMode),t.resServerCredentials&&(this.resServerCredentials=t.resServerCredentials),t.client_id&&A(this,X,t.client_id),t.client_secret&&A(this,Q,t.client_secret),t.deviceAuthorizationUrl&&(this.deviceAuthorizationUrl=t.deviceAuthorizationUrl),this.autoRefresher=new ye({...t,autoRefreshUrl:this.authServerBaseUrl+"/token",tokenProvider:this}),this.deviceCodePoller=new we({...t,oauthClient:this,deviceCodePollUrl:null});let o,s,n;if(this.idTokenResponseType=="sessionStorage"?o=sessionStorage.getItem(this.idTokenName):this.idTokenResponseType=="localStorage"&&(o=localStorage.getItem(this.idTokenName)),this.accessTokenResponseType=="sessionStorage"?s=sessionStorage.getItem(this.accessTokenName):this.accessTokenResponseType=="localStorage"&&(s=localStorage.getItem(this.accessTokenName)),this.refreshTokenResponseType=="sessionStorage"?n=sessionStorage.getItem(this.refreshTokenName):this.refreshTokenResponseType=="localStorage"&&(n=localStorage.getItem(this.refreshTokenName)),this.receiveTokens({access_token:s,id_token:o,refresh_token:n}),s){const i=this.getTokenPayload(s);i&&(A(this,L,s),A(this,F,i))}if(n){const i=this.getTokenPayload(n);i&&(A(this,j,n),A(this,M,i))}o?this.validateIdToken(o).then(i=>{A(this,D,i),t.autoRefresh&&this.startAutoRefresh(t.autoRefresh).then().catch(a=>{d.logger.debug(l({err:a,msg:"Couldn't start auto refresh"}))})}).catch(i=>{d.logger.debug(l({err:i,msg:"Couldn't validate ID token"}))}):w(this,L)&&t.autoRefresh&&n?this.startAutoRefresh(t.autoRefresh).then().catch(i=>{d.logger.debug(l({err:i,msg:"Couldn't start auto refresh"}))}):n&&!s&&this.refreshTokenFlow(n).then(i=>{d.logger.debug(l({msg:"Refreshed tokens"})),t.autoRefresh&&this.startAutoRefresh(t.autoRefresh).then().catch(a=>{d.logger.debug(l({err:a,msg:"Couldn't start auto refresh"}))})}).catch(i=>{const a=g.asCrossauthError(i);d.logger.debug(l({err:a})),d.logger.error(l({msg:"failed refreshing tokens",cerr:a}))})}get idTokenPayload(){return w(this,D)}async handleRedirectUri(){const t=new URL(window.location.href);if(t.origin+t.pathname!=this.redirect_uri)return;const o=new URLSearchParams(window.location.search);let s,n,i,a;for(const[h,p]of o)h=="code"&&(s=p),h=="state"&&(n=p),h=="error"&&(i=p),h=="error_description"&&(a=p);if(!i&&!s)return;if(i){const h=g.fromOAuthError(i,a);throw d.logger.debug(l({err:h})),d.logger.error(l({cerr:h,msg:"Error from authorize endpoint: "+i})),h}if(w(this,Z)&&n!=w(this,Z))return{error:"access_denied",error_description:"Invalid state"};const c=await this.redirectEndpoint({code:s,scope:this.scope,codeVerifier:w(this,oe),error:i,errorDescription:a});if(c.error){const h=g.fromOAuthError(c.error,a);throw d.logger.debug(l({err:h})),d.logger.error(l({cerr:h,msg:"Error from redirect endpoint: "+c.error})),h}return await this.receiveTokens(c),c}async startAutoRefresh(t=["access","id"],o){return this.autoRefresher.startAutoRefresh(t,o)}stopAutoRefresh(){return this.autoRefresher.stopAutoRefresh()}async startDeviceCodePolling(t,o,s=5){return this.deviceCodePoller.startPolling(t,o,s)}stopDeviceCodePolling(){return this.deviceCodePoller.stopPolling()}getIdToken(){return w(this,D)}randomValue(t){const o=new Uint8Array(t);return self.crypto.getRandomValues(o),btoa(o.reduce((s,n)=>s+String.fromCharCode(n),"")).replace(/\//g,"_").replace(/\+/g,"-").replace(/=+$/,"")}async sha256(t){const s=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",s),i=Array.from(new Uint8Array(n));return btoa(i.reduce((a,c)=>a+String.fromCharCode(c),"")).replace(/\//g,"_").replace(/\+/g,"-").replace(/=+$/,"")}async api(t,o,s){let n={...this.resServerHeaders};o.startsWith("/")&&(o=o.substring(1));let i={};s&&(i.body=JSON.stringify(s));let a;this.accessTokenResponseType=="sessionStorage"?a=sessionStorage.getItem(this.accessTokenName):this.accessTokenResponseType=="localStorage"&&(a=localStorage.getItem(this.accessTokenName)),n.authorization="Bearer "+a;const c=await fetch(this.resServerBaseUrl+o,{headers:n,method:t,mode:this.resServerMode,credentials:this.resServerCredentials,...i});let h=null;return c.body&&(h=await c.json()),{status:c.status,body:h}}async getTokenExpiries(t,o){let s,n,i;return w(this,D)&&(s=w(this,D).exp?w(this,D).exp:null),w(this,F)&&(n=w(this,F).exp?w(this,F).exp:null),w(this,M)&&(i=w(this,M).exp?w(this,M).exp:null),{id:s,access:n,refresh:i}}async jsonFetchWithToken(t,o,s){if(s=="access"){if(!w(this,L))throw new g(_.InvalidToken,"Cannot make fetch with access token - no access token defined");o.headers||(o.headers={}),o.headers.authorization="Bearer "+w(this,L)}else{if(o.body||(o.body={}),!w(this,j))throw new g(_.InvalidToken,"Cannot make fetch with refresh token - no refresh token defined");o.body.refresh_token=w(this,j),o.body.grant_type="refresh_token"}return w(this,X)&&(o.body||(o.body={}),o.body.client_id=w(this,X),w(this,Q)&&(o.body.client_secret=w(this,Q))),typeof o.body!="string"&&(o.body=JSON.stringify(o.body)),await fetch(t,o)}async getCsrfToken(){}async receiveTokens(t){if(t.access_token){const o=this.getTokenPayload(t.access_token);o&&(A(this,L,t.access_token),A(this,F,o)),this.accessTokenResponseType=="localStorage"?localStorage.setItem(this.accessTokenName,t.access_token):this.accessTokenResponseType=="sessionStorage"&&sessionStorage.setItem(this.accessTokenName,t.access_token)}if(t.refresh_token){const o=this.getTokenPayload(t.refresh_token);o&&(A(this,j,t.refresh_token),A(this,M,o)),this.refreshTokenResponseType=="localStorage"?localStorage.setItem(this.refreshTokenName,t.refresh_token):this.accessTokenResponseType=="sessionStorage"&&sessionStorage.setItem(this.refreshTokenName,t.refresh_token)}if(t.id_token){const o=await this.validateIdToken(t.id_token);A(this,D,o),this.idTokenResponseType=="localStorage"?localStorage.setItem(this.idTokenName,t.id_token):this.idTokenResponseType=="sessionStorage"&&sessionStorage.setItem(this.idTokenName,t.id_token)}}async clientCredentialsFlow(t){const o=await super.clientCredentialsFlow(t);return await this.receiveTokens(o),o}async passwordFlow(t,o,s){const n=await super.passwordFlow(t,o,s);return await this.receiveTokens(n),n}async deviceCodeFlow(t){let o=this.authServerBaseUrl;return o.endsWith("/")||(o+="/"),o+=this.deviceAuthorizationUrl,await super.startDeviceCodeFlow(o,t)}async mfaOtpComplete(t,o){const s=await super.mfaOtpComplete(t,o);return await this.receiveTokens(s),s}async mfaOobComplete(t,o,s){const n=await super.mfaOobComplete(t,o,s);return await this.receiveTokens(n),n}async refreshTokenFlow(t){if(!t)if(w(this,j))t=w(this,j);else throw new g(_.InvalidToken,"Cannot refresh tokens: no refresh token present");const o=await super.refreshTokenFlow(t);return await this.receiveTokens(o),o}async authorizationCodeFlow(t,o=!1){const s=this.randomValue(this.stateLength);if(this.scope=t,o){const i=await this.codeChallengeAndVerifier();A(this,te,i.codeChallenge),A(this,oe,i.codeVerifier),A(this,Z,s)}const n=await super.startAuthorizationCodeFlow(s,{scope:t,codeChallenge:w(this,te),pkce:o});if(n.error||!n.url){const i=g.fromOAuthError(n.error??"Couldn't create URL for authorization code flow",n.error_description);throw d.logger.debug(l({err:i})),i}location.href=n.url}}return L=new WeakMap,j=new WeakMap,D=new WeakMap,F=new WeakMap,M=new WeakMap,X=new WeakMap,Q=new WeakMap,te=new WeakMap,oe=new WeakMap,Z=new WeakMap,y.CrossauthError=g,y.CrossauthLogger=d,y.OAuthAutoRefresher=ye,y.OAuthBffClient=br,y.OAuthClient=Rr,y.OAuthDeviceCodePoller=we,y.OAuthTokenConsumer=He,y.OAuthTokenProvider=Ar,y.j=l,Object.defineProperty(y,Symbol.toStringTag,{value:"Module"}),y}({});
package/dist/index.js CHANGED
@@ -4,10 +4,10 @@ var ue = (r) => {
4
4
  };
5
5
  var He = (r, e, t) => e in r ? xe(r, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : r[e] = t;
6
6
  var f = (r, e, t) => He(r, typeof e != "symbol" ? e + "" : e, t), fe = (r, e, t) => e.has(r) || ue("Cannot " + t);
7
- var p = (r, e, t) => (fe(r, e, "read from private field"), t ? t.call(r) : e.get(r)), R = (r, e, t) => e.has(r) ? ue("Cannot add the same private member more than once") : e instanceof WeakSet ? e.add(r) : e.set(r, t), T = (r, e, t, o) => (fe(r, e, "write to private field"), o ? o.call(r, t) : e.set(r, t), t);
8
- var je = Object.defineProperty, _e = (r) => {
7
+ var y = (r, e, t) => (fe(r, e, "read from private field"), t ? t.call(r) : e.get(r)), R = (r, e, t) => e.has(r) ? ue("Cannot add the same private member more than once") : e instanceof WeakSet ? e.add(r) : e.set(r, t), T = (r, e, t, o) => (fe(r, e, "write to private field"), o ? o.call(r, t) : e.set(r, t), t);
8
+ var De = Object.defineProperty, _e = (r) => {
9
9
  throw TypeError(r);
10
- }, De = (r, e, t) => e in r ? je(r, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : r[e] = t, u = (r, e, t) => De(r, typeof e != "symbol" ? e + "" : e, t), ke = (r, e, t) => e.has(r) || _e("Cannot " + t), w = (r, e, t) => (ke(r, e, "read from private field"), e.get(r)), ge = (r, e, t) => e.has(r) ? _e("Cannot add the same private member more than once") : e instanceof WeakSet ? e.add(r) : e.set(r, t), te = (r, e, t, o) => (ke(r, e, "write to private field"), e.set(r, t), t);
10
+ }, je = (r, e, t) => e in r ? De(r, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : r[e] = t, u = (r, e, t) => je(r, typeof e != "symbol" ? e + "" : e, t), ke = (r, e, t) => e.has(r) || _e("Cannot " + t), w = (r, e, t) => (ke(r, e, "read from private field"), e.get(r)), ge = (r, e, t) => e.has(r) ? _e("Cannot add the same private member more than once") : e instanceof WeakSet ? e.add(r) : e.set(r, t), te = (r, e, t, o) => (ke(r, e, "write to private field"), e.set(r, t), t);
11
11
  class K {
12
12
  }
13
13
  u(K, "active", "active"), /** Deactivated account. User cannot log in */
@@ -938,13 +938,13 @@ async function kr(r, e, t) {
938
938
  let c = !1;
939
939
  typeof e == "function" ? (e = await e(o, r), c = !0, we(a, e, "verify"), Y(e) && (e = await le(e, a))) : we(a, e, "verify");
940
940
  const h = Je(oe.encode(r.protected ?? ""), oe.encode("."), typeof r.payload == "string" ? oe.encode(r.payload) : r.payload);
941
- let y;
941
+ let p;
942
942
  try {
943
- y = z(r.signature);
943
+ p = z(r.signature);
944
944
  } catch {
945
945
  throw new C("Failed to base64url decode the signature");
946
946
  }
947
- if (!await _r(a, e, y, h))
947
+ if (!await _r(a, e, p, h))
948
948
  throw new Te();
949
949
  let _;
950
950
  if (i)
@@ -1148,10 +1148,10 @@ class Tr {
1148
1148
  verifierLength: a,
1149
1149
  tokenConsumer: c,
1150
1150
  authServerCredentials: h,
1151
- authServerMode: y,
1151
+ authServerMode: p,
1152
1152
  authServerHeaders: _
1153
1153
  }) {
1154
- u(this, "authServerBaseUrl", ""), ge(this, S), ge(this, A), u(this, "codeChallengeMethod", "S256"), u(this, "verifierLength", 32), u(this, "redirect_uri"), u(this, "stateLength", 32), u(this, "authzCode", ""), u(this, "oidcConfig"), u(this, "tokenConsumer"), u(this, "authServerHeaders", {}), u(this, "authServerMode"), u(this, "authServerCredentials"), u(this, "oauthPostType", "json"), u(this, "oauthLogFetch", !1), u(this, "oauthUseUserInfoEndpoint", !1), u(this, "oauthAuthorizeRedirect"), this.tokenConsumer = c, this.authServerBaseUrl = e, a && (this.verifierLength = a), i && (this.stateLength = i), t && te(this, S, t), o && te(this, A, o), s && (this.redirect_uri = s), n && (this.codeChallengeMethod = n), this.authServerBaseUrl = e, h && (this.authServerCredentials = h), y && (this.authServerMode = y), _ && (this.authServerHeaders = _);
1154
+ u(this, "authServerBaseUrl", ""), ge(this, S), ge(this, A), u(this, "codeChallengeMethod", "S256"), u(this, "verifierLength", 32), u(this, "redirect_uri"), u(this, "stateLength", 32), u(this, "authzCode", ""), u(this, "oidcConfig"), u(this, "tokenConsumer"), u(this, "authServerHeaders", {}), u(this, "authServerMode"), u(this, "authServerCredentials"), u(this, "oauthPostType", "json"), u(this, "oauthLogFetch", !1), u(this, "oauthUseUserInfoEndpoint", !1), u(this, "oauthAuthorizeRedirect"), this.tokenConsumer = c, this.authServerBaseUrl = e, a && (this.verifierLength = a), i && (this.stateLength = i), t && te(this, S, t), o && te(this, A, o), s && (this.redirect_uri = s), n && (this.codeChallengeMethod = n), this.authServerBaseUrl = e, h && (this.authServerCredentials = h), p && (this.authServerMode = p), _ && (this.authServerHeaders = _);
1155
1155
  }
1156
1156
  set client_id(e) {
1157
1157
  te(this, S, e);
@@ -1225,14 +1225,19 @@ class Tr {
1225
1225
  * - `error_description` friendly error message or undefined
1226
1226
  * if no error
1227
1227
  */
1228
- async startAuthorizationCodeFlow(e, t, o, s = !1) {
1229
- var n, i, a;
1230
- if (d.logger.debug(l({ msg: "Starting authorization code flow" })), this.oidcConfig || await this.loadConfig(), !((n = this.oidcConfig) != null && n.response_types_supported.includes("code")) || !((i = this.oidcConfig) != null && i.response_modes_supported.includes("query")))
1228
+ async startAuthorizationCodeFlow(e, {
1229
+ scope: t,
1230
+ codeChallenge: o,
1231
+ pkce: s = !1,
1232
+ upstream: n
1233
+ }) {
1234
+ var i, a, c;
1235
+ if (d.logger.debug(l({ msg: "Starting authorization code flow, scope " + t })), this.oidcConfig || await this.loadConfig(), !((i = this.oidcConfig) != null && i.response_types_supported.includes("code")) || !((a = this.oidcConfig) != null && a.response_modes_supported.includes("query")))
1231
1236
  return {
1232
1237
  error: "invalid_request",
1233
1238
  error_description: "Server does not support authorization code flow"
1234
1239
  };
1235
- if (!((a = this.oidcConfig) != null && a.authorization_endpoint))
1240
+ if (!((c = this.oidcConfig) != null && c.authorization_endpoint))
1236
1241
  return {
1237
1242
  error: "server_error",
1238
1243
  error_description: "Cannot get authorize endpoint"
@@ -1245,10 +1250,10 @@ class Tr {
1245
1250
  error: "invalid_request",
1246
1251
  error_description: "Cannot make authorization code flow without Redirect Uri"
1247
1252
  };
1248
- let c = this.oidcConfig.authorization_endpoint;
1249
- this.oauthAuthorizeRedirect && (c = this.oauthAuthorizeRedirect);
1250
- let h = c + "?response_type=code&client_id=" + encodeURIComponent(w(this, S)) + "&state=" + encodeURIComponent(e) + "&redirect_uri=" + encodeURIComponent(this.redirect_uri);
1251
- return t && (h += "&scope=" + encodeURIComponent(t)), s && o && (h += "&code_challenge=" + o), { url: h };
1253
+ let h = this.oidcConfig.authorization_endpoint;
1254
+ this.oauthAuthorizeRedirect && (h = this.oauthAuthorizeRedirect);
1255
+ let p = h + "?response_type=code&client_id=" + encodeURIComponent(w(this, S)) + "&state=" + encodeURIComponent(e) + "&redirect_uri=" + encodeURIComponent(this.redirect_uri);
1256
+ return t && (p += "&scope=" + encodeURIComponent(t)), s && o && (p += "&code_challenge=" + o), { url: p };
1252
1257
  }
1253
1258
  async codeChallengeAndVerifier() {
1254
1259
  const e = this.randomValue(this.verifierLength);
@@ -1302,7 +1307,13 @@ class Tr {
1302
1307
  * @returns The {@link OAuthTokenResponse} from the `token` endpoint
1303
1308
  * request, or `error` and `error_description`.
1304
1309
  */
1305
- async redirectEndpoint(e, t, o, s, n) {
1310
+ async redirectEndpoint({
1311
+ code: e,
1312
+ scope: t,
1313
+ codeVerifier: o,
1314
+ error: s,
1315
+ errorDescription: n
1316
+ }) {
1306
1317
  var i, a;
1307
1318
  if (this.oidcConfig || await this.loadConfig(), s || !e)
1308
1319
  return s || (s = "server_error"), n || (n = "Unknown error"), { error: s, error_description: n };
@@ -1317,15 +1328,15 @@ class Tr {
1317
1328
  error_description: "Cannot get token endpoint"
1318
1329
  };
1319
1330
  const c = this.oidcConfig.token_endpoint;
1320
- let h, y;
1321
- h = "authorization_code", y = w(this, A);
1331
+ let h, p;
1332
+ h = "authorization_code", p = w(this, A);
1322
1333
  let _ = {
1323
1334
  grant_type: h,
1324
1335
  client_id: w(this, S),
1325
1336
  code: this.authzCode,
1326
1337
  redirect_uri: this.redirect_uri
1327
1338
  };
1328
- t && (_.scope = t), y && (_.client_secret = y), o && (_.code_verifier = o);
1339
+ t && (_.scope = t), p && (_.client_secret = p), o && (_.code_verifier = o);
1329
1340
  try {
1330
1341
  let b = await this.post(c, _, this.authServerHeaders);
1331
1342
  if (b.id_token) {
@@ -1799,35 +1810,44 @@ class Tr {
1799
1810
  * @returns the parsed JSON response as an object.
1800
1811
  * @throws any exception raised by `fetch()`
1801
1812
  */
1802
- async post(e, t, o = {}) {
1813
+ async post(e, t, o = {}, s) {
1803
1814
  d.logger.debug(l({
1804
1815
  msg: "Fetch POST",
1805
1816
  url: e,
1806
1817
  params: Object.keys(t)
1807
1818
  }));
1808
- let s = {};
1809
- this.authServerCredentials && (s.credentials = this.authServerCredentials), this.authServerMode && (s.mode = this.authServerMode);
1810
- let n = "", i = "";
1819
+ let n = {};
1820
+ this.authServerCredentials && (n.credentials = this.authServerCredentials), this.authServerMode && (n.mode = this.authServerMode);
1821
+ let i = "", a = "";
1811
1822
  if (this.oauthPostType == "json")
1812
- n = JSON.stringify(t), i = "application/json";
1823
+ i = JSON.stringify(t), a = "application/json";
1813
1824
  else {
1814
- n = "";
1815
- for (let c in t)
1816
- n != "" && (n += "&"), n += encodeURIComponent(c) + "=" + encodeURIComponent(t[c]);
1817
- i = "application/x-www-form-urlencoded";
1818
- }
1819
- this.oauthLogFetch && d.logger.debug(l({ msg: "OAuth fetch", method: "POST", url: e, body: n }));
1820
- const a = await (await fetch(e, {
1825
+ i = "";
1826
+ for (let p in t)
1827
+ i != "" && (i += "&"), i += encodeURIComponent(p) + "=" + encodeURIComponent(t[p]);
1828
+ a = "application/x-www-form-urlencoded";
1829
+ }
1830
+ this.oauthLogFetch && d.logger.debug(l({ msg: "OAuth fetch", method: "POST", url: e, body: i }));
1831
+ let c = {};
1832
+ s && (c = s);
1833
+ const h = await fetch(e, {
1821
1834
  method: "POST",
1822
- ...s,
1835
+ ...n,
1823
1836
  headers: {
1824
1837
  Accept: "application/json",
1825
- "Content-Type": i,
1838
+ "Content-Type": a,
1826
1839
  ...o
1827
1840
  },
1828
- body: n
1829
- })).json();
1830
- return this.oauthLogFetch && d.logger.debug(l({ msg: "OAuth fetch response", body: JSON.stringify(a) })), a;
1841
+ ...c,
1842
+ body: i
1843
+ });
1844
+ try {
1845
+ const p = await h.clone().json();
1846
+ return this.oauthLogFetch && d.logger.debug(l({ msg: "OAuth fetch response", body: JSON.stringify(p) })), await h.json(), p;
1847
+ } catch (p) {
1848
+ let _ = g.asCrossauthError(p);
1849
+ throw i = await h.text(), d.logger.debug(l({ msg: "Response is not JSON", response: i })), _;
1850
+ }
1831
1851
  }
1832
1852
  /**
1833
1853
  * Makes a GET request to the given URL using `fetch()`.
@@ -2167,8 +2187,8 @@ class Ke {
2167
2187
  d.logger.debug(l({ msg: "Refresh token has expired" }));
2168
2188
  return;
2169
2189
  }
2170
- let y = (_) => new Promise((b) => setTimeout(b, _));
2171
- d.logger.debug(l({ msg: `Waiting ${h} before refreshing tokens` })), o = h, await y(h), await this.autoRefresh(e, n, t);
2190
+ let p = (_) => new Promise((b) => setTimeout(b, _));
2191
+ d.logger.debug(l({ msg: `Waiting ${h} before refreshing tokens` })), o = h, await p(h), await this.autoRefresh(e, n, t);
2172
2192
  }
2173
2193
  async autoRefresh(e, t, o) {
2174
2194
  if (this.autoRefreshActive) {
@@ -2210,14 +2230,14 @@ class Ke {
2210
2230
  try {
2211
2231
  await this.tokenProvider.receiveTokens(s);
2212
2232
  } catch (h) {
2213
- const y = g.asCrossauthError(h);
2214
- o ? o("Couldn't receive tokens", y) : (d.logger.debug(l({ err: h })), d.logger.error(l({ msg: "Error receiving tokens", cerr: y })));
2233
+ const p = g.asCrossauthError(h);
2234
+ o ? o("Couldn't receive tokens", p) : (d.logger.debug(l({ err: h })), d.logger.error(l({ msg: "Error receiving tokens", cerr: p })));
2215
2235
  }
2216
2236
  } else
2217
- i < se ? (d.logger.error(l({ msg: `Failed auto refreshing tokens. Retrying in ${de} seconds` })), await ((y) => new Promise((_) => setTimeout(_, y)))(de * 1e3)) : (d.logger.error(l({ msg: "Failed auto refreshing tokens. Number of retries exceeded" })), o && o("Failed auto refreshing tokens")), i++;
2237
+ i < se ? (d.logger.error(l({ msg: `Failed auto refreshing tokens. Retrying in ${de} seconds` })), await ((p) => new Promise((_) => setTimeout(_, p)))(de * 1e3)) : (d.logger.error(l({ msg: "Failed auto refreshing tokens. Number of retries exceeded" })), o && o("Failed auto refreshing tokens")), i++;
2218
2238
  } catch (a) {
2219
2239
  const c = g.asCrossauthError(a);
2220
- d.logger.debug(l({ err: c })), i < se ? (d.logger.error(l({ msg: `Failed auto refreshing tokens. Retrying in ${se} seconds` })), await ((y) => new Promise((_) => setTimeout(_, y)))(de * 1e3)) : (d.logger.error(l({ msg: "Failed auto refreshing tokens. Number of retries exceeded" })), o && o(c.message, c)), i++;
2240
+ d.logger.debug(l({ err: c })), i < se ? (d.logger.error(l({ msg: `Failed auto refreshing tokens. Retrying in ${se} seconds` })), await ((p) => new Promise((_) => setTimeout(_, p)))(de * 1e3)) : (d.logger.error(l({ msg: "Failed auto refreshing tokens. Number of retries exceeded" })), o && o(c.message, c)), i++;
2221
2241
  }
2222
2242
  }
2223
2243
  }
@@ -2287,7 +2307,7 @@ class We {
2287
2307
  this.pollingActive = !1, o("expired_token", "Timeout waiting for authorization");
2288
2308
  else if (i.error == "authorization_pending" || i.error == "slow_down") {
2289
2309
  i.error == "slow_down" && (t += 5);
2290
- let a = i.interval ?? t, c = (h) => new Promise((y) => setTimeout(y, h));
2310
+ let a = i.interval ?? t, c = (h) => new Promise((p) => setTimeout(p, h));
2291
2311
  d.logger.debug(l({ msg: "device code poll: waiting " + String(a) + " seconds" })), await c(a * 1e3), this.pollingActive && this.poll(e, t, o);
2292
2312
  } else i.error ? (this.pollingActive = !1, o("error", i.error_description ?? i.error)) : (this.pollingActive = !1, o("complete"));
2293
2313
  }
@@ -2581,7 +2601,7 @@ class br extends Er {
2581
2601
  return btoa(n.reduce((i, a) => i + String.fromCharCode(a), "")).replace(/\//g, "_").replace(/\+/g, "-").replace(/=+$/, "");
2582
2602
  }
2583
2603
  }
2584
- var j, W, N, D, J, B, q, Z, ee, V;
2604
+ var D, W, N, j, J, B, q, Z, ee, V;
2585
2605
  class Ir extends Tr {
2586
2606
  /**
2587
2607
  * Constructor
@@ -2641,10 +2661,10 @@ class Ir extends Tr {
2641
2661
  f(this, "accessTokenName", "CROSSAUTH_AT");
2642
2662
  f(this, "refreshTokenName", "CROSSAUTH_RT");
2643
2663
  f(this, "idTokenName", "CROSSAUTH_IT");
2644
- R(this, j);
2664
+ R(this, D);
2645
2665
  R(this, W);
2646
2666
  R(this, N);
2647
- R(this, D);
2667
+ R(this, j);
2648
2668
  R(this, J);
2649
2669
  R(this, B);
2650
2670
  R(this, q);
@@ -2668,7 +2688,7 @@ class Ir extends Tr {
2668
2688
  refresh_token: n
2669
2689
  }), s) {
2670
2690
  const i = this.getTokenPayload(s);
2671
- i && (T(this, j, s), T(this, D, i));
2691
+ i && (T(this, D, s), T(this, j, i));
2672
2692
  }
2673
2693
  if (n) {
2674
2694
  const i = this.getTokenPayload(n);
@@ -2680,7 +2700,7 @@ class Ir extends Tr {
2680
2700
  });
2681
2701
  }).catch((i) => {
2682
2702
  d.logger.debug(l({ err: i, msg: "Couldn't validate ID token" }));
2683
- }) : p(this, j) && t.autoRefresh && n ? this.startAutoRefresh(t.autoRefresh).then().catch((i) => {
2703
+ }) : y(this, D) && t.autoRefresh && n ? this.startAutoRefresh(t.autoRefresh).then().catch((i) => {
2684
2704
  d.logger.debug(l({ err: i, msg: "Couldn't start auto refresh" }));
2685
2705
  }) : n && !s && this.refreshTokenFlow(n).then((i) => {
2686
2706
  d.logger.debug(l({ msg: "Refreshed tokens" })), t.autoRefresh && this.startAutoRefresh(t.autoRefresh).then().catch((a) => {
@@ -2692,7 +2712,7 @@ class Ir extends Tr {
2692
2712
  });
2693
2713
  }
2694
2714
  get idTokenPayload() {
2695
- return p(this, N);
2715
+ return y(this, N);
2696
2716
  }
2697
2717
  /**
2698
2718
  * Processes the query parameters for a Redirect URI request if they
@@ -2721,19 +2741,25 @@ class Ir extends Tr {
2721
2741
  if (t.origin + t.pathname != this.redirect_uri) return;
2722
2742
  const o = new URLSearchParams(window.location.search);
2723
2743
  let s, n, i, a;
2724
- for (const [h, y] of o)
2725
- h == "code" && (s = y), h == "state" && (n = y), h == "error" && (i = y), h == "error_description" && (a = y);
2744
+ for (const [h, p] of o)
2745
+ h == "code" && (s = p), h == "state" && (n = p), h == "error" && (i = p), h == "error_description" && (a = p);
2726
2746
  if (!i && !s) return;
2727
2747
  if (i) {
2728
2748
  const h = g.fromOAuthError(i, a);
2729
2749
  throw d.logger.debug(l({ err: h })), d.logger.error(l({ cerr: h, msg: "Error from authorize endpoint: " + i })), h;
2730
2750
  }
2731
- if (p(this, V) && n != p(this, V))
2751
+ if (y(this, V) && n != y(this, V))
2732
2752
  return {
2733
2753
  error: "access_denied",
2734
2754
  error_description: "Invalid state"
2735
2755
  };
2736
- const c = await this.redirectEndpoint(s, this.scope, p(this, ee), i, a);
2756
+ const c = await this.redirectEndpoint({
2757
+ code: s,
2758
+ scope: this.scope,
2759
+ codeVerifier: y(this, ee),
2760
+ error: i,
2761
+ errorDescription: a
2762
+ });
2737
2763
  if (c.error) {
2738
2764
  const h = g.fromOAuthError(c.error, a);
2739
2765
  throw d.logger.debug(l({ err: h })), d.logger.error(l({ cerr: h, msg: "Error from redirect endpoint: " + c.error })), h;
@@ -2777,7 +2803,7 @@ class Ir extends Tr {
2777
2803
  * @returns the payload as an object
2778
2804
  */
2779
2805
  getIdToken() {
2780
- return p(this, N);
2806
+ return y(this, N);
2781
2807
  }
2782
2808
  ///////
2783
2809
  // Implementation of abstract methods
@@ -2838,7 +2864,7 @@ class Ir extends Tr {
2838
2864
  */
2839
2865
  async getTokenExpiries(t, o) {
2840
2866
  let s, n, i;
2841
- return p(this, N) && (s = p(this, N).exp ? p(this, N).exp : null), p(this, D) && (n = p(this, D).exp ? p(this, D).exp : null), p(this, J) && (i = p(this, J).exp ? p(this, J).exp : null), {
2867
+ return y(this, N) && (s = y(this, N).exp ? y(this, N).exp : null), y(this, j) && (n = y(this, j).exp ? y(this, j).exp : null), y(this, J) && (i = y(this, J).exp ? y(this, J).exp : null), {
2842
2868
  id: s,
2843
2869
  access: n,
2844
2870
  refresh: i
@@ -2856,15 +2882,15 @@ class Ir extends Tr {
2856
2882
  */
2857
2883
  async jsonFetchWithToken(t, o, s) {
2858
2884
  if (s == "access") {
2859
- if (!p(this, j))
2885
+ if (!y(this, D))
2860
2886
  throw new g(m.InvalidToken, "Cannot make fetch with access token - no access token defined");
2861
- o.headers || (o.headers = {}), o.headers.authorization = "Bearer " + p(this, j);
2887
+ o.headers || (o.headers = {}), o.headers.authorization = "Bearer " + y(this, D);
2862
2888
  } else {
2863
- if (o.body || (o.body = {}), !p(this, W))
2889
+ if (o.body || (o.body = {}), !y(this, W))
2864
2890
  throw new g(m.InvalidToken, "Cannot make fetch with refresh token - no refresh token defined");
2865
- o.body.refresh_token = p(this, W), o.body.grant_type = "refresh_token";
2891
+ o.body.refresh_token = y(this, W), o.body.grant_type = "refresh_token";
2866
2892
  }
2867
- return p(this, B) && (o.body || (o.body = {}), o.body.client_id = p(this, B), p(this, q) && (o.body.client_secret = p(this, q))), typeof o.body != "string" && (o.body = JSON.stringify(o.body)), await fetch(t, o);
2893
+ return y(this, B) && (o.body || (o.body = {}), o.body.client_id = y(this, B), y(this, q) && (o.body.client_secret = y(this, q))), typeof o.body != "string" && (o.body = JSON.stringify(o.body)), await fetch(t, o);
2868
2894
  }
2869
2895
  /**
2870
2896
  * Does nothing as CSRF tokens are not needed for this class
@@ -2875,7 +2901,7 @@ class Ir extends Tr {
2875
2901
  async receiveTokens(t) {
2876
2902
  if (t.access_token) {
2877
2903
  const o = this.getTokenPayload(t.access_token);
2878
- o && (T(this, j, t.access_token), T(this, D, o)), this.accessTokenResponseType == "localStorage" ? localStorage.setItem(this.accessTokenName, t.access_token) : this.accessTokenResponseType == "sessionStorage" && sessionStorage.setItem(this.accessTokenName, t.access_token);
2904
+ o && (T(this, D, t.access_token), T(this, j, o)), this.accessTokenResponseType == "localStorage" ? localStorage.setItem(this.accessTokenName, t.access_token) : this.accessTokenResponseType == "sessionStorage" && sessionStorage.setItem(this.accessTokenName, t.access_token);
2879
2905
  }
2880
2906
  if (t.refresh_token) {
2881
2907
  const o = this.getTokenPayload(t.refresh_token);
@@ -2945,8 +2971,8 @@ class Ir extends Tr {
2945
2971
  */
2946
2972
  async refreshTokenFlow(t) {
2947
2973
  if (!t)
2948
- if (p(this, W))
2949
- t = p(this, W);
2974
+ if (y(this, W))
2975
+ t = y(this, W);
2950
2976
  else
2951
2977
  throw new g(m.InvalidToken, "Cannot refresh tokens: no refresh token present");
2952
2978
  const o = await super.refreshTokenFlow(t);
@@ -2963,7 +2989,7 @@ class Ir extends Tr {
2963
2989
  const i = await this.codeChallengeAndVerifier();
2964
2990
  T(this, Z, i.codeChallenge), T(this, ee, i.codeVerifier), T(this, V, s);
2965
2991
  }
2966
- const n = await super.startAuthorizationCodeFlow(s, t, p(this, Z), o);
2992
+ const n = await super.startAuthorizationCodeFlow(s, { scope: t, codeChallenge: y(this, Z), pkce: o });
2967
2993
  if (n.error || !n.url) {
2968
2994
  const i = g.fromOAuthError(
2969
2995
  n.error ?? "Couldn't create URL for authorization code flow",
@@ -2974,7 +3000,7 @@ class Ir extends Tr {
2974
3000
  location.href = n.url;
2975
3001
  }
2976
3002
  }
2977
- j = new WeakMap(), W = new WeakMap(), N = new WeakMap(), D = new WeakMap(), J = new WeakMap(), B = new WeakMap(), q = new WeakMap(), Z = new WeakMap(), ee = new WeakMap(), V = new WeakMap();
3003
+ D = new WeakMap(), W = new WeakMap(), N = new WeakMap(), j = new WeakMap(), J = new WeakMap(), B = new WeakMap(), q = new WeakMap(), Z = new WeakMap(), ee = new WeakMap(), V = new WeakMap();
2978
3004
  export {
2979
3005
  g as CrossauthError,
2980
3006
  d as CrossauthLogger,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@crossauth/frontend",
3
3
  "private": false,
4
- "version": "1.1.2",
4
+ "version": "1.1.4",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
7
7
  "main": "./dist/index.cjs",
@@ -22,7 +22,7 @@
22
22
  },
23
23
  "dependencies": {
24
24
  "@esbuild-plugins/node-modules-polyfill": "^0.2.2",
25
- "@crossauth/common": "^1.1.2"
25
+ "@crossauth/common": "^1.1.4"
26
26
  },
27
27
  "scripts": {
28
28
  "dev": "vite",