@crossauth/frontend 1.0.1 → 1.1.1

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/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  Crossauth common
2
2
  ================
3
3
 
4
- Copyright (c) 2024 Matthew Baker
4
+ Copyright (c) 2026 Matthew Baker
5
5
 
6
6
  Crossauth is a cross platform package for authentication.
7
7
  It has a Typescript version and soon also a Python and
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var Ue=Object.defineProperty;var he=r=>{throw TypeError(r)};var Ne=(r,e,t)=>e in r?Ue(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var f=(r,e,t)=>Ne(r,typeof e!="symbol"?e+"":e,t),le=(r,e,t)=>e.has(r)||he("Cannot "+t);var p=(r,e,t)=>(le(r,e,"read from private field"),t?t.call(r):e.get(r)),E=(r,e,t)=>e.has(r)?he("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),T=(r,e,t,o)=>(le(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,me=r=>{throw TypeError(r)},He=(r,e,t)=>e in r?je(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,u=(r,e,t)=>He(r,typeof e!="symbol"?e+"":e,t),ve=(r,e,t)=>e.has(r)||me("Cannot "+t),w=(r,e,t)=>(ve(r,e,"read from private field"),e.get(r)),ue=(r,e,t)=>e.has(r)?me("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),Y=(r,e,t,o)=>(ve(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,"awaitingEmailVerification","awaitingemailverification"),u(j,"passwordChangeNeeded","passwordchangeneeded"),u(j,"passwordResetNeeded","passwordresetneeded"),u(j,"factor2ResetNeeded","factor2resetneeded"),u(j,"passwordAndFactor2ResetNeeded","passwordandfactor2resetneeded");class R{}u(R,"session","s:"),u(R,"passwordResetToken","p:"),u(R,"emailVerificationToken","e:"),u(R,"apiKey","api:"),u(R,"authorizationCode","authz:"),u(R,"accessToken","access:"),u(R,"refreshToken","refresh:"),u(R,"mfaToken","omfa:"),u(R,"deviceCode","dc:"),u(R,"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,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=m[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??m[i];return"errorMessage"in e?n=e.errorMessage:"message"in e&&(n=e.message),new g(i,n)}let o=t??m[48];return"message"in e&&(o=e.message),new g(48,o)}}const W=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(W,"None",0),u(W,"Error",1),u(W,"Warn",2),u(W,"Info",3),u(W,"Debug",4),u(W,"levelName",["NONE","ERROR","WARN","INFO","DEBUG"]);let d=W;function h(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 ke={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},te=crypto,Ce=r=>r instanceof CryptoKey,X=new TextEncoder,G=new TextDecoder;function xe(...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 Ke=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},F=r=>{let e=r;e instanceof Uint8Array&&(e=G.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return Ke(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class oe extends Error{static get code(){return"ERR_JOSE_GENERIC"}constructor(e){var t;super(e),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(t=Error.captureStackTrace)==null||t.call(Error,this,this.constructor)}}class O extends oe{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}}class S extends oe{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}}class D extends oe{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}static get code(){return"ERR_JWT_INVALID"}}class ze extends oe{constructor(){super(...arguments),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED",this.message="signature verification failed"}static get code(){return"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 Z(r,e){return r.name===e}function ie(r){return parseInt(r.name.slice(4),10)}function De(r){switch(r){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function We(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 Fe(r,e,...t){switch(e){case"HS256":case"HS384":case"HS512":{if(!Z(r.algorithm,"HMAC"))throw U("HMAC");const o=parseInt(e.slice(2),10);if(ie(r.algorithm.hash)!==o)throw U(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!Z(r.algorithm,"RSASSA-PKCS1-v1_5"))throw U("RSASSA-PKCS1-v1_5");const o=parseInt(e.slice(2),10);if(ie(r.algorithm.hash)!==o)throw U(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!Z(r.algorithm,"RSA-PSS"))throw U("RSA-PSS");const o=parseInt(e.slice(2),10);if(ie(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"ES256":case"ES384":case"ES512":{if(!Z(r.algorithm,"ECDSA"))throw U("ECDSA");const o=De(e);if(r.algorithm.namedCurve!==o)throw U(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}We(r,t)}function _e(r,e,...t){var o;if(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 fe=(r,...e)=>_e("Key must be ",r,...e);function Se(r,e,...t){return _e(`Key for the ${r} algorithm must be `,e,...t)}const Te=r=>Ce(r)?!0:(r==null?void 0:r[Symbol.toStringTag])==="KeyObject",re=["CryptoKey"],Je=(...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 Me(r){return typeof r=="object"&&r!==null}function $(r){if(!Me(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 Be=(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 Le(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"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 be=async r=>{if(!r.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:e,keyUsages:t}=Le(r),o=[e,r.ext??!1,r.key_ops??t],i={...r};return delete i.alg,delete i.use,te.subtle.importKey("jwk",i,...o)},Ae=r=>F(r);let se,ne;const Ee=r=>(r==null?void 0:r[Symbol.toStringTag])==="KeyObject",Pe=async(r,e,t,o)=>{let i=r.get(e);if(i!=null&&i[o])return i[o];const n=await be({...t,alg:o});return i?i[o]=n:r.set(e,{[o]:n}),n},$e=(r,e)=>{if(Ee(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?Ae(t.k):(ne||(ne=new WeakMap),Pe(ne,r,t,e))}return r},qe=(r,e)=>{if(Ee(r)){let t=r.export({format:"jwk"});return t.k?Ae(t.k):(se||(se=new WeakMap),Pe(se,r,t,e))}return r},Ve={normalizePublicKey:$e,normalizePrivateKey:qe},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 i=r.subarray(o,o+e.length);return i.length!==e.length?!1:i.every((n,s)=>n===e[s])||H(r,e,o+1)},ge=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 O("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},Re=async(r,e,t,o,i)=>{let n,s;const a=new Uint8Array(atob(t.replace(r,"")).split("").map(l=>l.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 l=ge(a);n=l.startsWith("P-")?{name:"ECDH",namedCurve:l}:{name:l},s=c?[]:["deriveBits"];break}case"EdDSA":n={name:ge(a)},s=c?["verify"]:["sign"];break;default:throw new O('Invalid or unsupported "alg" (Algorithm) value')}return te.subtle.importKey(e,a,n,!1,s)},Ge=(r,e,t)=>Re(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",r,e),Ye=(r,e,t)=>Re(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",r,e);async function Xe(r,e,t){if(typeof r!="string"||r.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return Ye(r,e)}async function Ze(r,e,t){if(typeof r!="string"||r.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return Ge(r,e)}async function pe(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 F(r.k);case"RSA":if(r.oth!==void 0)throw new O('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return be({...r,alg:e});default:throw new O('Unsupported "kty" (Key Type) Parameter value')}}const ee=r=>r==null?void 0:r[Symbol.toStringTag],Qe=(r,e)=>{if(!(e instanceof Uint8Array)){if(!Te(e))throw new TypeError(Se(r,e,...re,"Uint8Array"));if(e.type!=="secret")throw new TypeError(`${ee(e)} instances for symmetric algorithms must be of type "secret"`)}},er=(r,e,t)=>{if(!Te(e))throw new TypeError(Se(r,e,...re));if(e.type==="secret")throw new TypeError(`${ee(e)} instances for asymmetric algorithms must not be of type "secret"`);if(e.algorithm&&t==="verify"&&e.type==="private")throw new TypeError(`${ee(e)} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&t==="encrypt"&&e.type==="private")throw new TypeError(`${ee(e)} instances for asymmetric algorithm encryption must be of type "public"`)},rr=(r,e,t)=>{r.startsWith("HS")||r==="dir"||r.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(r)?Qe(r,e):er(r,e,t)};function tr(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 or(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"EdDSA":return{name:e.name};default:throw new O(`alg ${r} is not supported either by JOSE or your javascript runtime`)}}async function ir(r,e,t){if(e=await Ve.normalizePublicKey(e,r),Ce(e))return Fe(e,r,t),e;if(e instanceof Uint8Array){if(!r.startsWith("HS"))throw new TypeError(fe(e,...re));return te.subtle.importKey("raw",e,{hash:`SHA-${r.slice(-3)}`,name:"HMAC"},!1,[t])}throw new TypeError(fe(e,...re,"Uint8Array"))}const sr=async(r,e,t,o)=>{const i=await ir(r,e,"verify");Be(r,i);const n=or(r,i.algorithm);try{return await te.subtle.verify(n,i,t,o)}catch{return!1}};async function nr(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 L=F(r.protected);o=JSON.parse(G.decode(L))}catch{throw new S("JWS Protected Header is invalid")}if(!Je(o,r.header))throw new S("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const i={...o,...r.header},n=tr(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),rr(a,e,"verify");const l=xe(X.encode(r.protected??""),X.encode("."),typeof r.payload=="string"?X.encode(r.payload):r.payload);let y;try{y=F(r.signature)}catch{throw new S("Failed to base64url decode the signature")}if(!await sr(a,e,y,l))throw new ze;let k;if(s)try{k=F(r.payload)}catch{throw new S("Failed to base64url decode the payload")}else typeof r.payload=="string"?k=X.encode(r.payload):k=r.payload;const b={payload:k};return r.protected!==void 0&&(b.protectedHeader=o),r.header!==void 0&&(b.unprotectedHeader=r.header),c?{...b,key:e}:b}async function ar(r,e,t){if(r instanceof Uint8Array&&(r=G.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 nr({payload:i,protected:o,signature:n},e),c={payload:a.payload,protectedHeader:a.protectedHeader};return typeof e=="function"?{...c,key:a.key}:c}const Ie=F;function ye(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(G.decode(Ie(e)));if(!$(t))throw new Error;return t}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}function cr(r){if(typeof r!="string")throw new D("JWTs must use Compact JWS serialization, JWT must be a string");const{1:e,length:t}=r.split(".");if(t===5)throw new D("Only JWTs using Compact JWS serialization can be decoded");if(t!==3)throw new D("Invalid JWT");if(!e)throw new D("JWTs must contain a payload");let o;try{o=Ie(e)}catch{throw new D("Failed to base64url decode the payload")}let i;try{i=JSON.parse(G.decode(o))}catch{throw new D("Failed to parse the decoded payload as JSON")}if(!$(i))throw new D("Invalid JWT Claims Set");return i}const C=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(C,"All","all"),u(C,"AuthorizationCode","authorizationCode"),u(C,"AuthorizationCodeWithPKCE","authorizationCodeWithPKCE"),u(C,"ClientCredentials","clientCredentials"),u(C,"RefreshToken","refreshToken"),u(C,"DeviceCode","deviceCode"),u(C,"Password","password"),u(C,"PasswordMfa","passwordMfa"),u(C,"OidcAuthorizationCode","oidcAuthorizationCode"),u(C,"flowName",{[C.AuthorizationCode]:"Authorization Code",[C.AuthorizationCodeWithPKCE]:"Authorization Code with PKCE",[C.ClientCredentials]:"Client Credentials",[C.RefreshToken]:"Refresh Token",[C.DeviceCode]:"Device Code",[C.Password]:"Password",[C.PasswordMfa]:"Password MFA",[C.OidcAuthorizationCode]:"OIDC Authorization Code"});var _,A;class dr{constructor({authServerBaseUrl:e,client_id:t,client_secret:o,redirect_uri:i,codeChallengeMethod:n,stateLength:s,verifierLength:a,tokenConsumer:c,authServerCredentials:l,authServerMode:y,authServerHeaders:k}){u(this,"authServerBaseUrl",""),ue(this,_),ue(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),s&&(this.stateLength=s),t&&Y(this,_,t),o&&Y(this,A,o),i&&(this.redirect_uri=i),n&&(this.codeChallengeMethod=n),this.authServerBaseUrl=e,l&&(this.authServerCredentials=l),y&&(this.authServerMode=y),k&&(this.authServerHeaders=k)}set client_id(e){Y(this,_,e)}set client_secret(e){Y(this,A,e)}async loadConfig(e){if(e){d.logger.debug(h({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(h({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(h({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={...ke};try{const o=await t.json();for(const[i,n]of Object.entries(o))this.oidcConfig[i]=n}catch{throw new g(m.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(h({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(!w(this,_))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 l=c+"?response_type=code&client_id="+encodeURIComponent(w(this,_))+"&state="+encodeURIComponent(e)+"&redirect_uri="+encodeURIComponent(this.redirect_uri);return t&&(l+="&scope="+encodeURIComponent(t)),i&&o&&(l+="&code_challenge="+o),{url:l}}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(h({err:s})),d.logger.error(h({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(h({err:s})),d.logger.error(h({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 l,y;l="authorization_code",y=w(this,A);let k={grant_type:l,client_id:w(this,_),code:this.authzCode,redirect_uri:this.redirect_uri};t&&(k.scope=t),y&&(k.client_secret=y),o&&(k.code_verifier=o);try{let b=await this.post(c,k,this.authServerHeaders);if(b.id_token){const L=await this.getIdPayload(b.id_token,b.access_token);if(L.error)return L;b.id_payload=L.payload}return b}catch(b){return d.logger.error(h({err:b})),{error:"server_error",error_description:"Unable to get access token from server"}}}async clientCredentialsFlow(e){var t,o;if(d.logger.debug(h({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,_))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:w(this,_),client_secret:w(this,A)};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(h({err:s})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async passwordFlow(e,t,o){var i,n;if(d.logger.debug(h({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:w(this,_),client_secret:w(this,A),username:e,password:t};o&&(a.scope=o);try{let c=await this.post(s,a,this.authServerHeaders);if(c.id_token){const l=await this.getIdPayload(c.id_token,c.access_token);if(l.error)return l;c.id_payload=l.payload}return c}catch(c){return d.logger.error(h({err:c})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async mfaAuthenticators(e){var t,o,i;if(d.logger.debug(h({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 l=s[c];if(!l.id||!l.authenticator_type||!l.active)return{error:"server_error",error_description:"Invalid mfa/authenticators response"};a.push({id:l.id,authenticator_type:l.authenticator_type,active:l.active,name:l.name,oob_channel:l.oob_channel})}return{authenticators:a}}async mfaOtpRequest(e,t){var o,i;if(d.logger.debug(h({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:w(this,_),client_secret:w(this,A),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(h({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:w(this,_),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,i;if(d.logger.debug(h({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:w(this,_),client_secret:w(this,A),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(h({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:w(this,_),client_secret:w(this,A),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 l=await this.getIdPayload(c.id_token,c.access_token);if(l.error)return l;c.id_payload=l.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(h({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=w(this,A);let s={grant_type:"refresh_token",refresh_token:e,client_id:w(this,_)};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(h({err:a})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async startDeviceCodeFlow(e,t){var o;if(d.logger.debug(h({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:w(this,_),client_secret:w(this,A)};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(h({err:n})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async pollDeviceCodeFlow(e){var t,o,i;if(d.logger.debug(h({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,_),client_secret:w(this,A),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(h({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(h({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(h({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(h({msg:"OAuth fetch response",body:JSON.stringify(a)})),a}async get(e,t={}){d.logger.debug(h({msg:"Fetch GET",url:e}));let o={};this.authServerCredentials&&(o.credentials=this.authServerCredentials),this.authServerMode&&(o.mode=this.authServerMode),this.oauthLogFetch&&d.logger.debug(h({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(h({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(h({err:o}));return}}getTokenPayload(e){return cr(e)}}_=new WeakMap,A=new WeakMap;class hr{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 Ze(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 Xe(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(h({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(h({err:o}))}if(!t||!t.ok)throw new g(m.Connection,"Couldn't get OIDC configuration");this.oidcConfig={...ke};try{const o=await t.json();for(const[i,n]of Object.entries(o))this.oidcConfig[i]=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 i=e.keys[o];this.keys[i.kid??"_default"]=await pe(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(i){d.logger.error(h({err:i}))}if(!o||!o.ok)throw new g(m.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(m.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(h({msg:"Skipping key with "+a.kty}));continue}const c=await pe(a);this.keys[s]=c}catch(s){throw d.logger.error(h({err:s})),new g(m.Connection,"Couldn't load keys")}}catch(i){throw d.logger.error(h({err:i})),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=ye(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(h({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(h({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=ye(e).kid}catch{d.logger.warn(h({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(h({msg:"No matching keys found for access token"}));return}try{const{payload:i}=await ar(e,o),n=JSON.parse(new TextDecoder().decode(i));if(n.exp*1e3<Date.now()+this.clockTolerance){d.logger.warn(h({msg:"Access token has expired"}));return}return n}catch(i){const n=g.asCrossauthError(i);d.logger.debug(h({err:n})),d.logger.warn(h({msg:"Access token did not validate",cerr:n}));return}}}const we=30,Q=2,ae=30;class ce{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(h({msg:"Starting auto refresh"}));try{await this.scheduleAutoRefresh(e,t)}catch(o){const i=g.asCrossauthError(o);d.logger.error(h({cerr:i})),d.logger.debug(h({err:i}))}}}stopAutoRefresh(){this.autoRefreshActive=!1,d.logger.debug(h({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(h({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(h({msg:"No tokens expire"}));return}let l=c*1e3-a-we;if(l<0&&o!=null&&o<=0){d.logger.debug(h({msg:"Expiry time has passed"}));return}if(l<0&&(l=0),s.refresh&&s.refresh-we<l){d.logger.debug(h({msg:"Refresh token has expired"}));return}let y=k=>new Promise(b=>setTimeout(b,k));d.logger.debug(h({msg:`Waiting ${l} before refreshing tokens`})),o=l,await y(l),await this.autoRefresh(e,n,t)}async autoRefresh(e,t,o){if(this.autoRefreshActive){let i,n=!1,s=0;for(;!n&&s<=Q;)try{let a={...this.headers};t&&(a[this.csrfHeader]=t),d.logger.debug(h({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(h({msg:"Failed auto refreshing tokens",status:c.status}));try{i=await c.json()}catch{try{d.logger.error(h({msg:"/refresh returned a non-JSON response "+(i?await i.text():void 0)}))}catch{d.logger.error(h({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(l){const y=g.asCrossauthError(l);o?o("Couldn't receive tokens",y):(d.logger.debug(h({err:l})),d.logger.error(h({msg:"Error receiving tokens",cerr:y})))}}else s<Q?(d.logger.error(h({msg:`Failed auto refreshing tokens. Retrying in ${ae} seconds`})),await(y=>new Promise(k=>setTimeout(k,y)))(ae*1e3)):(d.logger.error(h({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(h({err:c})),s<Q?(d.logger.error(h({msg:`Failed auto refreshing tokens. Retrying in ${Q} seconds`})),await(y=>new Promise(k=>setTimeout(k,y)))(ae*1e3)):(d.logger.error(h({msg:"Failed auto refreshing tokens. Number of retries exceeded"})),o&&o(c.message,c)),s++}}}}class de{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(h({msg:"Starting auto refresh"})),await this.poll(e,o,t))}stopPolling(){this.pollingActive=!1,d.logger.debug(h({msg:"Stopping auto refresh"}))}async poll(e,t,o){var i;if(!e)d.logger.debug(h({msg:"device code poll: no device code provided"})),o("error","Error waiting for authorization");else try{if(d.logger.debug(h({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(h({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=l=>new Promise(y=>setTimeout(y,l));d.logger.debug(h({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(h({err:s})),d.logger.error(h({msg:"Polling failed",cerr:s})),o("error",s.message)}}}class lr{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 ce({...e,autoRefreshUrl:this.autoRefreshUrl,tokenProvider:this}),this.deviceCodePoller=new de({...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,l;return i&&(a=i.exp?i.exp:null),n&&(c=n.exp?n.exp:null),s&&(l=s.exp?s.exp:null),{id:a,access:c,refresh:l}}catch{return d.logger.error(h({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 ur{getCsrfToken(){return new Promise(e=>{})}}class Oe extends hr{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(/=+$/,"")}}var x,N,I,K,z,J,M,q,V,B;class fr extends dr{constructor(t){t.tokenConsumer||(t.tokenConsumer=new Oe(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");E(this,x);E(this,N);E(this,I);E(this,K);E(this,z);E(this,J);E(this,M);f(this,"autoRefresher");f(this,"deviceCodePoller");f(this,"deviceAuthorizationUrl","device_authorization");E(this,q);E(this,V);E(this,B);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,J,t.client_id),t.client_secret&&T(this,M,t.client_secret),t.deviceAuthorizationUrl&&(this.deviceAuthorizationUrl=t.deviceAuthorizationUrl),this.autoRefresher=new ce({...t,autoRefreshUrl:this.authServerBaseUrl+"/token",tokenProvider:this}),this.deviceCodePoller=new de({...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&&(T(this,x,i),T(this,K,s))}if(n){const s=this.getTokenPayload(n);s&&(T(this,N,n),T(this,z,s))}o?this.validateIdToken(o).then(s=>{T(this,I,s),t.autoRefresh&&this.startAutoRefresh(t.autoRefresh).then().catch(a=>{d.logger.debug(h({err:a,msg:"Couldn't start auto refresh"}))})}).catch(s=>{d.logger.debug(h({err:s,msg:"Couldn't validate ID token"}))}):p(this,x)&&t.autoRefresh&&n?this.startAutoRefresh(t.autoRefresh).then().catch(s=>{d.logger.debug(h({err:s,msg:"Couldn't start auto refresh"}))}):n&&!i&&this.refreshTokenFlow(n).then(s=>{d.logger.debug(h({msg:"Refreshed tokens"})),t.autoRefresh&&this.startAutoRefresh(t.autoRefresh).then().catch(a=>{d.logger.debug(h({err:a,msg:"Couldn't start auto refresh"}))})}).catch(s=>{const a=g.asCrossauthError(s);d.logger.debug(h({err:a})),d.logger.error(h({msg:"failed refreshing tokens",cerr:a}))})}get idTokenPayload(){return p(this,I)}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[l,y]of o)l=="code"&&(i=y),l=="state"&&(n=y),l=="error"&&(s=y),l=="error_description"&&(a=y);if(!s&&!i)return;if(s){const l=g.fromOAuthError(s,a);throw d.logger.debug(h({err:l})),d.logger.error(h({cerr:l,msg:"Error from authorize endpoint: "+s})),l}if(p(this,B)&&n!=p(this,B))return{error:"access_denied",error_description:"Invalid state"};const c=await this.redirectEndpoint(i,this.scope,p(this,V),s,a);if(c.error){const l=g.fromOAuthError(c.error,a);throw d.logger.debug(h({err:l})),d.logger.error(h({cerr:l,msg:"Error from redirect endpoint: "+c.error})),l}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 p(this,I)}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 l=null;return c.body&&(l=await c.json()),{status:c.status,body:l}}async getTokenExpiries(t,o){let i,n,s;return p(this,I)&&(i=p(this,I).exp?p(this,I).exp:null),p(this,K)&&(n=p(this,K).exp?p(this,K).exp:null),p(this,z)&&(s=p(this,z).exp?p(this,z).exp:null),{id:i,access:n,refresh:s}}async jsonFetchWithToken(t,o,i){if(i=="access"){if(!p(this,x))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,x)}else{if(o.body||(o.body={}),!p(this,N))throw new g(m.InvalidToken,"Cannot make fetch with refresh token - no refresh token defined");o.body.refresh_token=p(this,N),o.body.grant_type="refresh_token"}return p(this,J)&&(o.body||(o.body={}),o.body.client_id=p(this,J),p(this,M)&&(o.body.client_secret=p(this,M))),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,x,t.access_token),T(this,K,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,N,t.refresh_token),T(this,z,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,I,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(p(this,N))t=p(this,N);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 i=this.randomValue(this.stateLength);if(this.scope=t,o){const s=await this.codeChallengeAndVerifier();T(this,q,s.codeChallenge),T(this,V,s.codeVerifier),T(this,B,i)}const n=await super.startAuthorizationCodeFlow(i,t,p(this,q),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(h({err:s})),s}location.href=n.url}}x=new WeakMap,N=new WeakMap,I=new WeakMap,K=new WeakMap,z=new WeakMap,J=new WeakMap,M=new WeakMap,q=new WeakMap,V=new WeakMap,B=new WeakMap;exports.CrossauthError=g;exports.CrossauthLogger=d;exports.OAuthAutoRefresher=ce;exports.OAuthBffClient=lr;exports.OAuthClient=fr;exports.OAuthDeviceCodePoller=de;exports.OAuthTokenConsumer=Oe;exports.OAuthTokenProvider=ur;exports.j=h;
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;