@crossauth/frontend 0.0.40 → 0.0.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.iife.js +1 -1
- package/dist/index.js +6 -1
- package/package.json +2 -2
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{d.logger.error(h({msg:"/refresh returned a non-JSON response "+(i?await i.text():void 0)})),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 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;
|
package/dist/index.iife.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var crossauth_frontend=function(p){"use strict";var fr=Object.defineProperty;var Ne=p=>{throw TypeError(p)};var gr=(p,v,_)=>v in p?fr(p,v,{enumerable:!0,configurable:!0,writable:!0,value:_}):p[v]=_;var f=(p,v,_)=>gr(p,typeof v!="symbol"?v+"":v,_),je=(p,v,_)=>v.has(p)||Ne("Cannot "+_);var y=(p,v,_)=>(je(p,v,"read from private field"),_?_.call(p):v.get(p)),I=(p,v,_)=>v.has(p)?Ne("Cannot add the same private member more than once"):v instanceof WeakSet?v.add(p):v.set(p,_),E=(p,v,_,Q)=>(je(p,v,"write to private field"),Q?Q.call(p,_):v.set(p,_),_);var D,K,j,W,F,L,$,Y,X,q;var v=Object.defineProperty,_=r=>{throw TypeError(r)},Q=(r,e,t)=>e in r?v(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,u=(r,e,t)=>Q(r,typeof e!="symbol"?e+"":e,t),ge=(r,e,t)=>e.has(r)||_("Cannot "+t),m=(r,e,t)=>(ge(r,e,"read from private field"),e.get(r)),pe=(r,e,t)=>e.has(r)?_("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),ee=(r,e,t,o)=>(ge(r,e,"write to private field"),e.set(r,t),t);class z{}u(z,"active","active"),u(z,"disabled","disabled"),u(z,"awaitingTwoFactorSetup","awaitingtwofactorsetup"),u(z,"awaitingEmailVerification","awaitingemailverification"),u(z,"passwordChangeNeeded","passwordchangeneeded"),u(z,"passwordResetNeeded","passwordresetneeded"),u(z,"factor2ResetNeeded","factor2resetneeded"),u(z,"passwordAndFactor2ResetNeeded","passwordandfactor2resetneeded");class U{}u(U,"session","s:"),u(U,"passwordResetToken","p:"),u(U,"emailVerificationToken","e:"),u(U,"apiKey","api:"),u(U,"authorizationCode","authz:"),u(U,"accessToken","access:"),u(U,"refreshToken","refresh:"),u(U,"mfaToken","omfa:"),u(U,"deviceCode","dc:"),u(U,"userCode","uc:");var k=(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))(k||{});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=k[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??k[i];return"errorMessage"in e?n=e.errorMessage:"message"in e&&(n=e.message),new g(i,n)}let o=t??k[48];return"message"in e&&(o=e.message),new g(48,o)}}const J=class O{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();O.levelName.includes(t)?this.level=O.levelName.indexOf(t):this.level=O.Error}else this.level=O.Error}static get logger(){return globalThis.crossauthLogger}setLevel(e){this.level=e}log(e,t){e<=this.level&&(typeof t=="string"?console.log("Crossauth "+O.levelName[e]+" "+new Date().toISOString(),t):console.log(JSON.stringify({level:O.levelName[e],time:new Date().toISOString(),...t})))}error(e){this.log(O.Error,e)}warn(e){this.log(O.Warn,e)}info(e){this.log(O.Info,e)}debug(e){this.log(O.Debug,e)}static setLogger(e,t){globalThis.crossauthLogger=e,globalThis.crossauthLoggerAcceptsJson=t}};u(J,"None",0),u(J,"Error",1),u(J,"Warn",2),u(J,"Info",3),u(J,"Debug",4),u(J,"levelName",["NONE","ERROR","WARN","INFO","DEBUG"]);let d=J;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 ye={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},re=crypto,we=r=>r instanceof CryptoKey,te=new TextEncoder,V=new TextDecoder;function He(...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},B=r=>{let e=r;e instanceof Uint8Array&&(e=V.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 N extends oe{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}}class b extends oe{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}}class M 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 H(r,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${r}`)}function ie(r,e){return r.name===e}function ce(r){return parseInt(r.name.slice(4),10)}function xe(r){switch(r){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function De(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 We(r,e,...t){switch(e){case"HS256":case"HS384":case"HS512":{if(!ie(r.algorithm,"HMAC"))throw H("HMAC");const o=parseInt(e.slice(2),10);if(ce(r.algorithm.hash)!==o)throw H(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!ie(r.algorithm,"RSASSA-PKCS1-v1_5"))throw H("RSASSA-PKCS1-v1_5");const o=parseInt(e.slice(2),10);if(ce(r.algorithm.hash)!==o)throw H(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!ie(r.algorithm,"RSA-PSS"))throw H("RSA-PSS");const o=parseInt(e.slice(2),10);if(ce(r.algorithm.hash)!==o)throw H(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(r.algorithm.name!=="Ed25519"&&r.algorithm.name!=="Ed448")throw H("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!ie(r.algorithm,"ECDSA"))throw H("ECDSA");const o=xe(e);if(r.algorithm.namedCurve!==o)throw H(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}De(r,t)}function me(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 ve=(r,...e)=>me("Key must be ",r,...e);function ke(r,e,...t){return me(`Key for the ${r} algorithm must be `,e,...t)}const Ce=r=>we(r)?!0:(r==null?void 0:r[Symbol.toStringTag])==="KeyObject",se=["CryptoKey"],Fe=(...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 Je(r){return typeof r=="object"&&r!==null}function G(r){if(!Je(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 Me=(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 Be(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 N('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 N('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 N('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new N('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:t}}const _e=async r=>{if(!r.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:e,keyUsages:t}=Be(r),o=[e,r.ext??!1,r.key_ops??t],i={...r};return delete i.alg,delete i.use,re.subtle.importKey("jwk",i,...o)},Se=r=>B(r);let de,he;const Te=r=>(r==null?void 0:r[Symbol.toStringTag])==="KeyObject",be=async(r,e,t,o)=>{let i=r.get(e);if(i!=null&&i[o])return i[o];const n=await _e({...t,alg:o});return i?i[o]=n:r.set(e,{[o]:n}),n},Le=(r,e)=>{if(Te(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?Se(t.k):(he||(he=new WeakMap),be(he,r,t,e))}return r},$e=(r,e)=>{if(Te(r)){let t=r.export({format:"jwk"});return t.k?Se(t.k):(de||(de=new WeakMap),be(de,r,t,e))}return r},qe={normalizePublicKey:Le,normalizePrivateKey:$e},x=(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])||x(r,e,o+1)},Ae=r=>{switch(!0){case x(r,[42,134,72,206,61,3,1,7]):return"P-256";case x(r,[43,129,4,0,34]):return"P-384";case x(r,[43,129,4,0,35]):return"P-521";case x(r,[43,101,110]):return"X25519";case x(r,[43,101,111]):return"X448";case x(r,[43,101,112]):return"Ed25519";case x(r,[43,101,113]):return"Ed448";default:throw new N("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},Ee=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=Ae(a);n=l.startsWith("P-")?{name:"ECDH",namedCurve:l}:{name:l},s=c?[]:["deriveBits"];break}case"EdDSA":n={name:Ae(a)},s=c?["verify"]:["sign"];break;default:throw new N('Invalid or unsupported "alg" (Algorithm) value')}return re.subtle.importKey(e,a,n,!1,s)},Ve=(r,e,t)=>Ee(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",r,e),Ge=(r,e,t)=>Ee(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",r,e);async function Ye(r,e,t){if(typeof r!="string"||r.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return Ge(r,e)}async function Xe(r,e,t){if(typeof r!="string"||r.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return Ve(r,e)}async function Pe(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 B(r.k);case"RSA":if(r.oth!==void 0)throw new N('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return _e({...r,alg:e});default:throw new N('Unsupported "kty" (Key Type) Parameter value')}}const ne=r=>r==null?void 0:r[Symbol.toStringTag],Ze=(r,e)=>{if(!(e instanceof Uint8Array)){if(!Ce(e))throw new TypeError(ke(r,e,...se,"Uint8Array"));if(e.type!=="secret")throw new TypeError(`${ne(e)} instances for symmetric algorithms must be of type "secret"`)}},Qe=(r,e,t)=>{if(!Ce(e))throw new TypeError(ke(r,e,...se));if(e.type==="secret")throw new TypeError(`${ne(e)} instances for asymmetric algorithms must not be of type "secret"`);if(e.algorithm&&t==="verify"&&e.type==="private")throw new TypeError(`${ne(e)} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&t==="encrypt"&&e.type==="private")throw new TypeError(`${ne(e)} instances for asymmetric algorithm encryption must be of type "public"`)},er=(r,e,t)=>{r.startsWith("HS")||r==="dir"||r.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(r)?Ze(r,e):Qe(r,e,t)};function rr(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 N(`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 tr(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 N(`alg ${r} is not supported either by JOSE or your javascript runtime`)}}async function or(r,e,t){if(e=await qe.normalizePublicKey(e,r),we(e))return We(e,r,t),e;if(e instanceof Uint8Array){if(!r.startsWith("HS"))throw new TypeError(ve(e,...se));return re.subtle.importKey("raw",e,{hash:`SHA-${r.slice(-3)}`,name:"HMAC"},!1,[t])}throw new TypeError(ve(e,...se,"Uint8Array"))}const ir=async(r,e,t,o)=>{const i=await or(r,e,"verify");Me(r,i);const n=tr(r,i.algorithm);try{return await re.subtle.verify(n,i,t,o)}catch{return!1}};async function sr(r,e,t){if(!G(r))throw new b("Flattened JWS must be an object");if(r.protected===void 0&&r.header===void 0)throw new b('Flattened JWS must have either of the "protected" or "header" members');if(r.protected!==void 0&&typeof r.protected!="string")throw new b("JWS Protected Header incorrect type");if(r.payload===void 0)throw new b("JWS Payload missing");if(typeof r.signature!="string")throw new b("JWS Signature missing or incorrect type");if(r.header!==void 0&&!G(r.header))throw new b("JWS Unprotected Header incorrect type");let o={};if(r.protected)try{const Z=B(r.protected);o=JSON.parse(V.decode(Z))}catch{throw new b("JWS Protected Header is invalid")}if(!Fe(o,r.header))throw new b("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const i={...o,...r.header},n=rr(b,new Map([["b64",!0]]),void 0,o,i);let s=!0;if(n.has("b64")&&(s=o.b64,typeof s!="boolean"))throw new b('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=i;if(typeof a!="string"||!a)throw new b('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(s){if(typeof r.payload!="string")throw new b("JWS Payload must be a string")}else if(typeof r.payload!="string"&&!(r.payload instanceof Uint8Array))throw new b("JWS Payload must be a string or an Uint8Array instance");let c=!1;typeof e=="function"&&(e=await e(o,r),c=!0),er(a,e,"verify");const l=He(te.encode(r.protected??""),te.encode("."),typeof r.payload=="string"?te.encode(r.payload):r.payload);let w;try{w=B(r.signature)}catch{throw new b("Failed to base64url decode the signature")}if(!await ir(a,e,w,l))throw new ze;let T;if(s)try{T=B(r.payload)}catch{throw new b("Failed to base64url decode the payload")}else typeof r.payload=="string"?T=te.encode(r.payload):T=r.payload;const R={payload:T};return r.protected!==void 0&&(R.protectedHeader=o),r.header!==void 0&&(R.unprotectedHeader=r.header),c?{...R,key:e}:R}async function nr(r,e,t){if(r instanceof Uint8Array&&(r=V.decode(r)),typeof r!="string")throw new b("Compact JWS must be a string or Uint8Array");const{0:o,1:i,2:n,length:s}=r.split(".");if(s!==3)throw new b("Invalid Compact JWS");const a=await sr({payload:i,protected:o,signature:n},e),c={payload:a.payload,protectedHeader:a.protectedHeader};return typeof e=="function"?{...c,key:a.key}:c}const Re=B;function Ie(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(V.decode(Re(e)));if(!G(t))throw new Error;return t}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}function ar(r){if(typeof r!="string")throw new M("JWTs must use Compact JWS serialization, JWT must be a string");const{1:e,length:t}=r.split(".");if(t===5)throw new M("Only JWTs using Compact JWS serialization can be decoded");if(t!==3)throw new M("Invalid JWT");if(!e)throw new M("JWTs must contain a payload");let o;try{o=Re(e)}catch{throw new M("Failed to base64url decode the payload")}let i;try{i=JSON.parse(V.decode(o))}catch{throw new M("Failed to parse the decoded payload as JSON")}if(!G(i))throw new M("Invalid JWT Claims Set");return i}const S=class C{static flowNames(e){let t={};return e.forEach(o=>{o in C.flowName&&(t[o]=C.flowName[o])}),t}static isValidFlow(e){return C.allFlows().includes(e)}static areAllValidFlows(e){let t=!0;return e.forEach(o=>{C.isValidFlow(o)||(t=!1)}),t}static allFlows(){return[C.AuthorizationCode,C.AuthorizationCodeWithPKCE,C.ClientCredentials,C.RefreshToken,C.DeviceCode,C.Password,C.PasswordMfa,C.OidcAuthorizationCode]}static grantType(e){switch(e){case C.AuthorizationCode:case C.AuthorizationCodeWithPKCE:case C.OidcAuthorizationCode:return["authorization_code"];case C.ClientCredentials:return["client_credentials"];case C.RefreshToken:return["refresh_token"];case C.Password:return["password"];case C.PasswordMfa:return["http://auth0.com/oauth/grant-type/mfa-otp","http://auth0.com/oauth/grant-type/mfa-oob"];case C.DeviceCode:return["urn:ietf:params:oauth:grant-type:device_code"]}}};u(S,"All","all"),u(S,"AuthorizationCode","authorizationCode"),u(S,"AuthorizationCodeWithPKCE","authorizationCodeWithPKCE"),u(S,"ClientCredentials","clientCredentials"),u(S,"RefreshToken","refreshToken"),u(S,"DeviceCode","deviceCode"),u(S,"Password","password"),u(S,"PasswordMfa","passwordMfa"),u(S,"OidcAuthorizationCode","oidcAuthorizationCode"),u(S,"flowName",{[S.AuthorizationCode]:"Authorization Code",[S.AuthorizationCodeWithPKCE]:"Authorization Code with PKCE",[S.ClientCredentials]:"Client Credentials",[S.RefreshToken]:"Refresh Token",[S.DeviceCode]:"Device Code",[S.Password]:"Password",[S.PasswordMfa]:"Password MFA",[S.OidcAuthorizationCode]:"OIDC Authorization Code"});var A,P;class cr{constructor({authServerBaseUrl:e,client_id:t,client_secret:o,redirect_uri:i,codeChallengeMethod:n,stateLength:s,verifierLength:a,tokenConsumer:c,authServerCredentials:l,authServerMode:w,authServerHeaders:T}){u(this,"authServerBaseUrl",""),pe(this,A),pe(this,P),u(this,"codeChallengeMethod","S256"),u(this,"verifierLength",32),u(this,"redirect_uri"),u(this,"stateLength",32),u(this,"authzCode",""),u(this,"oidcConfig"),u(this,"tokenConsumer"),u(this,"authServerHeaders",{}),u(this,"authServerMode"),u(this,"authServerCredentials"),u(this,"oauthPostType","json"),u(this,"oauthLogFetch",!1),u(this,"oauthUseUserInfoEndpoint",!1),u(this,"oauthAuthorizeRedirect"),this.tokenConsumer=c,this.authServerBaseUrl=e,a&&(this.verifierLength=a),s&&(this.stateLength=s),t&&ee(this,A,t),o&&ee(this,P,o),i&&(this.redirect_uri=i),n&&(this.codeChallengeMethod=n),this.authServerBaseUrl=e,l&&(this.authServerCredentials=l),w&&(this.authServerMode=w),T&&(this.authServerHeaders=T)}set client_id(e){ee(this,A,e)}set client_secret(e){ee(this,P,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(k.Connection,"Couldn't get OIDC configuration from URL"+this.authServerBaseUrl+"/.well-known/openid-configuration");this.oidcConfig={...ye};try{const o=await t.json();for(const[i,n]of Object.entries(o))this.oidcConfig[i]=n}catch{throw new g(k.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(!m(this,A))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(m(this,A))+"&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,w;l="authorization_code",w=m(this,P);let T={grant_type:l,client_id:m(this,A),code:this.authzCode,redirect_uri:this.redirect_uri};t&&(T.scope=t),w&&(T.client_secret=w),o&&(T.code_verifier=o);try{let R=await this.post(c,T,this.authServerHeaders);if(R.id_token){const Z=await this.getIdPayload(R.id_token,R.access_token);if(Z.error)return Z;R.id_payload=Z.payload}return R}catch(R){return d.logger.error(h({err:R})),{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(!m(this,A))return{error:"invalid_request",error_description:"Cannot make client credentials flow without client id"};const i=this.oidcConfig.token_endpoint;let n={grant_type:"client_credentials",client_id:m(this,A),client_secret:m(this,P)};e&&(n.scope=e);try{let s=await this.post(i,n,this.authServerHeaders);if(s.id_token){const a=await this.getIdPayload(s.id_token,s.access_token);if(a.error)return a;s.id_payload=a.payload}return s}catch(s){return d.logger.error(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:m(this,A),client_secret:m(this,P),username:e,password:t};o&&(a.scope=o);try{let c=await this.post(s,a,this.authServerHeaders);if(c.id_token){const 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:m(this,A),client_secret:m(this,P),challenge_type:"otp",mfa_token:e,authenticator_id:t},this.authServerHeaders);return s.challenge_type!="otp"?{error:s.error??"server_error",error_description:s.error_description??"Invalid OTP challenge response"}:s}async mfaOtpComplete(e,t,o){var i,n;if(d.logger.debug(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:m(this,A),client_secret:m(this,P),challenge_type:"otp",mfa_token:e,otp:t,scope:o},this.authServerHeaders);if(a.id_token){const c=await this.getIdPayload(a.id_token,a.access_token);if(c.error)return c;a.id_payload=c.payload}return{id_token:a.id_token,access_token:a.access_token,refresh_token:a.refresh_token,expires_in:Number(a.expires_in),scope:a.scope,token_type:a.token_type,error:a.error,error_description:a.error_description}}async mfaOobRequest(e,t){var o,i;if(d.logger.debug(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:m(this,A),client_secret:m(this,P),challenge_type:"oob",mfa_token:e,authenticator_id:t},this.authServerHeaders);return s.challenge_type!="oob"||!s.oob_code||!s.binding_method?{error:s.error??"server_error",error_description:s.error_description??"Invalid OOB challenge response"}:{challenge_type:s.challenge_type,oob_code:s.oob_code,binding_method:s.binding_method,error:s.error,error_description:s.error_description}}async mfaOobComplete(e,t,o,i){var n,s;if(d.logger.debug(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:m(this,A),client_secret:m(this,P),challenge_type:"otp",mfa_token:e,oob_code:t,binding_code:o,scope:i},this.authServerHeaders);if(c.error)return{error:c.error,error_description:c.error_description};if(c.id_token){const 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=m(this,P);let s={grant_type:"refresh_token",refresh_token:e,client_id:m(this,A)};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:m(this,A),client_secret:m(this,P)};t&&(i.scope=t);try{let n=await this.post(e,i,this.authServerHeaders);return n.id_token&&!await this.validateIdToken(n.id_token)?{error:"access_denied",error_description:"Invalid ID token"}:n}catch(n){return d.logger.error(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:m(this,A),client_secret:m(this,P),device_code:e};try{const s=await this.post((i=this.oidcConfig)==null?void 0:i.token_endpoint,n,this.authServerHeaders);if(s.error)return s;if(s.id_token){const a=await this.getIdPayload(s.id_token,s.access_token);if(a.error)return a;s.id_payload=a.payload}return s}catch(s){return d.logger.error(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 ar(e)}}A=new WeakMap,P=new WeakMap;class dr{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(k.Configuration,"If specifying jwtPublic key, must also specify jwtKeyType")}async loadKeys(e){try{if(this.jwtSecretKey){if(!this.jwtKeyType)throw new g(k.Configuration,"Must specify jwtKeyType if setting jwtSecretKey");this.keys._default=await Xe(this.jwtSecretKey,this.jwtKeyType)}else if(this.jwtPublicKey){if(!this.jwtKeyType)throw new g(k.Configuration,"Must specify jwtKeyType if setting jwtPublicKey");const t=await Ye(this.jwtPublicKey,this.jwtKeyType);this.keys._default=t}else{if(this.oidcConfig||await this.loadConfig(),!this.oidcConfig)throw new g(k.Connection,"Load OIDC config before Jwks");await this.loadJwks(void 0,e)}}catch(t){throw d.logger.debug(h({err:t})),new g(k.Connection,"Couldn't load keys")}}async loadConfig(e){if(e){this.oidcConfig=e;return}if(!this.authServerBaseUrl)throw new g(k.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(k.Connection,"Couldn't get OIDC configuration");this.oidcConfig={...ye};try{const o=await t.json();for(const[i,n]of Object.entries(o))this.oidcConfig[i]=n}catch{throw new g(k.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(k.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(k.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(k.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(k.Connection,"Couldn't load keys")}}catch(i){throw d.logger.error(h({err:i})),new g(k.Connection,"Unrecognized response from OIDC jwks endpoint")}}}async tokenAuthorized(e,t,o){if(!this.keys||Object.keys(this.keys).length==0){const n=Ie(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=Ie(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 nr(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 Oe=30,ae=2,le=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(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-Oe;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-Oe<l){d.logger.debug(h({msg:"Refresh token has expired"}));return}let w=T=>new Promise(R=>setTimeout(R,T));d.logger.debug(h({msg:`Waiting ${l} before refreshing tokens`})),o=l,await w(l),await this.autoRefresh(e,n,t)}async autoRefresh(e,t,o){if(this.autoRefreshActive){let i,n=!1,s=0;for(;!n&&s<=ae;)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{d.logger.error(h({msg:"/refresh returned a non-JSON response "+(i?await i.text():void 0)})),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 w=g.asCrossauthError(l);o?o("Couldn't receive tokens",w):(d.logger.debug(h({err:l})),d.logger.error(h({msg:"Error receiving tokens",cerr:w})))}}else s<ae?(d.logger.error(h({msg:`Failed auto refreshing tokens. Retrying in ${le} seconds`})),await(w=>new Promise(T=>setTimeout(T,w)))(le*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<ae?(d.logger.error(h({msg:`Failed auto refreshing tokens. Retrying in ${ae} seconds`})),await(w=>new Promise(T=>setTimeout(T,w)))(le*1e3)):(d.logger.error(h({msg:"Failed auto refreshing tokens. Number of retries exceeded"})),o&&o(c.message,c)),s++}}}}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(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(w=>setTimeout(w,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 hr{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,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 lr{getCsrfToken(){return new Promise(e=>{})}}class Ue extends dr{async hash(e){const o=new TextEncoder().encode(e),i=await crypto.subtle.digest("SHA-256",o),n=Array.from(new Uint8Array(i));return btoa(n.reduce((s,a)=>s+String.fromCharCode(a),"")).replace(/\//g,"_").replace(/\+/g,"-").replace(/=+$/,"")}}class ur extends cr{constructor(t){t.tokenConsumer||(t.tokenConsumer=new Ue(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");I(this,D);I(this,K);I(this,j);I(this,W);I(this,F);I(this,L);I(this,$);f(this,"autoRefresher");f(this,"deviceCodePoller");f(this,"deviceAuthorizationUrl","device_authorization");I(this,Y);I(this,X);I(this,q);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&&E(this,L,t.client_id),t.client_secret&&E(this,$,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,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&&(E(this,D,i),E(this,W,s))}if(n){const s=this.getTokenPayload(n);s&&(E(this,K,n),E(this,F,s))}o?this.validateIdToken(o).then(s=>{E(this,j,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"}))}):y(this,D)&&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 y(this,j)}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,w]of o)l=="code"&&(i=w),l=="state"&&(n=w),l=="error"&&(s=w),l=="error_description"&&(a=w);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(y(this,q)&&n!=y(this,q))return{error:"access_denied",error_description:"Invalid state"};const c=await this.redirectEndpoint(i,this.scope,y(this,X),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 y(this,j)}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 y(this,j)&&(i=y(this,j).exp?y(this,j).exp:null),y(this,W)&&(n=y(this,W).exp?y(this,W).exp:null),y(this,F)&&(s=y(this,F).exp?y(this,F).exp:null),{id:i,access:n,refresh:s}}async jsonFetchWithToken(t,o,i){if(i=="access"){if(!y(this,D))throw new g(k.InvalidToken,"Cannot make fetch with access token - no access token defined");o.headers||(o.headers={}),o.headers.authorization="Bearer "+y(this,D)}else{if(o.body||(o.body={}),!y(this,K))throw new g(k.InvalidToken,"Cannot make fetch with refresh token - no refresh token defined");o.body.refresh_token=y(this,K),o.body.grant_type="refresh_token"}return y(this,L)&&(o.body||(o.body={}),o.body.client_id=y(this,L),y(this,$)&&(o.body.client_secret=y(this,$))),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&&(E(this,D,t.access_token),E(this,W,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&&(E(this,K,t.refresh_token),E(this,F,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);E(this,j,o),this.idTokenResponseType=="localStorage"?localStorage.setItem(this.idTokenName,t.id_token):this.idTokenResponseType=="sessionStorage"&&sessionStorage.setItem(this.idTokenName,t.id_token)}}async clientCredentialsFlow(t){const o=await super.clientCredentialsFlow(t);return await this.receiveTokens(o),o}async passwordFlow(t,o,i){const n=await super.passwordFlow(t,o,i);return await this.receiveTokens(n),n}async deviceCodeFlow(t){let o=this.authServerBaseUrl;return o.endsWith("/")||(o+="/"),o+=this.deviceAuthorizationUrl,await super.startDeviceCodeFlow(o,t)}async mfaOtpComplete(t,o){const i=await super.mfaOtpComplete(t,o);return await this.receiveTokens(i),i}async mfaOobComplete(t,o,i){const n=await super.mfaOobComplete(t,o,i);return await this.receiveTokens(n),n}async refreshTokenFlow(t){if(!t)if(y(this,K))t=y(this,K);else throw new g(k.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();E(this,Y,s.codeChallenge),E(this,X,s.codeVerifier),E(this,q,i)}const n=await super.startAuthorizationCodeFlow(i,t,y(this,Y),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}}return D=new WeakMap,K=new WeakMap,j=new WeakMap,W=new WeakMap,F=new WeakMap,L=new WeakMap,$=new WeakMap,Y=new WeakMap,X=new WeakMap,q=new WeakMap,p.CrossauthError=g,p.CrossauthLogger=d,p.OAuthAutoRefresher=ue,p.OAuthBffClient=hr,p.OAuthClient=ur,p.OAuthDeviceCodePoller=fe,p.OAuthTokenConsumer=Ue,p.OAuthTokenProvider=lr,p.j=h,Object.defineProperty(p,Symbol.toStringTag,{value:"Module"}),p}({});
|
|
1
|
+
var crossauth_frontend=function(p){"use strict";var fr=Object.defineProperty;var Ne=p=>{throw TypeError(p)};var gr=(p,v,_)=>v in p?fr(p,v,{enumerable:!0,configurable:!0,writable:!0,value:_}):p[v]=_;var f=(p,v,_)=>gr(p,typeof v!="symbol"?v+"":v,_),je=(p,v,_)=>v.has(p)||Ne("Cannot "+_);var y=(p,v,_)=>(je(p,v,"read from private field"),_?_.call(p):v.get(p)),I=(p,v,_)=>v.has(p)?Ne("Cannot add the same private member more than once"):v instanceof WeakSet?v.add(p):v.set(p,_),E=(p,v,_,Q)=>(je(p,v,"write to private field"),Q?Q.call(p,_):v.set(p,_),_);var D,K,j,W,F,L,$,Y,X,q;var v=Object.defineProperty,_=r=>{throw TypeError(r)},Q=(r,e,t)=>e in r?v(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,u=(r,e,t)=>Q(r,typeof e!="symbol"?e+"":e,t),ge=(r,e,t)=>e.has(r)||_("Cannot "+t),m=(r,e,t)=>(ge(r,e,"read from private field"),e.get(r)),pe=(r,e,t)=>e.has(r)?_("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),ee=(r,e,t,o)=>(ge(r,e,"write to private field"),e.set(r,t),t);class z{}u(z,"active","active"),u(z,"disabled","disabled"),u(z,"awaitingTwoFactorSetup","awaitingtwofactorsetup"),u(z,"awaitingEmailVerification","awaitingemailverification"),u(z,"passwordChangeNeeded","passwordchangeneeded"),u(z,"passwordResetNeeded","passwordresetneeded"),u(z,"factor2ResetNeeded","factor2resetneeded"),u(z,"passwordAndFactor2ResetNeeded","passwordandfactor2resetneeded");class U{}u(U,"session","s:"),u(U,"passwordResetToken","p:"),u(U,"emailVerificationToken","e:"),u(U,"apiKey","api:"),u(U,"authorizationCode","authz:"),u(U,"accessToken","access:"),u(U,"refreshToken","refresh:"),u(U,"mfaToken","omfa:"),u(U,"deviceCode","dc:"),u(U,"userCode","uc:");var k=(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))(k||{});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=k[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??k[i];return"errorMessage"in e?n=e.errorMessage:"message"in e&&(n=e.message),new g(i,n)}let o=t??k[48];return"message"in e&&(o=e.message),new g(48,o)}}const J=class O{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();O.levelName.includes(t)?this.level=O.levelName.indexOf(t):this.level=O.Error}else this.level=O.Error}static get logger(){return globalThis.crossauthLogger}setLevel(e){this.level=e}log(e,t){e<=this.level&&(typeof t=="string"?console.log("Crossauth "+O.levelName[e]+" "+new Date().toISOString(),t):console.log(JSON.stringify({level:O.levelName[e],time:new Date().toISOString(),...t})))}error(e){this.log(O.Error,e)}warn(e){this.log(O.Warn,e)}info(e){this.log(O.Info,e)}debug(e){this.log(O.Debug,e)}static setLogger(e,t){globalThis.crossauthLogger=e,globalThis.crossauthLoggerAcceptsJson=t}};u(J,"None",0),u(J,"Error",1),u(J,"Warn",2),u(J,"Info",3),u(J,"Debug",4),u(J,"levelName",["NONE","ERROR","WARN","INFO","DEBUG"]);let d=J;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 ye={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},re=crypto,we=r=>r instanceof CryptoKey,te=new TextEncoder,V=new TextDecoder;function He(...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},B=r=>{let e=r;e instanceof Uint8Array&&(e=V.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 N extends oe{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}}class b extends oe{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}}class M 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 H(r,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${r}`)}function ie(r,e){return r.name===e}function ce(r){return parseInt(r.name.slice(4),10)}function xe(r){switch(r){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function De(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 We(r,e,...t){switch(e){case"HS256":case"HS384":case"HS512":{if(!ie(r.algorithm,"HMAC"))throw H("HMAC");const o=parseInt(e.slice(2),10);if(ce(r.algorithm.hash)!==o)throw H(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!ie(r.algorithm,"RSASSA-PKCS1-v1_5"))throw H("RSASSA-PKCS1-v1_5");const o=parseInt(e.slice(2),10);if(ce(r.algorithm.hash)!==o)throw H(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!ie(r.algorithm,"RSA-PSS"))throw H("RSA-PSS");const o=parseInt(e.slice(2),10);if(ce(r.algorithm.hash)!==o)throw H(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(r.algorithm.name!=="Ed25519"&&r.algorithm.name!=="Ed448")throw H("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!ie(r.algorithm,"ECDSA"))throw H("ECDSA");const o=xe(e);if(r.algorithm.namedCurve!==o)throw H(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}De(r,t)}function me(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 ve=(r,...e)=>me("Key must be ",r,...e);function ke(r,e,...t){return me(`Key for the ${r} algorithm must be `,e,...t)}const Ce=r=>we(r)?!0:(r==null?void 0:r[Symbol.toStringTag])==="KeyObject",se=["CryptoKey"],Fe=(...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 Je(r){return typeof r=="object"&&r!==null}function G(r){if(!Je(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 Me=(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 Be(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 N('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 N('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 N('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new N('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:t}}const _e=async r=>{if(!r.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:e,keyUsages:t}=Be(r),o=[e,r.ext??!1,r.key_ops??t],i={...r};return delete i.alg,delete i.use,re.subtle.importKey("jwk",i,...o)},Se=r=>B(r);let de,he;const Te=r=>(r==null?void 0:r[Symbol.toStringTag])==="KeyObject",be=async(r,e,t,o)=>{let i=r.get(e);if(i!=null&&i[o])return i[o];const n=await _e({...t,alg:o});return i?i[o]=n:r.set(e,{[o]:n}),n},Le=(r,e)=>{if(Te(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?Se(t.k):(he||(he=new WeakMap),be(he,r,t,e))}return r},$e=(r,e)=>{if(Te(r)){let t=r.export({format:"jwk"});return t.k?Se(t.k):(de||(de=new WeakMap),be(de,r,t,e))}return r},qe={normalizePublicKey:Le,normalizePrivateKey:$e},x=(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])||x(r,e,o+1)},Ae=r=>{switch(!0){case x(r,[42,134,72,206,61,3,1,7]):return"P-256";case x(r,[43,129,4,0,34]):return"P-384";case x(r,[43,129,4,0,35]):return"P-521";case x(r,[43,101,110]):return"X25519";case x(r,[43,101,111]):return"X448";case x(r,[43,101,112]):return"Ed25519";case x(r,[43,101,113]):return"Ed448";default:throw new N("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},Ee=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=Ae(a);n=l.startsWith("P-")?{name:"ECDH",namedCurve:l}:{name:l},s=c?[]:["deriveBits"];break}case"EdDSA":n={name:Ae(a)},s=c?["verify"]:["sign"];break;default:throw new N('Invalid or unsupported "alg" (Algorithm) value')}return re.subtle.importKey(e,a,n,!1,s)},Ve=(r,e,t)=>Ee(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",r,e),Ge=(r,e,t)=>Ee(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",r,e);async function Ye(r,e,t){if(typeof r!="string"||r.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return Ge(r,e)}async function Xe(r,e,t){if(typeof r!="string"||r.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return Ve(r,e)}async function Pe(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 B(r.k);case"RSA":if(r.oth!==void 0)throw new N('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return _e({...r,alg:e});default:throw new N('Unsupported "kty" (Key Type) Parameter value')}}const ne=r=>r==null?void 0:r[Symbol.toStringTag],Ze=(r,e)=>{if(!(e instanceof Uint8Array)){if(!Ce(e))throw new TypeError(ke(r,e,...se,"Uint8Array"));if(e.type!=="secret")throw new TypeError(`${ne(e)} instances for symmetric algorithms must be of type "secret"`)}},Qe=(r,e,t)=>{if(!Ce(e))throw new TypeError(ke(r,e,...se));if(e.type==="secret")throw new TypeError(`${ne(e)} instances for asymmetric algorithms must not be of type "secret"`);if(e.algorithm&&t==="verify"&&e.type==="private")throw new TypeError(`${ne(e)} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&t==="encrypt"&&e.type==="private")throw new TypeError(`${ne(e)} instances for asymmetric algorithm encryption must be of type "public"`)},er=(r,e,t)=>{r.startsWith("HS")||r==="dir"||r.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(r)?Ze(r,e):Qe(r,e,t)};function rr(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 N(`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 tr(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 N(`alg ${r} is not supported either by JOSE or your javascript runtime`)}}async function or(r,e,t){if(e=await qe.normalizePublicKey(e,r),we(e))return We(e,r,t),e;if(e instanceof Uint8Array){if(!r.startsWith("HS"))throw new TypeError(ve(e,...se));return re.subtle.importKey("raw",e,{hash:`SHA-${r.slice(-3)}`,name:"HMAC"},!1,[t])}throw new TypeError(ve(e,...se,"Uint8Array"))}const ir=async(r,e,t,o)=>{const i=await or(r,e,"verify");Me(r,i);const n=tr(r,i.algorithm);try{return await re.subtle.verify(n,i,t,o)}catch{return!1}};async function sr(r,e,t){if(!G(r))throw new b("Flattened JWS must be an object");if(r.protected===void 0&&r.header===void 0)throw new b('Flattened JWS must have either of the "protected" or "header" members');if(r.protected!==void 0&&typeof r.protected!="string")throw new b("JWS Protected Header incorrect type");if(r.payload===void 0)throw new b("JWS Payload missing");if(typeof r.signature!="string")throw new b("JWS Signature missing or incorrect type");if(r.header!==void 0&&!G(r.header))throw new b("JWS Unprotected Header incorrect type");let o={};if(r.protected)try{const Z=B(r.protected);o=JSON.parse(V.decode(Z))}catch{throw new b("JWS Protected Header is invalid")}if(!Fe(o,r.header))throw new b("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const i={...o,...r.header},n=rr(b,new Map([["b64",!0]]),void 0,o,i);let s=!0;if(n.has("b64")&&(s=o.b64,typeof s!="boolean"))throw new b('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=i;if(typeof a!="string"||!a)throw new b('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(s){if(typeof r.payload!="string")throw new b("JWS Payload must be a string")}else if(typeof r.payload!="string"&&!(r.payload instanceof Uint8Array))throw new b("JWS Payload must be a string or an Uint8Array instance");let c=!1;typeof e=="function"&&(e=await e(o,r),c=!0),er(a,e,"verify");const l=He(te.encode(r.protected??""),te.encode("."),typeof r.payload=="string"?te.encode(r.payload):r.payload);let w;try{w=B(r.signature)}catch{throw new b("Failed to base64url decode the signature")}if(!await ir(a,e,w,l))throw new ze;let T;if(s)try{T=B(r.payload)}catch{throw new b("Failed to base64url decode the payload")}else typeof r.payload=="string"?T=te.encode(r.payload):T=r.payload;const R={payload:T};return r.protected!==void 0&&(R.protectedHeader=o),r.header!==void 0&&(R.unprotectedHeader=r.header),c?{...R,key:e}:R}async function nr(r,e,t){if(r instanceof Uint8Array&&(r=V.decode(r)),typeof r!="string")throw new b("Compact JWS must be a string or Uint8Array");const{0:o,1:i,2:n,length:s}=r.split(".");if(s!==3)throw new b("Invalid Compact JWS");const a=await sr({payload:i,protected:o,signature:n},e),c={payload:a.payload,protectedHeader:a.protectedHeader};return typeof e=="function"?{...c,key:a.key}:c}const Re=B;function Ie(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(V.decode(Re(e)));if(!G(t))throw new Error;return t}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}function ar(r){if(typeof r!="string")throw new M("JWTs must use Compact JWS serialization, JWT must be a string");const{1:e,length:t}=r.split(".");if(t===5)throw new M("Only JWTs using Compact JWS serialization can be decoded");if(t!==3)throw new M("Invalid JWT");if(!e)throw new M("JWTs must contain a payload");let o;try{o=Re(e)}catch{throw new M("Failed to base64url decode the payload")}let i;try{i=JSON.parse(V.decode(o))}catch{throw new M("Failed to parse the decoded payload as JSON")}if(!G(i))throw new M("Invalid JWT Claims Set");return i}const S=class C{static flowNames(e){let t={};return e.forEach(o=>{o in C.flowName&&(t[o]=C.flowName[o])}),t}static isValidFlow(e){return C.allFlows().includes(e)}static areAllValidFlows(e){let t=!0;return e.forEach(o=>{C.isValidFlow(o)||(t=!1)}),t}static allFlows(){return[C.AuthorizationCode,C.AuthorizationCodeWithPKCE,C.ClientCredentials,C.RefreshToken,C.DeviceCode,C.Password,C.PasswordMfa,C.OidcAuthorizationCode]}static grantType(e){switch(e){case C.AuthorizationCode:case C.AuthorizationCodeWithPKCE:case C.OidcAuthorizationCode:return["authorization_code"];case C.ClientCredentials:return["client_credentials"];case C.RefreshToken:return["refresh_token"];case C.Password:return["password"];case C.PasswordMfa:return["http://auth0.com/oauth/grant-type/mfa-otp","http://auth0.com/oauth/grant-type/mfa-oob"];case C.DeviceCode:return["urn:ietf:params:oauth:grant-type:device_code"]}}};u(S,"All","all"),u(S,"AuthorizationCode","authorizationCode"),u(S,"AuthorizationCodeWithPKCE","authorizationCodeWithPKCE"),u(S,"ClientCredentials","clientCredentials"),u(S,"RefreshToken","refreshToken"),u(S,"DeviceCode","deviceCode"),u(S,"Password","password"),u(S,"PasswordMfa","passwordMfa"),u(S,"OidcAuthorizationCode","oidcAuthorizationCode"),u(S,"flowName",{[S.AuthorizationCode]:"Authorization Code",[S.AuthorizationCodeWithPKCE]:"Authorization Code with PKCE",[S.ClientCredentials]:"Client Credentials",[S.RefreshToken]:"Refresh Token",[S.DeviceCode]:"Device Code",[S.Password]:"Password",[S.PasswordMfa]:"Password MFA",[S.OidcAuthorizationCode]:"OIDC Authorization Code"});var A,P;class cr{constructor({authServerBaseUrl:e,client_id:t,client_secret:o,redirect_uri:i,codeChallengeMethod:n,stateLength:s,verifierLength:a,tokenConsumer:c,authServerCredentials:l,authServerMode:w,authServerHeaders:T}){u(this,"authServerBaseUrl",""),pe(this,A),pe(this,P),u(this,"codeChallengeMethod","S256"),u(this,"verifierLength",32),u(this,"redirect_uri"),u(this,"stateLength",32),u(this,"authzCode",""),u(this,"oidcConfig"),u(this,"tokenConsumer"),u(this,"authServerHeaders",{}),u(this,"authServerMode"),u(this,"authServerCredentials"),u(this,"oauthPostType","json"),u(this,"oauthLogFetch",!1),u(this,"oauthUseUserInfoEndpoint",!1),u(this,"oauthAuthorizeRedirect"),this.tokenConsumer=c,this.authServerBaseUrl=e,a&&(this.verifierLength=a),s&&(this.stateLength=s),t&&ee(this,A,t),o&&ee(this,P,o),i&&(this.redirect_uri=i),n&&(this.codeChallengeMethod=n),this.authServerBaseUrl=e,l&&(this.authServerCredentials=l),w&&(this.authServerMode=w),T&&(this.authServerHeaders=T)}set client_id(e){ee(this,A,e)}set client_secret(e){ee(this,P,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(k.Connection,"Couldn't get OIDC configuration from URL"+this.authServerBaseUrl+"/.well-known/openid-configuration");this.oidcConfig={...ye};try{const o=await t.json();for(const[i,n]of Object.entries(o))this.oidcConfig[i]=n}catch{throw new g(k.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(!m(this,A))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(m(this,A))+"&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,w;l="authorization_code",w=m(this,P);let T={grant_type:l,client_id:m(this,A),code:this.authzCode,redirect_uri:this.redirect_uri};t&&(T.scope=t),w&&(T.client_secret=w),o&&(T.code_verifier=o);try{let R=await this.post(c,T,this.authServerHeaders);if(R.id_token){const Z=await this.getIdPayload(R.id_token,R.access_token);if(Z.error)return Z;R.id_payload=Z.payload}return R}catch(R){return d.logger.error(h({err:R})),{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(!m(this,A))return{error:"invalid_request",error_description:"Cannot make client credentials flow without client id"};const i=this.oidcConfig.token_endpoint;let n={grant_type:"client_credentials",client_id:m(this,A),client_secret:m(this,P)};e&&(n.scope=e);try{let s=await this.post(i,n,this.authServerHeaders);if(s.id_token){const a=await this.getIdPayload(s.id_token,s.access_token);if(a.error)return a;s.id_payload=a.payload}return s}catch(s){return d.logger.error(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:m(this,A),client_secret:m(this,P),username:e,password:t};o&&(a.scope=o);try{let c=await this.post(s,a,this.authServerHeaders);if(c.id_token){const 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:m(this,A),client_secret:m(this,P),challenge_type:"otp",mfa_token:e,authenticator_id:t},this.authServerHeaders);return s.challenge_type!="otp"?{error:s.error??"server_error",error_description:s.error_description??"Invalid OTP challenge response"}:s}async mfaOtpComplete(e,t,o){var i,n;if(d.logger.debug(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:m(this,A),client_secret:m(this,P),challenge_type:"otp",mfa_token:e,otp:t,scope:o},this.authServerHeaders);if(a.id_token){const c=await this.getIdPayload(a.id_token,a.access_token);if(c.error)return c;a.id_payload=c.payload}return{id_token:a.id_token,access_token:a.access_token,refresh_token:a.refresh_token,expires_in:Number(a.expires_in),scope:a.scope,token_type:a.token_type,error:a.error,error_description:a.error_description}}async mfaOobRequest(e,t){var o,i;if(d.logger.debug(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:m(this,A),client_secret:m(this,P),challenge_type:"oob",mfa_token:e,authenticator_id:t},this.authServerHeaders);return s.challenge_type!="oob"||!s.oob_code||!s.binding_method?{error:s.error??"server_error",error_description:s.error_description??"Invalid OOB challenge response"}:{challenge_type:s.challenge_type,oob_code:s.oob_code,binding_method:s.binding_method,error:s.error,error_description:s.error_description}}async mfaOobComplete(e,t,o,i){var n,s;if(d.logger.debug(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:m(this,A),client_secret:m(this,P),challenge_type:"otp",mfa_token:e,oob_code:t,binding_code:o,scope:i},this.authServerHeaders);if(c.error)return{error:c.error,error_description:c.error_description};if(c.id_token){const 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=m(this,P);let s={grant_type:"refresh_token",refresh_token:e,client_id:m(this,A)};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:m(this,A),client_secret:m(this,P)};t&&(i.scope=t);try{let n=await this.post(e,i,this.authServerHeaders);return n.id_token&&!await this.validateIdToken(n.id_token)?{error:"access_denied",error_description:"Invalid ID token"}:n}catch(n){return d.logger.error(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:m(this,A),client_secret:m(this,P),device_code:e};try{const s=await this.post((i=this.oidcConfig)==null?void 0:i.token_endpoint,n,this.authServerHeaders);if(s.error)return s;if(s.id_token){const a=await this.getIdPayload(s.id_token,s.access_token);if(a.error)return a;s.id_payload=a.payload}return s}catch(s){return d.logger.error(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 ar(e)}}A=new WeakMap,P=new WeakMap;class dr{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(k.Configuration,"If specifying jwtPublic key, must also specify jwtKeyType")}async loadKeys(e){try{if(this.jwtSecretKey){if(!this.jwtKeyType)throw new g(k.Configuration,"Must specify jwtKeyType if setting jwtSecretKey");this.keys._default=await Xe(this.jwtSecretKey,this.jwtKeyType)}else if(this.jwtPublicKey){if(!this.jwtKeyType)throw new g(k.Configuration,"Must specify jwtKeyType if setting jwtPublicKey");const t=await Ye(this.jwtPublicKey,this.jwtKeyType);this.keys._default=t}else{if(this.oidcConfig||await this.loadConfig(),!this.oidcConfig)throw new g(k.Connection,"Load OIDC config before Jwks");await this.loadJwks(void 0,e)}}catch(t){throw d.logger.debug(h({err:t})),new g(k.Connection,"Couldn't load keys")}}async loadConfig(e){if(e){this.oidcConfig=e;return}if(!this.authServerBaseUrl)throw new g(k.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(k.Connection,"Couldn't get OIDC configuration");this.oidcConfig={...ye};try{const o=await t.json();for(const[i,n]of Object.entries(o))this.oidcConfig[i]=n}catch{throw new g(k.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(k.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(k.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(k.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(k.Connection,"Couldn't load keys")}}catch(i){throw d.logger.error(h({err:i})),new g(k.Connection,"Unrecognized response from OIDC jwks endpoint")}}}async tokenAuthorized(e,t,o){if(!this.keys||Object.keys(this.keys).length==0){const n=Ie(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=Ie(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 nr(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 Oe=30,ae=2,le=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(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-Oe;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-Oe<l){d.logger.debug(h({msg:"Refresh token has expired"}));return}let w=T=>new Promise(R=>setTimeout(R,T));d.logger.debug(h({msg:`Waiting ${l} before refreshing tokens`})),o=l,await w(l),await this.autoRefresh(e,n,t)}async autoRefresh(e,t,o){if(this.autoRefreshActive){let i,n=!1,s=0;for(;!n&&s<=ae;)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 w=g.asCrossauthError(l);o?o("Couldn't receive tokens",w):(d.logger.debug(h({err:l})),d.logger.error(h({msg:"Error receiving tokens",cerr:w})))}}else s<ae?(d.logger.error(h({msg:`Failed auto refreshing tokens. Retrying in ${le} seconds`})),await(w=>new Promise(T=>setTimeout(T,w)))(le*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<ae?(d.logger.error(h({msg:`Failed auto refreshing tokens. Retrying in ${ae} seconds`})),await(w=>new Promise(T=>setTimeout(T,w)))(le*1e3)):(d.logger.error(h({msg:"Failed auto refreshing tokens. Number of retries exceeded"})),o&&o(c.message,c)),s++}}}}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(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(w=>setTimeout(w,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 hr{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,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 lr{getCsrfToken(){return new Promise(e=>{})}}class Ue extends dr{async hash(e){const o=new TextEncoder().encode(e),i=await crypto.subtle.digest("SHA-256",o),n=Array.from(new Uint8Array(i));return btoa(n.reduce((s,a)=>s+String.fromCharCode(a),"")).replace(/\//g,"_").replace(/\+/g,"-").replace(/=+$/,"")}}class ur extends cr{constructor(t){t.tokenConsumer||(t.tokenConsumer=new Ue(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");I(this,D);I(this,K);I(this,j);I(this,W);I(this,F);I(this,L);I(this,$);f(this,"autoRefresher");f(this,"deviceCodePoller");f(this,"deviceAuthorizationUrl","device_authorization");I(this,Y);I(this,X);I(this,q);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&&E(this,L,t.client_id),t.client_secret&&E(this,$,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,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&&(E(this,D,i),E(this,W,s))}if(n){const s=this.getTokenPayload(n);s&&(E(this,K,n),E(this,F,s))}o?this.validateIdToken(o).then(s=>{E(this,j,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"}))}):y(this,D)&&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 y(this,j)}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,w]of o)l=="code"&&(i=w),l=="state"&&(n=w),l=="error"&&(s=w),l=="error_description"&&(a=w);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(y(this,q)&&n!=y(this,q))return{error:"access_denied",error_description:"Invalid state"};const c=await this.redirectEndpoint(i,this.scope,y(this,X),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 y(this,j)}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 y(this,j)&&(i=y(this,j).exp?y(this,j).exp:null),y(this,W)&&(n=y(this,W).exp?y(this,W).exp:null),y(this,F)&&(s=y(this,F).exp?y(this,F).exp:null),{id:i,access:n,refresh:s}}async jsonFetchWithToken(t,o,i){if(i=="access"){if(!y(this,D))throw new g(k.InvalidToken,"Cannot make fetch with access token - no access token defined");o.headers||(o.headers={}),o.headers.authorization="Bearer "+y(this,D)}else{if(o.body||(o.body={}),!y(this,K))throw new g(k.InvalidToken,"Cannot make fetch with refresh token - no refresh token defined");o.body.refresh_token=y(this,K),o.body.grant_type="refresh_token"}return y(this,L)&&(o.body||(o.body={}),o.body.client_id=y(this,L),y(this,$)&&(o.body.client_secret=y(this,$))),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&&(E(this,D,t.access_token),E(this,W,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&&(E(this,K,t.refresh_token),E(this,F,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);E(this,j,o),this.idTokenResponseType=="localStorage"?localStorage.setItem(this.idTokenName,t.id_token):this.idTokenResponseType=="sessionStorage"&&sessionStorage.setItem(this.idTokenName,t.id_token)}}async clientCredentialsFlow(t){const o=await super.clientCredentialsFlow(t);return await this.receiveTokens(o),o}async passwordFlow(t,o,i){const n=await super.passwordFlow(t,o,i);return await this.receiveTokens(n),n}async deviceCodeFlow(t){let o=this.authServerBaseUrl;return o.endsWith("/")||(o+="/"),o+=this.deviceAuthorizationUrl,await super.startDeviceCodeFlow(o,t)}async mfaOtpComplete(t,o){const i=await super.mfaOtpComplete(t,o);return await this.receiveTokens(i),i}async mfaOobComplete(t,o,i){const n=await super.mfaOobComplete(t,o,i);return await this.receiveTokens(n),n}async refreshTokenFlow(t){if(!t)if(y(this,K))t=y(this,K);else throw new g(k.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();E(this,Y,s.codeChallenge),E(this,X,s.codeVerifier),E(this,q,i)}const n=await super.startAuthorizationCodeFlow(i,t,y(this,Y),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}}return D=new WeakMap,K=new WeakMap,j=new WeakMap,W=new WeakMap,F=new WeakMap,L=new WeakMap,$=new WeakMap,Y=new WeakMap,X=new WeakMap,q=new WeakMap,p.CrossauthError=g,p.CrossauthLogger=d,p.OAuthAutoRefresher=ue,p.OAuthBffClient=hr,p.OAuthClient=ur,p.OAuthDeviceCodePoller=fe,p.OAuthTokenConsumer=Ue,p.OAuthTokenProvider=lr,p.j=h,Object.defineProperty(p,Symbol.toStringTag,{value:"Module"}),p}({});
|
package/dist/index.js
CHANGED
|
@@ -2085,7 +2085,12 @@ class Re {
|
|
|
2085
2085
|
try {
|
|
2086
2086
|
i = await c.json();
|
|
2087
2087
|
} catch {
|
|
2088
|
-
|
|
2088
|
+
try {
|
|
2089
|
+
d.logger.error(h({ msg: "/refresh returned a non-JSON response " + (i ? await i.text() : void 0) }));
|
|
2090
|
+
} catch {
|
|
2091
|
+
d.logger.error(h({ msg: "/refresh returned a with no body " }));
|
|
2092
|
+
}
|
|
2093
|
+
i = { ok: !1, error: "Unknown" };
|
|
2089
2094
|
}
|
|
2090
2095
|
if (i != null && i.ok) {
|
|
2091
2096
|
await this.scheduleAutoRefresh(e, o), n = !0;
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crossauth/frontend",
|
|
3
3
|
"private": false,
|
|
4
|
-
"version": "0.0.
|
|
4
|
+
"version": "0.0.41",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"main": "./dist/index.cjs",
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
},
|
|
23
23
|
"dependencies": {
|
|
24
24
|
"@esbuild-plugins/node-modules-polyfill": "^0.2.2",
|
|
25
|
-
"@crossauth/common": "^0.0.
|
|
25
|
+
"@crossauth/common": "^0.0.41"
|
|
26
26
|
},
|
|
27
27
|
"scripts": {
|
|
28
28
|
"dev": "vite",
|