@crossauth/common 1.1.7 → 1.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var ye=Object.defineProperty;var Q=e=>{throw TypeError(e)};var me=(e,t,r)=>t in e?ye(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var c=(e,t,r)=>me(e,typeof t!="symbol"?t+"":t,r),Z=(e,t,r)=>t.has(e)||Q("Cannot "+r);var g=(e,t,r)=>(Z(e,t,"read from private field"),r?r.call(e):t.get(e)),$=(e,t,r)=>t.has(e)?Q("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),D=(e,t,r,n)=>(Z(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class T{}c(T,"active","active"),c(T,"disabled","disabled"),c(T,"awaitingTwoFactorSetup","awaitingtwofactorsetup"),c(T,"awaitingTwoFactorSetupAndEmailVerification","awaitingtwofactorsetupandemailverification"),c(T,"awaitingEmailVerification","awaitingemailverification"),c(T,"passwordChangeNeeded","passwordchangeneeded"),c(T,"passwordResetNeeded","passwordresetneeded"),c(T,"factor2ResetNeeded","factor2resetneeded"),c(T,"passwordAndFactor2ResetNeeded","passwordandfactor2resetneeded");class A{}c(A,"session","s:"),c(A,"passwordResetToken","p:"),c(A,"emailVerificationToken","e:"),c(A,"apiKey","api:"),c(A,"authorizationCode","authz:"),c(A,"accessToken","access:"),c(A,"refreshToken","refresh:"),c(A,"mfaToken","omfa:"),c(A,"deviceCode","dc:"),c(A,"userCode","uc:");var y=(e=>(e[e.UserNotExist=0]="UserNotExist",e[e.PasswordInvalid=1]="PasswordInvalid",e[e.EmailNotExist=2]="EmailNotExist",e[e.UsernameOrPasswordInvalid=3]="UsernameOrPasswordInvalid",e[e.InvalidClientId=4]="InvalidClientId",e[e.ClientExists=5]="ClientExists",e[e.InvalidClientSecret=6]="InvalidClientSecret",e[e.InvalidClientIdOrSecret=7]="InvalidClientIdOrSecret",e[e.InvalidRedirectUri=8]="InvalidRedirectUri",e[e.InvalidOAuthFlow=9]="InvalidOAuthFlow",e[e.UserNotActive=10]="UserNotActive",e[e.EmailNotVerified=11]="EmailNotVerified",e[e.TwoFactorIncomplete=12]="TwoFactorIncomplete",e[e.Unauthorized=13]="Unauthorized",e[e.UnauthorizedClient=14]="UnauthorizedClient",e[e.InvalidScope=15]="InvalidScope",e[e.InsufficientScope=16]="InsufficientScope",e[e.InsufficientPriviledges=17]="InsufficientPriviledges",e[e.Forbidden=18]="Forbidden",e[e.InvalidKey=19]="InvalidKey",e[e.InvalidCsrf=20]="InvalidCsrf",e[e.InvalidSession=21]="InvalidSession",e[e.Expired=22]="Expired",e[e.Connection=23]="Connection",e[e.InvalidHash=24]="InvalidHash",e[e.UnsupportedAlgorithm=25]="UnsupportedAlgorithm",e[e.KeyExists=26]="KeyExists",e[e.PasswordChangeNeeded=27]="PasswordChangeNeeded",e[e.PasswordResetNeeded=28]="PasswordResetNeeded",e[e.Factor2ResetNeeded=29]="Factor2ResetNeeded",e[e.Configuration=30]="Configuration",e[e.InvalidEmail=31]="InvalidEmail",e[e.InvalidPhoneNumber=32]="InvalidPhoneNumber",e[e.InvalidUsername=33]="InvalidUsername",e[e.PasswordMatch=34]="PasswordMatch",e[e.InvalidToken=35]="InvalidToken",e[e.MfaRequired=36]="MfaRequired",e[e.PasswordFormat=37]="PasswordFormat",e[e.DataFormat=38]="DataFormat",e[e.FetchError=39]="FetchError",e[e.UserExists=40]="UserExists",e[e.FormEntry=41]="FormEntry",e[e.BadRequest=42]="BadRequest",e[e.AuthorizationPending=43]="AuthorizationPending",e[e.SlowDown=44]="SlowDown",e[e.ExpiredToken=45]="ExpiredToken",e[e.ConstraintViolation=46]="ConstraintViolation",e[e.NotImplemented=47]="NotImplemented",e[e.UnknownError=48]="UnknownError",e))(y||{});class p extends Error{constructor(r,n=void 0){let i,o=500;r==0?(i="User does not exist",o=401):r==1?(i="Password doesn't match",o=401):r==3?(i="Username or password incorrect",o=401):r==4?(i="Client id is invalid",o=401):r==5?(i="Client ID or name already exists",o=500):r==6?(i="Client secret is invalid",o=401):r==7?(i="Client id or secret is invalid",o=401):r==8?(i="Redirect Uri is not registered",o=401):r==9?(i="Invalid OAuth flow type",o=500):r==2?(i="No user exists with that email address",o=401):r==10?(i="Account is not active",o=403):r==33?(i="Username is not in an allowed format",o=400):r==31?(i="Email is not in an allowed format",o=400):r==32?(i="Phone number is not in an allowed format",o=400):r==11?(i="Email address has not been verified",o=403):r==12?(i="Two-factor setup is not complete",o=403):r==13?(i="Not authorized",o=401):r==14?(i="Client not authorized",o=401):r==15?(i="Invalid scope",o=403):r==16?(i="Insufficient scope",o=403):r==23?i="Connection failure":r==22?(i="Token has expired",o=401):r==24?i="Hash is not in a valid format":r==19?(i="Key is invalid",o=401):r==18?(i="You do not have permission to access this resource",o=403):r==17?(i="You do not have the right privileges to access this resource",o=401):r==20?(i="CSRF token is invalid",o=401):r==21?(i="Session cookie is invalid",o=401):r==25?i="Algorithm not supported":r==26?i="Attempt to create a key that already exists":r==27?(i="User must change password",o=403):r==28?(i="User must reset password",o=403):r==29?(i="User must reset 2FA",o=403):r==30?i="There was an error in the configuration":r==34?(i="Passwords do not match",o=401):r==35?(i="Token is not valid",o=401):r==36?(i="MFA is required",o=401):r==37?(i="Password format was incorrect",o=401):r==40?(i="User already exists",o=400):r==42?(i="The request is invalid",o=400):r==38?(i="Session data has unexpected format",o=500):r==39?(i="Couldn't execute a fetch",o=500):r==43?(i="Waiting for authorization",o=200):r==44?(i="Slow polling down by 5 seconds",o=200):r==45?(i="Token has expired",o=401):r==46?(i="Database update/insert caused a constraint violation",o=500):r==47?(i="This method has not been implemented",o=500):(i="Unknown error",o=500),n!=null&&!Array.isArray(n)?i=n:Array.isArray(n)&&(i=n.join(". "));super(i);c(this,"isCrossauthError",!0);c(this,"httpStatus");c(this,"code");c(this,"codeName");c(this,"messages");this.code=r,this.codeName=y[r],this.httpStatus=o,this.name="CrossauthError",Array.isArray(n)?this.messages=n:this.messages=[i],Object.setPrototypeOf(this,p.prototype)}static fromOAuthError(r,n){let i;switch(r){case"invalid_request":i=42;break;case"unauthorized_client":i=14;break;case"access_denied":i=13;break;case"unsupported_response_type":i=42;break;case"invalid_scope":i=15;break;case"server_error":i=48;break;case"temporarily_unavailable":i=23;break;case"invalid_token":i=35;break;case"expired_token":i=45;break;case"insufficient_scope":i=35;break;case"mfa_required":i=36;break;case"authorization_pending":i=43;break;case"slow_down":i=44;break;default:i=48}return new p(i,n)}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(r,n){if(r instanceof Error)return"isCrossauthError"in r?r:new p(48,r.message);if("errorCode"in r){let o=48;try{o=Number(r.errorCode)??48}catch{}let s=n??y[o];return"errorMessage"in r?s=r.errorMessage:"message"in r&&(s=r.message),new p(o,s)}let i=n??y[48];return"message"in r&&(i=r.message),new p(48,i)}}function we(e){return typeof e=="number"&&(e=""+e),e in B?B[e]:B[500]}const B={200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Unused",307:"Temporary Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Required",413:"Request Entry Too Large",414:"Request-URI Too Long",415:"Unsupported Media Type",416:"Requested Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",429:"Too Many Requests",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported"},w=class w{constructor(t){c(this,"level");if(t)this.level=t;else if(typeof process<"u"&&"CROSSAUTH_LOG_LEVEL"in process.env){const r=(process.env.CROSSAUTH_LOG_LEVEL??"ERROR").toUpperCase();w.levelName.includes(r)?this.level=w.levelName.indexOf(r):this.level=w.Error}else this.level=w.Error}static get logger(){return globalThis.crossauthLogger}setLevel(t){this.level=t}log(t,r){t<=this.level&&(typeof r=="string"?console.log("Crossauth "+w.levelName[t]+" "+new Date().toISOString(),r):console.log(JSON.stringify({level:w.levelName[t],time:new Date().toISOString(),...r})))}error(t){this.log(w.Error,t)}warn(t){this.log(w.Warn,t)}info(t){this.log(w.Info,t)}debug(t){this.log(w.Debug,t)}static setLogger(t,r){globalThis.crossauthLogger=t,globalThis.crossauthLoggerAcceptsJson=r}};c(w,"None",0),c(w,"Error",1),c(w,"Warn",2),c(w,"Info",3),c(w,"Debug",4),c(w,"levelName",["NONE","ERROR","WARN","INFO","DEBUG"]);let l=w;function u(e){let t;typeof e=="object"&&"err"in e&&typeof e.err=="object"&&(t=e.err.stack);try{typeof e=="object"&&"err"in e&&typeof e.err=="object"&&e.err&&"message"in e.err&&!("msg"in e)&&(e.msg=e.err.message)}catch{}try{typeof e=="object"&&"err"in e&&typeof e.err=="object"&&(e.err={...e.err,stack:t})}catch{}try{typeof e=="object"&&"err"in e&&!("msg"in e)&&(e.msg=e.msg="An unknown error occurred")}catch{}try{typeof e=="object"&&"cerr"in e&&"isCrossauthError"in e.cerr&&e.cerr&&(e.errorCode=e.cerr.code,e.errorCodeName=e.cerr.codeName,e.httpStatus=e.cerr.httpStatus,"msg"in e||(e.msg=e.cerr.message),delete e.cerr)}catch{}return typeof e=="string"||globalThis.crossauthLoggerAcceptsJson?e:JSON.stringify(e)}globalThis.crossauthLogger=new l;globalThis.crossauthLoggerAcceptsJson=!0;const X={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},q=crypto,ne=e=>e instanceof CryptoKey,M=new TextEncoder,H=new TextDecoder;function _e(...e){const t=e.reduce((i,{length:o})=>i+o,0),r=new Uint8Array(t);let n=0;for(const i of e)r.set(i,n),n+=i.length;return r}const ve=e=>{const t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r},O=e=>{let t=e;t instanceof Uint8Array&&(t=H.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return ve(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class C extends Error{constructor(t,r){var n;super(t,r),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(n=Error.captureStackTrace)==null||n.call(Error,this,this.constructor)}}C.code="ERR_JOSE_GENERIC";class Se extends C{constructor(t,r,n="unspecified",i="unspecified"){super(t,{cause:{claim:n,reason:i,payload:r}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=n,this.reason=i,this.payload=r}}Se.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class Ce extends C{constructor(t,r,n="unspecified",i="unspecified"){super(t,{cause:{claim:n,reason:i,payload:r}}),this.code="ERR_JWT_EXPIRED",this.claim=n,this.reason=i,this.payload=r}}Ce.code="ERR_JWT_EXPIRED";class be extends C{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}be.code="ERR_JOSE_ALG_NOT_ALLOWED";class I extends C{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}I.code="ERR_JOSE_NOT_SUPPORTED";class Ae extends C{constructor(t="decryption operation failed",r){super(t,r),this.code="ERR_JWE_DECRYPTION_FAILED"}}Ae.code="ERR_JWE_DECRYPTION_FAILED";class Ie extends C{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}Ie.code="ERR_JWE_INVALID";class _ extends C{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}_.code="ERR_JWS_INVALID";class k extends C{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}k.code="ERR_JWT_INVALID";class Ee extends C{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}Ee.code="ERR_JWK_INVALID";class Te extends C{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}Te.code="ERR_JWKS_INVALID";class Re extends C{constructor(t="no applicable key found in the JSON Web Key Set",r){super(t,r),this.code="ERR_JWKS_NO_MATCHING_KEY"}}Re.code="ERR_JWKS_NO_MATCHING_KEY";class Pe extends C{constructor(t="multiple matching keys found in the JSON Web Key Set",r){super(t,r),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}Pe.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class ke extends C{constructor(t="request timed out",r){super(t,r),this.code="ERR_JWKS_TIMEOUT"}}ke.code="ERR_JWKS_TIMEOUT";class oe extends C{constructor(t="signature verification failed",r){super(t,r),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}oe.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function E(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function z(e,t){return e.name===t}function V(e){return parseInt(e.name.slice(4),10)}function Ke(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Oe(e,t){if(t.length&&!t.some(r=>e.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(t.length>2){const n=t.pop();r+=`one of ${t.join(", ")}, or ${n}.`}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}function Ne(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!z(e.algorithm,"HMAC"))throw E("HMAC");const n=parseInt(t.slice(2),10);if(V(e.algorithm.hash)!==n)throw E(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!z(e.algorithm,"RSASSA-PKCS1-v1_5"))throw E("RSASSA-PKCS1-v1_5");const n=parseInt(t.slice(2),10);if(V(e.algorithm.hash)!==n)throw E(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!z(e.algorithm,"RSA-PSS"))throw E("RSA-PSS");const n=parseInt(t.slice(2),10);if(V(e.algorithm.hash)!==n)throw E(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw E("Ed25519 or Ed448");break}case"Ed25519":{if(!z(e.algorithm,"Ed25519"))throw E("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!z(e.algorithm,"ECDSA"))throw E("ECDSA");const n=Ke(t);if(e.algorithm.namedCurve!==n)throw E(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Oe(e,r)}function se(e,t,...r){var n;if(r=r.filter(Boolean),r.length>2){const i=r.pop();e+=`one of type ${r.join(", ")}, or ${i}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&(n=t.constructor)!=null&&n.name&&(e+=` Received an instance of ${t.constructor.name}`),e}const ee=(e,...t)=>se("Key must be ",e,...t);function ae(e,t,...r){return se(`Key for the ${e} algorithm must be `,t,...r)}const ce=e=>ne(e)?!0:(e==null?void 0:e[Symbol.toStringTag])==="KeyObject",L=["CryptoKey"],We=(...e)=>{const t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(const n of t){const i=Object.keys(n);if(!r||r.size===0){r=new Set(i);continue}for(const o of i){if(r.has(o))return!1;r.add(o)}}return!0};function Je(e){return typeof e=="object"&&e!==null}function U(e){if(!Je(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}const Ue=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};function x(e){return U(e)&&typeof e.kty=="string"}function xe(e){return e.kty!=="oct"&&typeof e.d=="string"}function De(e){return e.kty!=="oct"&&typeof e.d>"u"}function ze(e){return x(e)&&e.kty==="oct"&&typeof e.k=="string"}function He(e){let t,r;switch(e.kty){case"RSA":{switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new I('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new I('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(e.alg){case"Ed25519":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"EdDSA":t={name:e.crv},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new I('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new I('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}const de=async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:r}=He(e),n=[t,e.ext??!1,e.key_ops??r],i={...e};return delete i.alg,delete i.use,q.subtle.importKey("jwk",i,...n)},le=e=>O(e);let N,W;const ue=e=>(e==null?void 0:e[Symbol.toStringTag])==="KeyObject",F=async(e,t,r,n,i=!1)=>{let o=e.get(t);if(o!=null&&o[n])return o[n];const s=await de({...r,alg:n});return i&&Object.freeze(t),o?o[n]=s:e.set(t,{[n]:s}),s},Me=(e,t)=>{if(ue(e)){let r=e.export({format:"jwk"});return delete r.d,delete r.dp,delete r.dq,delete r.p,delete r.q,delete r.qi,r.k?le(r.k):(W||(W=new WeakMap),F(W,e,r,t))}return x(e)?e.k?O(e.k):(W||(W=new WeakMap),F(W,e,e,t,!0)):e},Le=(e,t)=>{if(ue(e)){let r=e.export({format:"jwk"});return r.k?le(r.k):(N||(N=new WeakMap),F(N,e,r,t))}return x(e)?e.k?O(e.k):(N||(N=new WeakMap),F(N,e,e,t,!0)):e},Fe={normalizePublicKey:Me,normalizePrivateKey:Le},K=(e,t,r=0)=>{r===0&&(t.unshift(t.length),t.unshift(6));const n=e.indexOf(t[0],r);if(n===-1)return!1;const i=e.subarray(n,n+t.length);return i.length!==t.length?!1:i.every((o,s)=>o===t[s])||K(e,t,n+1)},te=e=>{switch(!0){case K(e,[42,134,72,206,61,3,1,7]):return"P-256";case K(e,[43,129,4,0,34]):return"P-384";case K(e,[43,129,4,0,35]):return"P-521";case K(e,[43,101,110]):return"X25519";case K(e,[43,101,111]):return"X448";case K(e,[43,101,112]):return"Ed25519";case K(e,[43,101,113]):return"Ed448";default:throw new I("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},he=async(e,t,r,n,i)=>{let o,s;const a=new Uint8Array(atob(r.replace(e,"")).split("").map(f=>f.charCodeAt(0))),d=t==="spki";switch(n){case"PS256":case"PS384":case"PS512":o={name:"RSA-PSS",hash:`SHA-${n.slice(-3)}`},s=d?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":o={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.slice(-3)}`},s=d?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":o={name:"RSA-OAEP",hash:`SHA-${parseInt(n.slice(-3),10)||1}`},s=d?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":o={name:"ECDSA",namedCurve:"P-256"},s=d?["verify"]:["sign"];break;case"ES384":o={name:"ECDSA",namedCurve:"P-384"},s=d?["verify"]:["sign"];break;case"ES512":o={name:"ECDSA",namedCurve:"P-521"},s=d?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{const f=te(a);o=f.startsWith("P-")?{name:"ECDH",namedCurve:f}:{name:f},s=d?[]:["deriveBits"];break}case"Ed25519":o={name:"Ed25519"},s=d?["verify"]:["sign"];break;case"EdDSA":o={name:te(a)},s=d?["verify"]:["sign"];break;default:throw new I('Invalid or unsupported "alg" (Algorithm) value')}return q.subtle.importKey(t,a,o,!1,s)},qe=(e,t,r)=>he(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t),$e=(e,t,r)=>he(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",e,t);async function Be(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return $e(e,t)}async function Ve(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return qe(e,t)}async function j(e,t){if(!U(e))throw new TypeError("JWK must be an object");switch(t||(t=e.alg),e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return O(e.k);case"RSA":if("oth"in e&&e.oth!==void 0)throw new I('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return de({...e,alg:t});default:throw new I('Unsupported "kty" (Key Type) Parameter value')}}const J=e=>e==null?void 0:e[Symbol.toStringTag],G=(e,t,r)=>{var n,i;if(t.use!==void 0&&t.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(t.key_ops!==void 0&&((i=(n=t.key_ops).includes)==null?void 0:i.call(n,r))!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},je=(e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&x(t)){if(ze(t)&&G(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!ce(t))throw new TypeError(ae(e,t,...L,"Uint8Array",n?"JSON Web Key":null));if(t.type!=="secret")throw new TypeError(`${J(t)} instances for symmetric algorithms must be of type "secret"`)}},Ge=(e,t,r,n)=>{if(n&&x(t))switch(r){case"sign":if(xe(t)&&G(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(De(t)&&G(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!ce(t))throw new TypeError(ae(e,t,...L,n?"JSON Web Key":null));if(t.type==="secret")throw new TypeError(`${J(t)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${J(t)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${J(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${J(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${J(t)} instances for asymmetric algorithm encryption must be of type "public"`)};function fe(e,t,r,n){t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?je(t,r,n,e):Ge(t,r,n,e)}fe.bind(void 0,!1);const re=fe.bind(void 0,!0);function Ye(e,t,r,n,i){if(i.crit!==void 0&&(n==null?void 0:n.crit)===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(s=>typeof s!="string"||s.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let o;o=t;for(const s of n.crit){if(!o.has(s))throw new I(`Extension Header Parameter "${s}" is not recognized`);if(i[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(o.get(s)&&n[s]===void 0)throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return new Set(n.crit)}function Xe(e,t){const r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:t.name};default:throw new I(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function Qe(e,t,r){if(t=await Fe.normalizePublicKey(t,e),ne(t))return Ne(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(ee(t,...L));return q.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(ee(t,...L,"Uint8Array","JSON Web Key"))}const Ze=async(e,t,r,n)=>{const i=await Qe(e,t,"verify");Ue(e,i);const o=Xe(e,i.algorithm);try{return await q.subtle.verify(o,i,r,n)}catch{return!1}};async function et(e,t,r){if(!U(e))throw new _("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new _('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new _("JWS Protected Header incorrect type");if(e.payload===void 0)throw new _("JWS Payload missing");if(typeof e.signature!="string")throw new _("JWS Signature missing or incorrect type");if(e.header!==void 0&&!U(e.header))throw new _("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{const ge=O(e.protected);n=JSON.parse(H.decode(ge))}catch{throw new _("JWS Protected Header is invalid")}if(!We(n,e.header))throw new _("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const i={...n,...e.header},o=Ye(_,new Map([["b64",!0]]),r==null?void 0:r.crit,n,i);let s=!0;if(o.has("b64")&&(s=n.b64,typeof s!="boolean"))throw new _('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=i;if(typeof a!="string"||!a)throw new _('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(s){if(typeof e.payload!="string")throw new _("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new _("JWS Payload must be a string or an Uint8Array instance");let d=!1;typeof t=="function"?(t=await t(n,e),d=!0,re(a,t,"verify"),x(t)&&(t=await j(t,a))):re(a,t,"verify");const f=_e(M.encode(e.protected??""),M.encode("."),typeof e.payload=="string"?M.encode(e.payload):e.payload);let m;try{m=O(e.signature)}catch{throw new _("Failed to base64url decode the signature")}if(!await Ze(a,t,m,f))throw new oe;let b;if(s)try{b=O(e.payload)}catch{throw new _("Failed to base64url decode the payload")}else typeof e.payload=="string"?b=M.encode(e.payload):b=e.payload;const P={payload:b};return e.protected!==void 0&&(P.protectedHeader=n),e.header!==void 0&&(P.unprotectedHeader=e.header),d?{...P,key:t}:P}async function tt(e,t,r){if(e instanceof Uint8Array&&(e=H.decode(e)),typeof e!="string")throw new _("Compact JWS must be a string or Uint8Array");const{0:n,1:i,2:o,length:s}=e.split(".");if(s!==3)throw new _("Invalid Compact JWS");const a=await et({payload:i,protected:n,signature:o},t,r),d={payload:a.payload,protectedHeader:a.protectedHeader};return typeof t=="function"?{...d,key:a.key}:d}const pe=O;function ie(e){let t;if(typeof e=="string"){const r=e.split(".");(r.length===3||r.length===5)&&([t]=r)}else if(typeof e=="object"&&e)if("protected"in e)t=e.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof t!="string"||!t)throw new Error;const r=JSON.parse(H.decode(pe(t)));if(!U(r))throw new Error;return r}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}function rt(e){if(typeof e!="string")throw new k("JWTs must use Compact JWS serialization, JWT must be a string");const{1:t,length:r}=e.split(".");if(r===5)throw new k("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new k("Invalid JWT");if(!t)throw new k("JWTs must contain a payload");let n;try{n=pe(t)}catch{throw new k("Failed to base64url decode the payload")}let i;try{i=JSON.parse(H.decode(n))}catch{throw new k("Failed to parse the decoded payload as JSON")}if(!U(i))throw new k("Invalid JWT Claims Set");return i}const h=class h{static flowNames(t){let r={};return t.forEach(n=>{n in h.flowName&&(r[n]=h.flowName[n])}),r}static isValidFlow(t){return h.allFlows().includes(t)}static areAllValidFlows(t){let r=!0;return t.forEach(n=>{h.isValidFlow(n)||(r=!1)}),r}static allFlows(){return[h.AuthorizationCode,h.AuthorizationCodeWithPKCE,h.ClientCredentials,h.RefreshToken,h.DeviceCode,h.Password,h.PasswordMfa,h.OidcAuthorizationCode]}static grantType(t){switch(t){case h.AuthorizationCode:case h.AuthorizationCodeWithPKCE:case h.OidcAuthorizationCode:return["authorization_code"];case h.ClientCredentials:return["client_credentials"];case h.RefreshToken:return["refresh_token"];case h.Password:return["password"];case h.PasswordMfa:return["http://auth0.com/oauth/grant-type/mfa-otp","http://auth0.com/oauth/grant-type/mfa-oob"];case h.DeviceCode:return["urn:ietf:params:oauth:grant-type:device_code"]}}};c(h,"All","all"),c(h,"AuthorizationCode","authorizationCode"),c(h,"AuthorizationCodeWithPKCE","authorizationCodeWithPKCE"),c(h,"ClientCredentials","clientCredentials"),c(h,"RefreshToken","refreshToken"),c(h,"DeviceCode","deviceCode"),c(h,"Password","password"),c(h,"PasswordMfa","passwordMfa"),c(h,"OidcAuthorizationCode","oidcAuthorizationCode"),c(h,"flowName",{[h.AuthorizationCode]:"Authorization Code",[h.AuthorizationCodeWithPKCE]:"Authorization Code with PKCE",[h.ClientCredentials]:"Client Credentials",[h.RefreshToken]:"Refresh Token",[h.DeviceCode]:"Device Code",[h.Password]:"Password",[h.PasswordMfa]:"Password MFA",[h.OidcAuthorizationCode]:"OIDC Authorization Code"});let Y=h;var v,S;class it{constructor({authServerBaseUrl:t,client_id:r,client_secret:n,redirect_uri:i,codeChallengeMethod:o,stateLength:s,verifierLength:a,tokenConsumer:d,authServerCredentials:f,authServerMode:m,authServerHeaders:R}){c(this,"authServerBaseUrl","");$(this,v);$(this,S);c(this,"codeChallengeMethod","S256");c(this,"verifierLength",32);c(this,"redirect_uri");c(this,"stateLength",32);c(this,"authzCode","");c(this,"oidcConfig");c(this,"tokenConsumer");c(this,"authServerHeaders",{});c(this,"authServerMode");c(this,"authServerCredentials");c(this,"oauthPostType","json");c(this,"oauthLogFetch",!1);c(this,"oauthUseUserInfoEndpoint",!1);c(this,"oauthAuthorizeRedirect");this.tokenConsumer=d,this.authServerBaseUrl=t,a&&(this.verifierLength=a),s&&(this.stateLength=s),r&&D(this,v,r),n&&D(this,S,n),i&&(this.redirect_uri=i),o&&(this.codeChallengeMethod=o),this.authServerBaseUrl=t,f&&(this.authServerCredentials=f),m&&(this.authServerMode=m),R&&(this.authServerHeaders=R)}set client_id(t){D(this,v,t)}set client_secret(t){D(this,S,t)}async loadConfig(t){if(t){l.logger.debug(u({msg:"Reading OIDC config locally"})),this.oidcConfig=t;return}let r;try{const n=new URL(this.authServerBaseUrl+"/.well-known/openid-configuration");l.logger.debug(u({msg:`Fetching OIDC config from ${n}`}));let i={headers:this.authServerHeaders};this.authServerMode&&(i.mode=this.authServerMode),this.authServerCredentials&&(i.credentials=this.authServerCredentials),r=await fetch(n,i)}catch(n){l.logger.error(u({err:n}))}if(!r||!r.ok)throw new p(y.Connection,"Couldn't get OIDC configuration from URL"+this.authServerBaseUrl+"/.well-known/openid-configuration");this.oidcConfig={...X};try{const n=await r.json();for(const[i,o]of Object.entries(n))this.oidcConfig[i]=o}catch{throw new p(y.Connection,"Unrecognized response from OIDC configuration endpoint")}}getOidcConfig(){return this.oidcConfig}async startAuthorizationCodeFlow(t,{scope:r,codeChallenge:n,pkce:i=!1,upstream:o}){var d,f,m;if(l.logger.debug(u({msg:"Starting authorization code flow, scope "+r})),this.oidcConfig||await this.loadConfig(),!((d=this.oidcConfig)!=null&&d.response_types_supported.includes("code"))||!((f=this.oidcConfig)!=null&&f.response_modes_supported.includes("query")))return{error:"invalid_request",error_description:"Server does not support authorization code flow"};if(!((m=this.oidcConfig)!=null&&m.authorization_endpoint))return{error:"server_error",error_description:"Cannot get authorize endpoint"};if(!g(this,v))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 s=this.oidcConfig.authorization_endpoint;this.oauthAuthorizeRedirect&&(s=this.oauthAuthorizeRedirect);let a=s+"?response_type=code&client_id="+encodeURIComponent(g(this,v))+"&state="+encodeURIComponent(t)+"&redirect_uri="+encodeURIComponent(this.redirect_uri);return r&&(a+="&scope="+encodeURIComponent(r)),i&&n&&(a+="&code_challenge="+n),{url:a}}async codeChallengeAndVerifier(){const t=this.randomValue(this.verifierLength);return{codeChallenge:this.codeChallengeMethod=="plain"?t:await this.sha256(t),codeVerifier:t}}async getIdPayload(t,r){let n,i;try{let o;if(o=await this.validateIdToken(t),!o)return n="access_denied",i="Invalid ID token received",{error:n,error_description:i};if(r&&this.oauthUseUserInfoEndpoint){const s=await this.userInfoEndpoint(r);if(s.error)return n=s.error,i="Failed getting user info: "+(s.error_description??"unknown error"),{error:n,error_description:i};o={...o,...s}}return{payload:o}}catch(o){const s=p.asCrossauthError(o);return l.logger.debug(u({err:s})),l.logger.error(u({msg:"Couldn't get user info",cerr:s})),n=s.oauthErrorCode,i="Couldn't get user info: "+s.message,{error:n,error_description:i}}}async getAccessPayload(t,r){let n,i;try{let o;return o=await this.validateAccessToken(t,r),o?{payload:o}:(n="access_denied",i="Invalid access token received",{error:n,error_description:i})}catch(o){const s=p.asCrossauthError(o);return l.logger.debug(u({err:s})),l.logger.error(u({msg:"Couldn't get user info",cerr:s})),n=s.oauthErrorCode,i="Couldn't get user info: "+s.message,{error:n,error_description:i}}}async redirectEndpoint({code:t,scope:r,codeVerifier:n,error:i,errorDescription:o}){var m,R;if(this.oidcConfig||await this.loadConfig(),i||!t)return i||(i="server_error"),o||(o="Unknown error"),{error:i,error_description:o};if(this.authzCode=t,!((m=this.oidcConfig)!=null&&m.grant_types_supported.includes("authorization_code")))return{error:"invalid_request",error_description:"Server does not support authorization code grant"};if(!((R=this.oidcConfig)!=null&&R.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const s=this.oidcConfig.token_endpoint;let a,d;a="authorization_code",d=g(this,S);let f={grant_type:a,client_id:g(this,v),code:this.authzCode,redirect_uri:this.redirect_uri};r&&(f.scope=r),d&&(f.client_secret=d),n&&(f.code_verifier=n);try{let b=await this.post(s,f,this.authServerHeaders);if(b.id_token){const P=await this.getIdPayload(b.id_token,b.access_token);if(P.error)return P;b.id_payload=P.payload}return b}catch(b){return l.logger.error(u({err:b})),{error:"server_error",error_description:"Unable to get access token from server"}}}async clientCredentialsFlow(t){var i,o;if(l.logger.debug(u({msg:"Starting client credentials flow"})),this.oidcConfig||await this.loadConfig(),!((i=this.oidcConfig)!=null&&i.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(!g(this,v))return{error:"invalid_request",error_description:"Cannot make client credentials flow without client id"};const r=this.oidcConfig.token_endpoint;let n={grant_type:"client_credentials",client_id:g(this,v),client_secret:g(this,S)};t&&(n.scope=t);try{let s=await this.post(r,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 l.logger.error(u({err:s})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async passwordFlow(t,r,n){var s,a;if(l.logger.debug(u({msg:"Starting password flow"})),this.oidcConfig||await this.loadConfig(),!((s=this.oidcConfig)!=null&&s.grant_types_supported.includes("password")))return{error:"invalid_request",error_description:"Server does not support password grant"};if(!((a=this.oidcConfig)!=null&&a.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const i=this.oidcConfig.token_endpoint;let o={grant_type:"password",client_id:g(this,v),client_secret:g(this,S),username:t,password:r};n&&(o.scope=n);try{let d=await this.post(i,o,this.authServerHeaders);if(d.id_token){const f=await this.getIdPayload(d.id_token,d.access_token);if(f.error)return f;d.id_payload=f.payload}return d}catch(d){return l.logger.error(u({err:d})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async mfaAuthenticators(t){var o,s,a;if(l.logger.debug(u({msg:"Getting valid MFA authenticators"})),this.oidcConfig||await this.loadConfig(),!((o=this.oidcConfig)!=null&&o.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp"))&&((s=this.oidcConfig)!=null&&s.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-oob")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((a=this.oidcConfig)!=null&&a.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const r=this.oidcConfig.issuer+(this.oidcConfig.issuer.endsWith("/")?"":"/")+"mfa/authenticators",n=await this.get(r,{authorization:"Bearer "+t,...this.authServerHeaders});if(!Array.isArray(n))return{error:"server_error",error_description:"Expected array of authenticators in mfa/authenticators response"};let i=[];for(let d=0;d<n.length;++d){const f=n[d];if(!f.id||!f.authenticator_type||!f.active)return{error:"server_error",error_description:"Invalid mfa/authenticators response"};i.push({id:f.id,authenticator_type:f.authenticator_type,active:f.active,name:f.name,oob_channel:f.oob_channel})}return{authenticators:i}}async mfaOtpRequest(t,r){var o,s;if(l.logger.debug(u({msg:"Making MFA OTB request"})),this.oidcConfig||await this.loadConfig(),!((o=this.oidcConfig)!=null&&o.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((s=this.oidcConfig)!=null&&s.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const n=this.oidcConfig.issuer+(this.oidcConfig.issuer.endsWith("/")?"":"/")+"mfa/challenge",i=await this.post(n,{client_id:g(this,v),client_secret:g(this,S),challenge_type:"otp",mfa_token:t,authenticator_id:r},this.authServerHeaders);return i.challenge_type!="otp"?{error:i.error??"server_error",error_description:i.error_description??"Invalid OTP challenge response"}:i}async mfaOtpComplete(t,r,n){var s,a;if(l.logger.debug(u({msg:"Completing MFA OTP request"})),this.oidcConfig||await this.loadConfig(),!((s=this.oidcConfig)!=null&&s.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((a=this.oidcConfig)!=null&&a.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const i=this.oidcConfig.token_endpoint,o=await this.post(i,{grant_type:"http://auth0.com/oauth/grant-type/mfa-otp",client_id:g(this,v),client_secret:g(this,S),challenge_type:"otp",mfa_token:t,otp:r,scope:n},this.authServerHeaders);if(o.id_token){const d=await this.getIdPayload(o.id_token,o.access_token);if(d.error)return d;o.id_payload=d.payload}return{id_token:o.id_token,access_token:o.access_token,refresh_token:o.refresh_token,expires_in:Number(o.expires_in),scope:o.scope,token_type:o.token_type,error:o.error,error_description:o.error_description}}async mfaOobRequest(t,r){var o,s;if(l.logger.debug(u({msg:"Making MFA OOB request"})),this.oidcConfig||await this.loadConfig(),!((o=this.oidcConfig)!=null&&o.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((s=this.oidcConfig)!=null&&s.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const n=this.oidcConfig.issuer+(this.oidcConfig.issuer.endsWith("/")?"":"/")+"mfa/challenge",i=await this.post(n,{client_id:g(this,v),client_secret:g(this,S),challenge_type:"oob",mfa_token:t,authenticator_id:r},this.authServerHeaders);return i.challenge_type!="oob"||!i.oob_code||!i.binding_method?{error:i.error??"server_error",error_description:i.error_description??"Invalid OOB challenge response"}:{challenge_type:i.challenge_type,oob_code:i.oob_code,binding_method:i.binding_method,error:i.error,error_description:i.error_description}}async mfaOobComplete(t,r,n,i){var a,d;if(l.logger.debug(u({msg:"Completing MFA OOB request"})),this.oidcConfig||await this.loadConfig(),!((a=this.oidcConfig)!=null&&a.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(!((d=this.oidcConfig)!=null&&d.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const o=this.oidcConfig.token_endpoint,s=await this.post(o,{grant_type:"http://auth0.com/oauth/grant-type/mfa-oob",client_id:g(this,v),client_secret:g(this,S),challenge_type:"otp",mfa_token:t,oob_code:r,binding_code:n,scope:i},this.authServerHeaders);if(s.error)return{error:s.error,error_description:s.error_description};if(s.id_token){const f=await this.getIdPayload(s.id_token,s.access_token);if(f.error)return f;s.id_payload=f.payload}return{id_token:s.id_token,access_token:s.access_token,refresh_token:s.refresh_token,expires_in:"expires_in"in s?Number(s.expires_in):void 0,scope:s.scope,token_type:s.token_type}}async refreshTokenFlow(t){var o,s;if(l.logger.debug(u({msg:"Starting refresh token flow"})),this.oidcConfig||await this.loadConfig(),!((o=this.oidcConfig)!=null&&o.grant_types_supported.includes("refresh_token")))return{error:"invalid_request",error_description:"Server does not support refresh_token grant"};if(!((s=this.oidcConfig)!=null&&s.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const r=this.oidcConfig.token_endpoint;let n;n=g(this,S);let i={grant_type:"refresh_token",refresh_token:t,client_id:g(this,v)};n&&(i.client_secret=n);try{let a=await this.post(r,i,this.authServerHeaders);if(a.id_token){const d=await this.getIdPayload(a.id_token,a.access_token);if(d!=null&&d.error)return d;a.id_payload=d==null?void 0:d.payload}return a}catch(a){return l.logger.error(u({err:a})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async startDeviceCodeFlow(t,r){var i;if(l.logger.debug(u({msg:"Starting device code flow"})),this.oidcConfig||await this.loadConfig(),!((i=this.oidcConfig)!=null&&i.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 n={grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:g(this,v),client_secret:g(this,S)};r&&(n.scope=r);try{let o=await this.post(t,n,this.authServerHeaders);return o.id_token&&!await this.validateIdToken(o.id_token)?{error:"access_denied",error_description:"Invalid ID token"}:o}catch(o){return l.logger.error(u({err:o})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async pollDeviceCodeFlow(t){var n,i,o;if(l.logger.debug(u({msg:"Starting device code flow"})),this.oidcConfig||await this.loadConfig(),!((n=this.oidcConfig)!=null&&n.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(!((i=this.oidcConfig)!=null&&i.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};let r={grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:g(this,v),client_secret:g(this,S),device_code:t};try{const s=await this.post((o=this.oidcConfig)==null?void 0:o.token_endpoint,r,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 l.logger.error(u({err:s})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async userInfoEndpoint(t){var i;if(!((i=this.oidcConfig)!=null&&i.userinfo_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const r=this.oidcConfig.userinfo_endpoint;return await this.post(r,{},{authorization:"Bearer "+t})}async post(t,r,n={},i){l.logger.debug(u({msg:"Fetch POST",url:t,params:Object.keys(r)}));let o={};this.authServerCredentials&&(o.credentials=this.authServerCredentials),this.authServerMode&&(o.mode=this.authServerMode);let s="",a="";if(this.oauthPostType=="json")s=JSON.stringify(r),a="application/json";else{s="";for(let m in r)s!=""&&(s+="&"),s+=encodeURIComponent(m)+"="+encodeURIComponent(r[m]);a="application/x-www-form-urlencoded"}this.oauthLogFetch&&l.logger.debug(u({msg:"OAuth fetch",method:"POST",url:t,body:s}));let d={};i&&(d=i);const f=await fetch(t,{method:"POST",...o,headers:{Accept:"application/json","Content-Type":a,...n},...d,body:s});try{const m=await f.clone().json();return this.oauthLogFetch&&l.logger.debug(u({msg:"OAuth fetch response",body:JSON.stringify(m)})),await f.json(),m}catch(m){let R=p.asCrossauthError(m);throw s=await f.text(),l.logger.debug(u({msg:"Response is not JSON",response:s})),R}}async get(t,r={}){l.logger.debug(u({msg:"Fetch GET",url:t}));let n={};this.authServerCredentials&&(n.credentials=this.authServerCredentials),this.authServerMode&&(n.mode=this.authServerMode),this.oauthLogFetch&&l.logger.debug(u({msg:"OAuth fetch",method:"GET",url:t}));const o=await(await fetch(t,{method:"GET",...n,headers:{Accept:"application/json",...r}})).json();return this.oauthLogFetch&&l.logger.debug(u({msg:"OAuth fetch response",body:JSON.stringify(o)})),o}async validateIdToken(t){try{return await this.tokenConsumer.tokenAuthorized(t,"id")}catch(r){l.logger.debug(u({err:r})),l.logger.error(u({msg:"Id token invalid",cerr:r}));return}}async validateAccessToken(t,r){try{return await this.tokenConsumer.tokenAuthorized(t,"access",r)}catch(n){l.logger.debug(u({err:n})),l.logger.error(u({msg:"Access token invalid",cerr:n}));return}}async idTokenAuthorized(t,r){try{return await this.tokenConsumer.tokenAuthorized(t,"id",r)}catch(n){l.logger.warn(u({err:n})),l.logger.debug(u({err:n}));return}}getTokenPayload(t){return rt(t)}}v=new WeakMap,S=new WeakMap;class nt{constructor(t,r={}){c(this,"audience");c(this,"jwtKeyType");c(this,"jwtSecretKey");c(this,"jwtPublicKey");c(this,"clockTolerance",10);c(this,"authServerBaseUrl","");c(this,"oidcConfig");c(this,"keys",{});if(this.audience=t,r.authServerBaseUrl&&(this.authServerBaseUrl=r.authServerBaseUrl),r.jwtKeyType&&(this.jwtKeyType=r.jwtKeyType),r.jwtSecretKey&&(this.jwtSecretKey=r.jwtSecretKey),r.jwtPublicKey&&(this.jwtPublicKey=r.jwtPublicKey),r.clockTolerance&&(this.clockTolerance=r.clockTolerance),r.oidcConfig&&(this.oidcConfig=r.oidcConfig),this.jwtPublicKey&&!this.jwtKeyType)throw new p(y.Configuration,"If specifying jwtPublic key, must also specify jwtKeyType")}async loadKeys(t){try{if(this.jwtSecretKey){if(!this.jwtKeyType)throw new p(y.Configuration,"Must specify jwtKeyType if setting jwtSecretKey");this.keys._default=await Ve(this.jwtSecretKey,this.jwtKeyType)}else if(this.jwtPublicKey){if(!this.jwtKeyType)throw new p(y.Configuration,"Must specify jwtKeyType if setting jwtPublicKey");const r=await Be(this.jwtPublicKey,this.jwtKeyType);this.keys._default=r}else{if(this.oidcConfig||await this.loadConfig(),!this.oidcConfig)throw new p(y.Connection,"Load OIDC config before Jwks");await this.loadJwks(void 0,t)}}catch(r){throw l.logger.debug(u({err:r})),new p(y.Connection,"Couldn't load keys")}}async loadConfig(t){if(t){this.oidcConfig=t;return}if(!this.authServerBaseUrl)throw new p(y.Connection,"Couldn't get OIDC configuration. Either set authServerBaseUrl or set config manually");let r;try{let n=this.authServerBaseUrl;n.endsWith("/")||(n+="/"),r=await fetch(new URL(".well-known/openid-configuration",n))}catch(n){l.logger.error(u({err:n}))}if(!r||!r.ok)throw new p(y.Connection,"Couldn't get OIDC configuration");this.oidcConfig={...X};try{const n=await r.json();for(const[i,o]of Object.entries(n))this.oidcConfig[i]=o}catch{throw new p(y.Connection,"Unrecognized response from OIDC configuration endpoint")}}async loadJwks(t,r){if(t){this.keys={};for(let n=0;n<t.keys.length;++n){const i=t.keys[n],o="kid"in i&&i.kid?i.kid:"_default";this.keys[o]=await j(t.keys[n])}}else{if(!this.oidcConfig)throw new p(y.Connection,"Load OIDC config before Jwks");let n;try{n=await fetch(new URL(this.oidcConfig.jwks_uri))}catch(i){l.logger.error(u({err:i}))}if(!n||!n.ok)throw new p(y.Connection,"Couldn't get OIDC configuration");this.keys={};try{const i=await n.json();if(!("keys"in i)||!Array.isArray(i.keys))throw new p(y.Connection,"Couldn't fetch keys");for(let o=0;o<i.keys.length;++o)try{let s="_default",a={...i.keys[o]};if("kid"in a&&typeof a.kid=="string"&&(s=String(a.kid)),a&&!a.alg&&!a.jwk_alg&&r)if(r.startsWith("RS")&&a.kty=="RSA")a.alg=r;else{l.logger.debug(u({msg:"Skipping key with "+a.kty}));continue}const d=await j(a);this.keys[s]=d}catch(s){throw l.logger.error(u({err:s})),new p(y.Connection,"Couldn't load keys")}}catch(i){throw l.logger.error(u({err:i})),new p(y.Connection,"Unrecognized response from OIDC jwks endpoint")}}}async tokenAuthorized(t,r,n){if(!this.keys||Object.keys(this.keys).length==0){const o=ie(t);await this.loadKeys(o.alg)}const i=await this.validateToken(t);if(i){if(i.iss!=this.authServerBaseUrl){const o=i.jti?i.jti:i.sid?i.sid:"";l.logger.error(u({msg:`Invalid issuer ${i.iss} ${r} token`,hashedAccessToken:await this.hash(o)}));return}if(n!=!1&&i.aud){const o=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){l.logger.error(u({msg:`Invalid audience ${i.aud} in ${r} token`,hashedAccessToken:await this.hash(o)}));return}}return i}}async validateToken(t){(!this.keys||Object.keys(this.keys).length==0)&&l.logger.warn("No keys loaded so cannot validate tokens");let r;try{r=ie(t).kid}catch{l.logger.warn(u({msg:"Invalid access token format"}));return}let n;for(let i in this.keys)if(r==i){n=this.keys[i];break}if(!n&&"_default"in this.keys&&(n=this.keys._default),!n){l.logger.warn(u({msg:"No matching keys found for access token"}));return}try{const{payload:i}=await tt(t,n),o=JSON.parse(new TextDecoder().decode(i));if(o.exp*1e3<Date.now()+this.clockTolerance){l.logger.warn(u({msg:"Access token has expired"}));return}return o}catch(i){const o=p.asCrossauthError(i);l.logger.debug(u({err:o})),l.logger.warn(u({msg:"Access token did not validate",cerr:o}));return}}}exports.CrossauthError=p;exports.CrossauthLogger=l;exports.DEFAULT_OIDCCONFIG=X;exports.ErrorCode=y;exports.KeyPrefix=A;exports.OAuthClientBase=it;exports.OAuthFlows=Y;exports.OAuthTokenConsumerBase=nt;exports.UserState=T;exports.httpStatus=we;exports.j=u;
1
+ "use strict";var ye=Object.defineProperty;var Q=e=>{throw TypeError(e)};var me=(e,t,r)=>t in e?ye(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var c=(e,t,r)=>me(e,typeof t!="symbol"?t+"":t,r),Z=(e,t,r)=>t.has(e)||Q("Cannot "+r);var g=(e,t,r)=>(Z(e,t,"read from private field"),r?r.call(e):t.get(e)),$=(e,t,r)=>t.has(e)?Q("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),D=(e,t,r,n)=>(Z(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class T{}c(T,"active","active"),c(T,"disabled","disabled"),c(T,"awaitingTwoFactorSetup","awaitingtwofactorsetup"),c(T,"awaitingTwoFactorSetupAndEmailVerification","awaitingtwofactorsetupandemailverification"),c(T,"awaitingEmailVerification","awaitingemailverification"),c(T,"passwordChangeNeeded","passwordchangeneeded"),c(T,"passwordResetNeeded","passwordresetneeded"),c(T,"factor2ResetNeeded","factor2resetneeded"),c(T,"passwordAndFactor2ResetNeeded","passwordandfactor2resetneeded");class A{}c(A,"session","s:"),c(A,"passwordResetToken","p:"),c(A,"emailVerificationToken","e:"),c(A,"apiKey","api:"),c(A,"authorizationCode","authz:"),c(A,"accessToken","access:"),c(A,"refreshToken","refresh:"),c(A,"mfaToken","omfa:"),c(A,"deviceCode","dc:"),c(A,"userCode","uc:");var y=(e=>(e[e.UserNotExist=0]="UserNotExist",e[e.PasswordInvalid=1]="PasswordInvalid",e[e.EmailNotExist=2]="EmailNotExist",e[e.UsernameOrPasswordInvalid=3]="UsernameOrPasswordInvalid",e[e.InvalidClientId=4]="InvalidClientId",e[e.ClientExists=5]="ClientExists",e[e.InvalidClientSecret=6]="InvalidClientSecret",e[e.InvalidClientIdOrSecret=7]="InvalidClientIdOrSecret",e[e.InvalidRedirectUri=8]="InvalidRedirectUri",e[e.InvalidOAuthFlow=9]="InvalidOAuthFlow",e[e.UserNotActive=10]="UserNotActive",e[e.EmailNotVerified=11]="EmailNotVerified",e[e.TwoFactorIncomplete=12]="TwoFactorIncomplete",e[e.Unauthorized=13]="Unauthorized",e[e.UnauthorizedClient=14]="UnauthorizedClient",e[e.InvalidScope=15]="InvalidScope",e[e.InsufficientScope=16]="InsufficientScope",e[e.InsufficientPriviledges=17]="InsufficientPriviledges",e[e.Forbidden=18]="Forbidden",e[e.InvalidKey=19]="InvalidKey",e[e.InvalidCsrf=20]="InvalidCsrf",e[e.InvalidSession=21]="InvalidSession",e[e.Expired=22]="Expired",e[e.Connection=23]="Connection",e[e.InvalidHash=24]="InvalidHash",e[e.UnsupportedAlgorithm=25]="UnsupportedAlgorithm",e[e.KeyExists=26]="KeyExists",e[e.PasswordChangeNeeded=27]="PasswordChangeNeeded",e[e.PasswordResetNeeded=28]="PasswordResetNeeded",e[e.Factor2ResetNeeded=29]="Factor2ResetNeeded",e[e.Configuration=30]="Configuration",e[e.InvalidEmail=31]="InvalidEmail",e[e.InvalidPhoneNumber=32]="InvalidPhoneNumber",e[e.InvalidUsername=33]="InvalidUsername",e[e.PasswordMatch=34]="PasswordMatch",e[e.InvalidToken=35]="InvalidToken",e[e.MfaRequired=36]="MfaRequired",e[e.PasswordFormat=37]="PasswordFormat",e[e.DataFormat=38]="DataFormat",e[e.FetchError=39]="FetchError",e[e.UserExists=40]="UserExists",e[e.FormEntry=41]="FormEntry",e[e.BadRequest=42]="BadRequest",e[e.AuthorizationPending=43]="AuthorizationPending",e[e.SlowDown=44]="SlowDown",e[e.ExpiredToken=45]="ExpiredToken",e[e.ConstraintViolation=46]="ConstraintViolation",e[e.NotImplemented=47]="NotImplemented",e[e.UnknownError=48]="UnknownError",e))(y||{});class p extends Error{constructor(r,n=void 0){let i,o=500;r==0?(i="User does not exist",o=401):r==1?(i="Password doesn't match",o=401):r==3?(i="Username or password incorrect",o=401):r==4?(i="Client id is invalid",o=401):r==5?(i="Client ID or name already exists",o=500):r==6?(i="Client secret is invalid",o=401):r==7?(i="Client id or secret is invalid",o=401):r==8?(i="Redirect Uri is not registered",o=401):r==9?(i="Invalid OAuth flow type",o=500):r==2?(i="No user exists with that email address",o=401):r==10?(i="Account is not active",o=403):r==33?(i="Username is not in an allowed format",o=400):r==31?(i="Email is not in an allowed format",o=400):r==32?(i="Phone number is not in an allowed format",o=400):r==11?(i="Email address has not been verified",o=403):r==12?(i="Two-factor setup is not complete",o=403):r==13?(i="Not authorized",o=401):r==14?(i="Client not authorized",o=401):r==15?(i="Invalid scope",o=403):r==16?(i="Insufficient scope",o=403):r==23?i="Connection failure":r==22?(i="Token has expired",o=401):r==24?i="Hash is not in a valid format":r==19?(i="Key is invalid",o=401):r==18?(i="You do not have permission to access this resource",o=403):r==17?(i="You do not have the right privileges to access this resource",o=401):r==20?(i="CSRF token is invalid",o=401):r==21?(i="Session cookie is invalid",o=401):r==25?i="Algorithm not supported":r==26?i="Attempt to create a key that already exists":r==27?(i="User must change password",o=403):r==28?(i="User must reset password",o=403):r==29?(i="User must reset 2FA",o=403):r==30?i="There was an error in the configuration":r==34?(i="Passwords do not match",o=401):r==35?(i="Token is not valid",o=401):r==36?(i="MFA is required",o=401):r==37?(i="Password format was incorrect",o=401):r==40?(i="User already exists",o=400):r==42?(i="The request is invalid",o=400):r==38?(i="Session data has unexpected format",o=500):r==39?(i="Couldn't execute a fetch",o=500):r==43?(i="Waiting for authorization",o=200):r==44?(i="Slow polling down by 5 seconds",o=200):r==45?(i="Token has expired",o=401):r==46?(i="Database update/insert caused a constraint violation",o=500):r==47?(i="This method has not been implemented",o=500):(i="Unknown error",o=500),n!=null&&!Array.isArray(n)?i=n:Array.isArray(n)&&(i=n.join(". "));super(i);c(this,"isCrossauthError",!0);c(this,"httpStatus");c(this,"code");c(this,"codeName");c(this,"messages");this.code=r,this.codeName=y[r],this.httpStatus=o,this.name="CrossauthError",Array.isArray(n)?this.messages=n:this.messages=[i],Object.setPrototypeOf(this,p.prototype)}static fromOAuthError(r,n){let i;switch(r){case"invalid_request":i=42;break;case"unauthorized_client":i=14;break;case"access_denied":i=13;break;case"unsupported_response_type":i=42;break;case"invalid_scope":i=15;break;case"server_error":i=48;break;case"temporarily_unavailable":i=23;break;case"invalid_token":i=35;break;case"expired_token":i=45;break;case"insufficient_scope":i=35;break;case"mfa_required":i=36;break;case"authorization_pending":i=43;break;case"slow_down":i=44;break;default:i=48}return new p(i,n)}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(r,n){if(r instanceof Error)return"isCrossauthError"in r?r:new p(48,r.message);if("errorCode"in r){let o=48;try{o=Number(r.errorCode)??48}catch{}let s=n??y[o];return"errorMessage"in r?s=r.errorMessage:"message"in r&&(s=r.message),new p(o,s)}let i=n??y[48];return"message"in r&&(i=r.message),new p(48,i)}}function we(e){return typeof e=="number"&&(e=""+e),e in B?B[e]:B[500]}const B={200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Unused",307:"Temporary Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Required",413:"Request Entry Too Large",414:"Request-URI Too Long",415:"Unsupported Media Type",416:"Requested Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",429:"Too Many Requests",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported"},m=class m{constructor(t){c(this,"level");if(t)this.level=t;else if(typeof process<"u"&&"CROSSAUTH_LOG_LEVEL"in process.env){const r=(process.env.CROSSAUTH_LOG_LEVEL??"ERROR").toUpperCase();m.levelName.includes(r)?this.level=m.levelName.indexOf(r):this.level=m.Error}else this.level=m.Error}static get logger(){return globalThis.crossauthLogger}setLevel(t){this.level=t}log(t,r){t<=this.level&&(typeof r=="string"?console.log("Crossauth "+m.levelName[t]+" "+new Date().toISOString(),r):console.log(JSON.stringify({level:m.levelName[t],time:new Date().toISOString(),...r})))}error(t){this.log(m.Error,t)}warn(t){this.log(m.Warn,t)}info(t){this.log(m.Info,t)}debug(t){this.log(m.Debug,t)}static setLogger(t,r){globalThis.crossauthLogger=t,globalThis.crossauthLoggerAcceptsJson=r}};c(m,"None",0),c(m,"Error",1),c(m,"Warn",2),c(m,"Info",3),c(m,"Debug",4),c(m,"levelName",["NONE","ERROR","WARN","INFO","DEBUG"]);let l=m;function u(e){let t;typeof e=="object"&&"err"in e&&typeof e.err=="object"&&(t=e.err.stack);try{typeof e=="object"&&"err"in e&&typeof e.err=="object"&&e.err&&"message"in e.err&&!("msg"in e)&&(e.msg=e.err.message)}catch{}try{typeof e=="object"&&"err"in e&&typeof e.err=="object"&&(e.err={...e.err,stack:t})}catch{}try{typeof e=="object"&&"err"in e&&!("msg"in e)&&(e.msg=e.msg="An unknown error occurred")}catch{}try{typeof e=="object"&&"cerr"in e&&"isCrossauthError"in e.cerr&&e.cerr&&(e.errorCode=e.cerr.code,e.errorCodeName=e.cerr.codeName,e.httpStatus=e.cerr.httpStatus,"msg"in e||(e.msg=e.cerr.message),delete e.cerr)}catch{}return typeof e=="string"||globalThis.crossauthLoggerAcceptsJson?e:JSON.stringify(e)}globalThis.crossauthLogger=new l;globalThis.crossauthLoggerAcceptsJson=!0;const X={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},q=crypto,ne=e=>e instanceof CryptoKey,M=new TextEncoder,H=new TextDecoder;function _e(...e){const t=e.reduce((i,{length:o})=>i+o,0),r=new Uint8Array(t);let n=0;for(const i of e)r.set(i,n),n+=i.length;return r}const ve=e=>{const t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r},O=e=>{let t=e;t instanceof Uint8Array&&(t=H.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return ve(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class C extends Error{constructor(t,r){var n;super(t,r),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(n=Error.captureStackTrace)==null||n.call(Error,this,this.constructor)}}C.code="ERR_JOSE_GENERIC";class Se extends C{constructor(t,r,n="unspecified",i="unspecified"){super(t,{cause:{claim:n,reason:i,payload:r}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=n,this.reason=i,this.payload=r}}Se.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class Ce extends C{constructor(t,r,n="unspecified",i="unspecified"){super(t,{cause:{claim:n,reason:i,payload:r}}),this.code="ERR_JWT_EXPIRED",this.claim=n,this.reason=i,this.payload=r}}Ce.code="ERR_JWT_EXPIRED";class be extends C{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}be.code="ERR_JOSE_ALG_NOT_ALLOWED";class I extends C{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}I.code="ERR_JOSE_NOT_SUPPORTED";class Ae extends C{constructor(t="decryption operation failed",r){super(t,r),this.code="ERR_JWE_DECRYPTION_FAILED"}}Ae.code="ERR_JWE_DECRYPTION_FAILED";class Ie extends C{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}Ie.code="ERR_JWE_INVALID";class w extends C{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}w.code="ERR_JWS_INVALID";class k extends C{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}k.code="ERR_JWT_INVALID";class Ee extends C{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}Ee.code="ERR_JWK_INVALID";class Te extends C{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}Te.code="ERR_JWKS_INVALID";class Re extends C{constructor(t="no applicable key found in the JSON Web Key Set",r){super(t,r),this.code="ERR_JWKS_NO_MATCHING_KEY"}}Re.code="ERR_JWKS_NO_MATCHING_KEY";class Pe extends C{constructor(t="multiple matching keys found in the JSON Web Key Set",r){super(t,r),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}Pe.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class ke extends C{constructor(t="request timed out",r){super(t,r),this.code="ERR_JWKS_TIMEOUT"}}ke.code="ERR_JWKS_TIMEOUT";class oe extends C{constructor(t="signature verification failed",r){super(t,r),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}oe.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function E(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function z(e,t){return e.name===t}function V(e){return parseInt(e.name.slice(4),10)}function Ke(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Oe(e,t){if(t.length&&!t.some(r=>e.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(t.length>2){const n=t.pop();r+=`one of ${t.join(", ")}, or ${n}.`}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}function Ne(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!z(e.algorithm,"HMAC"))throw E("HMAC");const n=parseInt(t.slice(2),10);if(V(e.algorithm.hash)!==n)throw E(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!z(e.algorithm,"RSASSA-PKCS1-v1_5"))throw E("RSASSA-PKCS1-v1_5");const n=parseInt(t.slice(2),10);if(V(e.algorithm.hash)!==n)throw E(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!z(e.algorithm,"RSA-PSS"))throw E("RSA-PSS");const n=parseInt(t.slice(2),10);if(V(e.algorithm.hash)!==n)throw E(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw E("Ed25519 or Ed448");break}case"Ed25519":{if(!z(e.algorithm,"Ed25519"))throw E("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!z(e.algorithm,"ECDSA"))throw E("ECDSA");const n=Ke(t);if(e.algorithm.namedCurve!==n)throw E(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Oe(e,r)}function se(e,t,...r){var n;if(r=r.filter(Boolean),r.length>2){const i=r.pop();e+=`one of type ${r.join(", ")}, or ${i}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&(n=t.constructor)!=null&&n.name&&(e+=` Received an instance of ${t.constructor.name}`),e}const ee=(e,...t)=>se("Key must be ",e,...t);function ae(e,t,...r){return se(`Key for the ${e} algorithm must be `,t,...r)}const ce=e=>ne(e)?!0:(e==null?void 0:e[Symbol.toStringTag])==="KeyObject",L=["CryptoKey"],We=(...e)=>{const t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(const n of t){const i=Object.keys(n);if(!r||r.size===0){r=new Set(i);continue}for(const o of i){if(r.has(o))return!1;r.add(o)}}return!0};function Je(e){return typeof e=="object"&&e!==null}function U(e){if(!Je(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}const Ue=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};function x(e){return U(e)&&typeof e.kty=="string"}function xe(e){return e.kty!=="oct"&&typeof e.d=="string"}function De(e){return e.kty!=="oct"&&typeof e.d>"u"}function ze(e){return x(e)&&e.kty==="oct"&&typeof e.k=="string"}function He(e){let t,r;switch(e.kty){case"RSA":{switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new I('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new I('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(e.alg){case"Ed25519":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"EdDSA":t={name:e.crv},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new I('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new I('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}const de=async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:r}=He(e),n=[t,e.ext??!1,e.key_ops??r],i={...e};return delete i.alg,delete i.use,q.subtle.importKey("jwk",i,...n)},le=e=>O(e);let N,W;const ue=e=>(e==null?void 0:e[Symbol.toStringTag])==="KeyObject",F=async(e,t,r,n,i=!1)=>{let o=e.get(t);if(o!=null&&o[n])return o[n];const s=await de({...r,alg:n});return i&&Object.freeze(t),o?o[n]=s:e.set(t,{[n]:s}),s},Me=(e,t)=>{if(ue(e)){let r=e.export({format:"jwk"});return delete r.d,delete r.dp,delete r.dq,delete r.p,delete r.q,delete r.qi,r.k?le(r.k):(W||(W=new WeakMap),F(W,e,r,t))}return x(e)?e.k?O(e.k):(W||(W=new WeakMap),F(W,e,e,t,!0)):e},Le=(e,t)=>{if(ue(e)){let r=e.export({format:"jwk"});return r.k?le(r.k):(N||(N=new WeakMap),F(N,e,r,t))}return x(e)?e.k?O(e.k):(N||(N=new WeakMap),F(N,e,e,t,!0)):e},Fe={normalizePublicKey:Me,normalizePrivateKey:Le},K=(e,t,r=0)=>{r===0&&(t.unshift(t.length),t.unshift(6));const n=e.indexOf(t[0],r);if(n===-1)return!1;const i=e.subarray(n,n+t.length);return i.length!==t.length?!1:i.every((o,s)=>o===t[s])||K(e,t,n+1)},te=e=>{switch(!0){case K(e,[42,134,72,206,61,3,1,7]):return"P-256";case K(e,[43,129,4,0,34]):return"P-384";case K(e,[43,129,4,0,35]):return"P-521";case K(e,[43,101,110]):return"X25519";case K(e,[43,101,111]):return"X448";case K(e,[43,101,112]):return"Ed25519";case K(e,[43,101,113]):return"Ed448";default:throw new I("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},he=async(e,t,r,n,i)=>{let o,s;const a=new Uint8Array(atob(r.replace(e,"")).split("").map(f=>f.charCodeAt(0))),d=t==="spki";switch(n){case"PS256":case"PS384":case"PS512":o={name:"RSA-PSS",hash:`SHA-${n.slice(-3)}`},s=d?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":o={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.slice(-3)}`},s=d?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":o={name:"RSA-OAEP",hash:`SHA-${parseInt(n.slice(-3),10)||1}`},s=d?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":o={name:"ECDSA",namedCurve:"P-256"},s=d?["verify"]:["sign"];break;case"ES384":o={name:"ECDSA",namedCurve:"P-384"},s=d?["verify"]:["sign"];break;case"ES512":o={name:"ECDSA",namedCurve:"P-521"},s=d?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{const f=te(a);o=f.startsWith("P-")?{name:"ECDH",namedCurve:f}:{name:f},s=d?[]:["deriveBits"];break}case"Ed25519":o={name:"Ed25519"},s=d?["verify"]:["sign"];break;case"EdDSA":o={name:te(a)},s=d?["verify"]:["sign"];break;default:throw new I('Invalid or unsupported "alg" (Algorithm) value')}return q.subtle.importKey(t,a,o,!1,s)},qe=(e,t,r)=>he(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t),$e=(e,t,r)=>he(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",e,t);async function Be(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return $e(e,t)}async function Ve(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return qe(e,t)}async function j(e,t){if(!U(e))throw new TypeError("JWK must be an object");switch(t||(t=e.alg),e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return O(e.k);case"RSA":if("oth"in e&&e.oth!==void 0)throw new I('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return de({...e,alg:t});default:throw new I('Unsupported "kty" (Key Type) Parameter value')}}const J=e=>e==null?void 0:e[Symbol.toStringTag],G=(e,t,r)=>{var n,i;if(t.use!==void 0&&t.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(t.key_ops!==void 0&&((i=(n=t.key_ops).includes)==null?void 0:i.call(n,r))!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},je=(e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&x(t)){if(ze(t)&&G(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!ce(t))throw new TypeError(ae(e,t,...L,"Uint8Array",n?"JSON Web Key":null));if(t.type!=="secret")throw new TypeError(`${J(t)} instances for symmetric algorithms must be of type "secret"`)}},Ge=(e,t,r,n)=>{if(n&&x(t))switch(r){case"sign":if(xe(t)&&G(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(De(t)&&G(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!ce(t))throw new TypeError(ae(e,t,...L,n?"JSON Web Key":null));if(t.type==="secret")throw new TypeError(`${J(t)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${J(t)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${J(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${J(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${J(t)} instances for asymmetric algorithm encryption must be of type "public"`)};function fe(e,t,r,n){t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?je(t,r,n,e):Ge(t,r,n,e)}fe.bind(void 0,!1);const re=fe.bind(void 0,!0);function Ye(e,t,r,n,i){if(i.crit!==void 0&&(n==null?void 0:n.crit)===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(s=>typeof s!="string"||s.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let o;o=t;for(const s of n.crit){if(!o.has(s))throw new I(`Extension Header Parameter "${s}" is not recognized`);if(i[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(o.get(s)&&n[s]===void 0)throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return new Set(n.crit)}function Xe(e,t){const r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:t.name};default:throw new I(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function Qe(e,t,r){if(t=await Fe.normalizePublicKey(t,e),ne(t))return Ne(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(ee(t,...L));return q.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(ee(t,...L,"Uint8Array","JSON Web Key"))}const Ze=async(e,t,r,n)=>{const i=await Qe(e,t,"verify");Ue(e,i);const o=Xe(e,i.algorithm);try{return await q.subtle.verify(o,i,r,n)}catch{return!1}};async function et(e,t,r){if(!U(e))throw new w("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new w('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new w("JWS Protected Header incorrect type");if(e.payload===void 0)throw new w("JWS Payload missing");if(typeof e.signature!="string")throw new w("JWS Signature missing or incorrect type");if(e.header!==void 0&&!U(e.header))throw new w("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{const ge=O(e.protected);n=JSON.parse(H.decode(ge))}catch{throw new w("JWS Protected Header is invalid")}if(!We(n,e.header))throw new w("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const i={...n,...e.header},o=Ye(w,new Map([["b64",!0]]),r==null?void 0:r.crit,n,i);let s=!0;if(o.has("b64")&&(s=n.b64,typeof s!="boolean"))throw new w('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=i;if(typeof a!="string"||!a)throw new w('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(s){if(typeof e.payload!="string")throw new w("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new w("JWS Payload must be a string or an Uint8Array instance");let d=!1;typeof t=="function"?(t=await t(n,e),d=!0,re(a,t,"verify"),x(t)&&(t=await j(t,a))):re(a,t,"verify");const f=_e(M.encode(e.protected??""),M.encode("."),typeof e.payload=="string"?M.encode(e.payload):e.payload);let v;try{v=O(e.signature)}catch{throw new w("Failed to base64url decode the signature")}if(!await Ze(a,t,v,f))throw new oe;let b;if(s)try{b=O(e.payload)}catch{throw new w("Failed to base64url decode the payload")}else typeof e.payload=="string"?b=M.encode(e.payload):b=e.payload;const P={payload:b};return e.protected!==void 0&&(P.protectedHeader=n),e.header!==void 0&&(P.unprotectedHeader=e.header),d?{...P,key:t}:P}async function tt(e,t,r){if(e instanceof Uint8Array&&(e=H.decode(e)),typeof e!="string")throw new w("Compact JWS must be a string or Uint8Array");const{0:n,1:i,2:o,length:s}=e.split(".");if(s!==3)throw new w("Invalid Compact JWS");const a=await et({payload:i,protected:n,signature:o},t,r),d={payload:a.payload,protectedHeader:a.protectedHeader};return typeof t=="function"?{...d,key:a.key}:d}const pe=O;function ie(e){let t;if(typeof e=="string"){const r=e.split(".");(r.length===3||r.length===5)&&([t]=r)}else if(typeof e=="object"&&e)if("protected"in e)t=e.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof t!="string"||!t)throw new Error;const r=JSON.parse(H.decode(pe(t)));if(!U(r))throw new Error;return r}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}function rt(e){if(typeof e!="string")throw new k("JWTs must use Compact JWS serialization, JWT must be a string");const{1:t,length:r}=e.split(".");if(r===5)throw new k("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new k("Invalid JWT");if(!t)throw new k("JWTs must contain a payload");let n;try{n=pe(t)}catch{throw new k("Failed to base64url decode the payload")}let i;try{i=JSON.parse(H.decode(n))}catch{throw new k("Failed to parse the decoded payload as JSON")}if(!U(i))throw new k("Invalid JWT Claims Set");return i}const h=class h{static flowNames(t){let r={};return t.forEach(n=>{n in h.flowName&&(r[n]=h.flowName[n])}),r}static isValidFlow(t){return h.allFlows().includes(t)}static areAllValidFlows(t){let r=!0;return t.forEach(n=>{h.isValidFlow(n)||(r=!1)}),r}static allFlows(){return[h.AuthorizationCode,h.AuthorizationCodeWithPKCE,h.ClientCredentials,h.RefreshToken,h.DeviceCode,h.Password,h.PasswordMfa,h.OidcAuthorizationCode]}static grantType(t){switch(t){case h.AuthorizationCode:case h.AuthorizationCodeWithPKCE:case h.OidcAuthorizationCode:return["authorization_code"];case h.ClientCredentials:return["client_credentials"];case h.RefreshToken:return["refresh_token"];case h.Password:return["password"];case h.PasswordMfa:return["http://auth0.com/oauth/grant-type/mfa-otp","http://auth0.com/oauth/grant-type/mfa-oob"];case h.DeviceCode:return["urn:ietf:params:oauth:grant-type:device_code"]}}};c(h,"All","all"),c(h,"AuthorizationCode","authorizationCode"),c(h,"AuthorizationCodeWithPKCE","authorizationCodeWithPKCE"),c(h,"ClientCredentials","clientCredentials"),c(h,"RefreshToken","refreshToken"),c(h,"DeviceCode","deviceCode"),c(h,"Password","password"),c(h,"PasswordMfa","passwordMfa"),c(h,"OidcAuthorizationCode","oidcAuthorizationCode"),c(h,"flowName",{[h.AuthorizationCode]:"Authorization Code",[h.AuthorizationCodeWithPKCE]:"Authorization Code with PKCE",[h.ClientCredentials]:"Client Credentials",[h.RefreshToken]:"Refresh Token",[h.DeviceCode]:"Device Code",[h.Password]:"Password",[h.PasswordMfa]:"Password MFA",[h.OidcAuthorizationCode]:"OIDC Authorization Code"});let Y=h;var _,S;class it{constructor({authServerBaseUrl:t,client_id:r,client_secret:n,redirect_uri:i,codeChallengeMethod:o,stateLength:s,verifierLength:a,tokenConsumer:d,authServerCredentials:f,authServerMode:v,authServerHeaders:R}){c(this,"authServerBaseUrl","");$(this,_);$(this,S);c(this,"codeChallengeMethod","S256");c(this,"verifierLength",32);c(this,"redirect_uri");c(this,"stateLength",32);c(this,"authzCode","");c(this,"oidcConfig");c(this,"tokenConsumer");c(this,"authServerHeaders",{});c(this,"authServerMode");c(this,"authServerCredentials");c(this,"oauthPostType","json");c(this,"oauthLogFetch",!1);c(this,"oauthUseUserInfoEndpoint",!1);c(this,"oauthAuthorizeRedirect");this.tokenConsumer=d,this.authServerBaseUrl=t,a&&(this.verifierLength=a),s&&(this.stateLength=s),r&&D(this,_,r),n&&D(this,S,n),i&&(this.redirect_uri=i),o&&(this.codeChallengeMethod=o),this.authServerBaseUrl=t,f&&(this.authServerCredentials=f),v&&(this.authServerMode=v),R&&(this.authServerHeaders=R)}set client_id(t){D(this,_,t)}set client_secret(t){D(this,S,t)}async loadConfig(t){if(t){l.logger.debug(u({msg:"Reading OIDC config locally"})),this.oidcConfig=t;return}let r;try{const n=new URL(this.authServerBaseUrl+"/.well-known/openid-configuration");l.logger.debug(u({msg:`Fetching OIDC config from ${n}`}));let i={headers:this.authServerHeaders};this.authServerMode&&(i.mode=this.authServerMode),this.authServerCredentials&&(i.credentials=this.authServerCredentials),r=await fetch(n,i)}catch(n){l.logger.error(u({err:n}))}if(!r||!r.ok)throw new p(y.Connection,"Couldn't get OIDC configuration from URL"+this.authServerBaseUrl+"/.well-known/openid-configuration");this.oidcConfig={...X};try{const n=await r.json();for(const[i,o]of Object.entries(n))this.oidcConfig[i]=o}catch{throw new p(y.Connection,"Unrecognized response from OIDC configuration endpoint")}}getOidcConfig(){return this.oidcConfig}async startAuthorizationCodeFlow(t,{scope:r,codeChallenge:n,pkce:i=!1}){var a,d,f;if(l.logger.debug(u({msg:"Starting authorization code flow, scope "+r})),this.oidcConfig||await this.loadConfig(),!((a=this.oidcConfig)!=null&&a.response_types_supported.includes("code"))||!((d=this.oidcConfig)!=null&&d.response_modes_supported.includes("query")))return{error:"invalid_request",error_description:"Server does not support authorization code flow"};if(!((f=this.oidcConfig)!=null&&f.authorization_endpoint))return{error:"server_error",error_description:"Cannot get authorize endpoint"};if(!g(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 o=this.oidcConfig.authorization_endpoint;this.oauthAuthorizeRedirect&&(o=this.oauthAuthorizeRedirect);let s=o+"?response_type=code&client_id="+encodeURIComponent(g(this,_))+"&state="+encodeURIComponent(t)+"&redirect_uri="+encodeURIComponent(this.redirect_uri);return r&&(s+="&scope="+encodeURIComponent(r)),i&&n&&(s+="&code_challenge="+n),{url:s}}async codeChallengeAndVerifier(){const t=this.randomValue(this.verifierLength);return{codeChallenge:this.codeChallengeMethod=="plain"?t:await this.sha256(t),codeVerifier:t}}async getIdPayload(t,r){let n,i;try{let o;if(o=await this.validateIdToken(t),!o)return n="access_denied",i="Invalid ID token received",{error:n,error_description:i};if(r&&this.oauthUseUserInfoEndpoint){const s=await this.userInfoEndpoint(r);if(s.error)return n=s.error,i="Failed getting user info: "+(s.error_description??"unknown error"),{error:n,error_description:i};o={...o,...s}}return{payload:o}}catch(o){const s=p.asCrossauthError(o);return l.logger.debug(u({err:s})),l.logger.error(u({msg:"Couldn't get user info",cerr:s})),n=s.oauthErrorCode,i="Couldn't get user info: "+s.message,{error:n,error_description:i}}}async getAccessPayload(t,r){let n,i;try{let o;return o=await this.validateAccessToken(t,r),o?{payload:o}:(n="access_denied",i="Invalid access token received",{error:n,error_description:i})}catch(o){const s=p.asCrossauthError(o);return l.logger.debug(u({err:s})),l.logger.error(u({msg:"Couldn't get user info",cerr:s})),n=s.oauthErrorCode,i="Couldn't get user info: "+s.message,{error:n,error_description:i}}}async redirectEndpoint({code:t,scope:r,codeVerifier:n,error:i,errorDescription:o}){var v,R;if(this.oidcConfig||await this.loadConfig(),i||!t)return i||(i="server_error"),o||(o="Unknown error"),{error:i,error_description:o};if(this.authzCode=t,!((v=this.oidcConfig)!=null&&v.grant_types_supported.includes("authorization_code")))return{error:"invalid_request",error_description:"Server does not support authorization code grant"};if(!((R=this.oidcConfig)!=null&&R.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const s=this.oidcConfig.token_endpoint;let a,d;a="authorization_code",d=g(this,S);let f={grant_type:a,client_id:g(this,_),code:this.authzCode,redirect_uri:this.redirect_uri};r&&(f.scope=r),d&&(f.client_secret=d),n&&(f.code_verifier=n);try{let b=await this.post(s,f,this.authServerHeaders);if(b.id_token){const P=await this.getIdPayload(b.id_token,b.access_token);if(P.error)return P;b.id_payload=P.payload}return b}catch(b){return l.logger.error(u({err:b})),{error:"server_error",error_description:"Unable to get access token from server"}}}async clientCredentialsFlow(t){var i,o;if(l.logger.debug(u({msg:"Starting client credentials flow"})),this.oidcConfig||await this.loadConfig(),!((i=this.oidcConfig)!=null&&i.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(!g(this,_))return{error:"invalid_request",error_description:"Cannot make client credentials flow without client id"};const r=this.oidcConfig.token_endpoint;let n={grant_type:"client_credentials",client_id:g(this,_),client_secret:g(this,S)};t&&(n.scope=t);try{let s=await this.post(r,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 l.logger.error(u({err:s})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async passwordFlow(t,r,n){var s,a;if(l.logger.debug(u({msg:"Starting password flow"})),this.oidcConfig||await this.loadConfig(),!((s=this.oidcConfig)!=null&&s.grant_types_supported.includes("password")))return{error:"invalid_request",error_description:"Server does not support password grant"};if(!((a=this.oidcConfig)!=null&&a.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const i=this.oidcConfig.token_endpoint;let o={grant_type:"password",client_id:g(this,_),client_secret:g(this,S),username:t,password:r};n&&(o.scope=n);try{let d=await this.post(i,o,this.authServerHeaders);if(d.id_token){const f=await this.getIdPayload(d.id_token,d.access_token);if(f.error)return f;d.id_payload=f.payload}return d}catch(d){return l.logger.error(u({err:d})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async mfaAuthenticators(t){var o,s,a;if(l.logger.debug(u({msg:"Getting valid MFA authenticators"})),this.oidcConfig||await this.loadConfig(),!((o=this.oidcConfig)!=null&&o.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp"))&&((s=this.oidcConfig)!=null&&s.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-oob")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((a=this.oidcConfig)!=null&&a.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const r=this.oidcConfig.issuer+(this.oidcConfig.issuer.endsWith("/")?"":"/")+"mfa/authenticators",n=await this.get(r,{authorization:"Bearer "+t,...this.authServerHeaders});if(!Array.isArray(n))return{error:"server_error",error_description:"Expected array of authenticators in mfa/authenticators response"};let i=[];for(let d=0;d<n.length;++d){const f=n[d];if(!f.id||!f.authenticator_type||!f.active)return{error:"server_error",error_description:"Invalid mfa/authenticators response"};i.push({id:f.id,authenticator_type:f.authenticator_type,active:f.active,name:f.name,oob_channel:f.oob_channel})}return{authenticators:i}}async mfaOtpRequest(t,r){var o,s;if(l.logger.debug(u({msg:"Making MFA OTB request"})),this.oidcConfig||await this.loadConfig(),!((o=this.oidcConfig)!=null&&o.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((s=this.oidcConfig)!=null&&s.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const n=this.oidcConfig.issuer+(this.oidcConfig.issuer.endsWith("/")?"":"/")+"mfa/challenge",i=await this.post(n,{client_id:g(this,_),client_secret:g(this,S),challenge_type:"otp",mfa_token:t,authenticator_id:r},this.authServerHeaders);return i.challenge_type!="otp"?{error:i.error??"server_error",error_description:i.error_description??"Invalid OTP challenge response"}:i}async mfaOtpComplete(t,r,n){var s,a;if(l.logger.debug(u({msg:"Completing MFA OTP request"})),this.oidcConfig||await this.loadConfig(),!((s=this.oidcConfig)!=null&&s.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((a=this.oidcConfig)!=null&&a.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const i=this.oidcConfig.token_endpoint,o=await this.post(i,{grant_type:"http://auth0.com/oauth/grant-type/mfa-otp",client_id:g(this,_),client_secret:g(this,S),challenge_type:"otp",mfa_token:t,otp:r,scope:n},this.authServerHeaders);if(o.id_token){const d=await this.getIdPayload(o.id_token,o.access_token);if(d.error)return d;o.id_payload=d.payload}return{id_token:o.id_token,access_token:o.access_token,refresh_token:o.refresh_token,expires_in:Number(o.expires_in),scope:o.scope,token_type:o.token_type,error:o.error,error_description:o.error_description}}async mfaOobRequest(t,r){var o,s;if(l.logger.debug(u({msg:"Making MFA OOB request"})),this.oidcConfig||await this.loadConfig(),!((o=this.oidcConfig)!=null&&o.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((s=this.oidcConfig)!=null&&s.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const n=this.oidcConfig.issuer+(this.oidcConfig.issuer.endsWith("/")?"":"/")+"mfa/challenge",i=await this.post(n,{client_id:g(this,_),client_secret:g(this,S),challenge_type:"oob",mfa_token:t,authenticator_id:r},this.authServerHeaders);return i.challenge_type!="oob"||!i.oob_code||!i.binding_method?{error:i.error??"server_error",error_description:i.error_description??"Invalid OOB challenge response"}:{challenge_type:i.challenge_type,oob_code:i.oob_code,binding_method:i.binding_method,error:i.error,error_description:i.error_description}}async mfaOobComplete(t,r,n,i){var a,d;if(l.logger.debug(u({msg:"Completing MFA OOB request"})),this.oidcConfig||await this.loadConfig(),!((a=this.oidcConfig)!=null&&a.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(!((d=this.oidcConfig)!=null&&d.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const o=this.oidcConfig.token_endpoint,s=await this.post(o,{grant_type:"http://auth0.com/oauth/grant-type/mfa-oob",client_id:g(this,_),client_secret:g(this,S),challenge_type:"otp",mfa_token:t,oob_code:r,binding_code:n,scope:i},this.authServerHeaders);if(s.error)return{error:s.error,error_description:s.error_description};if(s.id_token){const f=await this.getIdPayload(s.id_token,s.access_token);if(f.error)return f;s.id_payload=f.payload}return{id_token:s.id_token,access_token:s.access_token,refresh_token:s.refresh_token,expires_in:"expires_in"in s?Number(s.expires_in):void 0,scope:s.scope,token_type:s.token_type}}async refreshTokenFlow(t){var o,s;if(l.logger.debug(u({msg:"Starting refresh token flow"})),this.oidcConfig||await this.loadConfig(),!((o=this.oidcConfig)!=null&&o.grant_types_supported.includes("refresh_token")))return{error:"invalid_request",error_description:"Server does not support refresh_token grant"};if(!((s=this.oidcConfig)!=null&&s.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const r=this.oidcConfig.token_endpoint;let n;n=g(this,S);let i={grant_type:"refresh_token",refresh_token:t,client_id:g(this,_)};n&&(i.client_secret=n);try{let a=await this.post(r,i,this.authServerHeaders);if(a.id_token){const d=await this.getIdPayload(a.id_token,a.access_token);if(d!=null&&d.error)return d;a.id_payload=d==null?void 0:d.payload}return a}catch(a){return l.logger.error(u({err:a})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async startDeviceCodeFlow(t,r){var i;if(l.logger.debug(u({msg:"Starting device code flow"})),this.oidcConfig||await this.loadConfig(),!((i=this.oidcConfig)!=null&&i.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 n={grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:g(this,_),client_secret:g(this,S)};r&&(n.scope=r);try{let o=await this.post(t,n,this.authServerHeaders);return o.id_token&&!await this.validateIdToken(o.id_token)?{error:"access_denied",error_description:"Invalid ID token"}:o}catch(o){return l.logger.error(u({err:o})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async pollDeviceCodeFlow(t){var n,i,o;if(l.logger.debug(u({msg:"Starting device code flow"})),this.oidcConfig||await this.loadConfig(),!((n=this.oidcConfig)!=null&&n.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(!((i=this.oidcConfig)!=null&&i.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};let r={grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:g(this,_),client_secret:g(this,S),device_code:t};try{const s=await this.post((o=this.oidcConfig)==null?void 0:o.token_endpoint,r,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 l.logger.error(u({err:s})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async userInfoEndpoint(t){var i;if(!((i=this.oidcConfig)!=null&&i.userinfo_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const r=this.oidcConfig.userinfo_endpoint;return await this.post(r,{},{authorization:"Bearer "+t})}async post(t,r,n={},i){l.logger.debug(u({msg:"Fetch POST",url:t,params:Object.keys(r)}));let o={};this.authServerCredentials&&(o.credentials=this.authServerCredentials),this.authServerMode&&(o.mode=this.authServerMode);let s="",a="";if(this.oauthPostType=="json")s=JSON.stringify(r),a="application/json";else{s="";for(let v in r)s!=""&&(s+="&"),s+=encodeURIComponent(v)+"="+encodeURIComponent(r[v]);a="application/x-www-form-urlencoded"}this.oauthLogFetch&&l.logger.debug(u({msg:"OAuth fetch",method:"POST",url:t,body:s}));let d={};i&&(d=i);const f=await fetch(t,{method:"POST",...o,headers:{Accept:"application/json","Content-Type":a,...n},...d,body:s});try{const v=await f.clone().json();return this.oauthLogFetch&&l.logger.debug(u({msg:"OAuth fetch response",body:JSON.stringify(v)})),await f.json(),v}catch(v){let R=p.asCrossauthError(v);throw s=await f.text(),l.logger.debug(u({msg:"Response is not JSON",response:s})),R}}async get(t,r={}){l.logger.debug(u({msg:"Fetch GET",url:t}));let n={};this.authServerCredentials&&(n.credentials=this.authServerCredentials),this.authServerMode&&(n.mode=this.authServerMode),this.oauthLogFetch&&l.logger.debug(u({msg:"OAuth fetch",method:"GET",url:t}));const o=await(await fetch(t,{method:"GET",...n,headers:{Accept:"application/json",...r}})).json();return this.oauthLogFetch&&l.logger.debug(u({msg:"OAuth fetch response",body:JSON.stringify(o)})),o}async validateIdToken(t){try{return await this.tokenConsumer.tokenAuthorized(t,"id")}catch(r){l.logger.debug(u({err:r})),l.logger.error(u({msg:"Id token invalid",cerr:r}));return}}async validateAccessToken(t,r){try{return await this.tokenConsumer.tokenAuthorized(t,"access",r)}catch(n){l.logger.debug(u({err:n})),l.logger.error(u({msg:"Access token invalid",cerr:n}));return}}async idTokenAuthorized(t,r){try{return await this.tokenConsumer.tokenAuthorized(t,"id",r)}catch(n){l.logger.warn(u({err:n})),l.logger.debug(u({err:n}));return}}getTokenPayload(t){return rt(t)}}_=new WeakMap,S=new WeakMap;class nt{constructor(t,r={}){c(this,"audience");c(this,"jwtKeyType");c(this,"jwtSecretKey");c(this,"jwtPublicKey");c(this,"clockTolerance",10);c(this,"authServerBaseUrl","");c(this,"oidcConfig");c(this,"keys",{});if(this.audience=t,r.authServerBaseUrl&&(this.authServerBaseUrl=r.authServerBaseUrl),r.jwtKeyType&&(this.jwtKeyType=r.jwtKeyType),r.jwtSecretKey&&(this.jwtSecretKey=r.jwtSecretKey),r.jwtPublicKey&&(this.jwtPublicKey=r.jwtPublicKey),r.clockTolerance&&(this.clockTolerance=r.clockTolerance),r.oidcConfig&&(this.oidcConfig=r.oidcConfig),this.jwtPublicKey&&!this.jwtKeyType)throw new p(y.Configuration,"If specifying jwtPublic key, must also specify jwtKeyType")}async loadKeys(t){try{if(this.jwtSecretKey){if(!this.jwtKeyType)throw new p(y.Configuration,"Must specify jwtKeyType if setting jwtSecretKey");this.keys._default=await Ve(this.jwtSecretKey,this.jwtKeyType)}else if(this.jwtPublicKey){if(!this.jwtKeyType)throw new p(y.Configuration,"Must specify jwtKeyType if setting jwtPublicKey");const r=await Be(this.jwtPublicKey,this.jwtKeyType);this.keys._default=r}else{if(this.oidcConfig||await this.loadConfig(),!this.oidcConfig)throw new p(y.Connection,"Load OIDC config before Jwks");await this.loadJwks(void 0,t)}}catch(r){throw l.logger.debug(u({err:r})),new p(y.Connection,"Couldn't load keys")}}async loadConfig(t){if(t){this.oidcConfig=t;return}if(!this.authServerBaseUrl)throw new p(y.Connection,"Couldn't get OIDC configuration. Either set authServerBaseUrl or set config manually");let r;try{let n=this.authServerBaseUrl;n.endsWith("/")||(n+="/"),r=await fetch(new URL(".well-known/openid-configuration",n))}catch(n){l.logger.error(u({err:n}))}if(!r||!r.ok)throw new p(y.Connection,"Couldn't get OIDC configuration");this.oidcConfig={...X};try{const n=await r.json();for(const[i,o]of Object.entries(n))this.oidcConfig[i]=o}catch{throw new p(y.Connection,"Unrecognized response from OIDC configuration endpoint")}}async loadJwks(t,r){if(t){this.keys={};for(let n=0;n<t.keys.length;++n){const i=t.keys[n],o="kid"in i&&i.kid?i.kid:"_default";this.keys[o]=await j(t.keys[n])}}else{if(!this.oidcConfig)throw new p(y.Connection,"Load OIDC config before Jwks");let n;try{n=await fetch(new URL(this.oidcConfig.jwks_uri))}catch(i){l.logger.error(u({err:i}))}if(!n||!n.ok)throw new p(y.Connection,"Couldn't get OIDC configuration");this.keys={};try{const i=await n.json();if(!("keys"in i)||!Array.isArray(i.keys))throw new p(y.Connection,"Couldn't fetch keys");for(let o=0;o<i.keys.length;++o)try{let s="_default",a={...i.keys[o]};if("kid"in a&&typeof a.kid=="string"&&(s=String(a.kid)),a&&!a.alg&&!a.jwk_alg&&r)if(r.startsWith("RS")&&a.kty=="RSA")a.alg=r;else{l.logger.debug(u({msg:"Skipping key with "+a.kty}));continue}const d=await j(a);this.keys[s]=d}catch(s){throw l.logger.error(u({err:s})),new p(y.Connection,"Couldn't load keys")}}catch(i){throw l.logger.error(u({err:i})),new p(y.Connection,"Unrecognized response from OIDC jwks endpoint")}}}async tokenAuthorized(t,r,n){if(!this.keys||Object.keys(this.keys).length==0){const o=ie(t);await this.loadKeys(o.alg)}const i=await this.validateToken(t);if(i){if(i.iss!=this.authServerBaseUrl){const o=i.jti?i.jti:i.sid?i.sid:"";l.logger.error(u({msg:`Invalid issuer ${i.iss} ${r} token`,hashedAccessToken:await this.hash(o)}));return}if(n!=!1&&i.aud){const o=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){l.logger.error(u({msg:`Invalid audience ${i.aud} in ${r} token`,hashedAccessToken:await this.hash(o)}));return}}return i}}async validateToken(t){(!this.keys||Object.keys(this.keys).length==0)&&l.logger.warn("No keys loaded so cannot validate tokens");let r;try{r=ie(t).kid}catch{l.logger.warn(u({msg:"Invalid access token format"}));return}let n;for(let i in this.keys)if(r==i){n=this.keys[i];break}if(!n&&"_default"in this.keys&&(n=this.keys._default),!n){l.logger.warn(u({msg:"No matching keys found for access token"}));return}try{const{payload:i}=await tt(t,n),o=JSON.parse(new TextDecoder().decode(i));if(o.exp*1e3<Date.now()+this.clockTolerance){l.logger.warn(u({msg:"Access token has expired"}));return}return o}catch(i){const o=p.asCrossauthError(i);l.logger.debug(u({err:o})),l.logger.warn(u({msg:"Access token did not validate",cerr:o}));return}}}exports.CrossauthError=p;exports.CrossauthLogger=l;exports.DEFAULT_OIDCCONFIG=X;exports.ErrorCode=y;exports.KeyPrefix=A;exports.OAuthClientBase=it;exports.OAuthFlows=Y;exports.OAuthTokenConsumerBase=nt;exports.UserState=T;exports.httpStatus=we;exports.j=u;
@@ -1 +1 @@
1
- var crossauth_common=function(p){"use strict";var rt=Object.defineProperty;var pe=p=>{throw TypeError(p)};var it=(p,g,y)=>g in p?rt(p,g,{enumerable:!0,configurable:!0,writable:!0,value:y}):p[g]=y;var c=(p,g,y)=>it(p,typeof g!="symbol"?g+"":g,y),ge=(p,g,y)=>g.has(p)||pe("Cannot "+y);var w=(p,g,y)=>(ge(p,g,"read from private field"),y?y.call(p):g.get(p)),Q=(p,g,y)=>g.has(p)?pe("Cannot add the same private member more than once"):g instanceof WeakSet?g.add(p):g.set(p,y),M=(p,g,y,_)=>(ge(p,g,"write to private field"),_?_.call(p,y):g.set(p,y),y);var C,I;class g{}c(g,"active","active"),c(g,"disabled","disabled"),c(g,"awaitingTwoFactorSetup","awaitingtwofactorsetup"),c(g,"awaitingTwoFactorSetupAndEmailVerification","awaitingtwofactorsetupandemailverification"),c(g,"awaitingEmailVerification","awaitingemailverification"),c(g,"passwordChangeNeeded","passwordchangeneeded"),c(g,"passwordResetNeeded","passwordresetneeded"),c(g,"factor2ResetNeeded","factor2resetneeded"),c(g,"passwordAndFactor2ResetNeeded","passwordandfactor2resetneeded");class y{}c(y,"session","s:"),c(y,"passwordResetToken","p:"),c(y,"emailVerificationToken","e:"),c(y,"apiKey","api:"),c(y,"authorizationCode","authz:"),c(y,"accessToken","access:"),c(y,"refreshToken","refresh:"),c(y,"mfaToken","omfa:"),c(y,"deviceCode","dc:"),c(y,"userCode","uc:");var _=(e=>(e[e.UserNotExist=0]="UserNotExist",e[e.PasswordInvalid=1]="PasswordInvalid",e[e.EmailNotExist=2]="EmailNotExist",e[e.UsernameOrPasswordInvalid=3]="UsernameOrPasswordInvalid",e[e.InvalidClientId=4]="InvalidClientId",e[e.ClientExists=5]="ClientExists",e[e.InvalidClientSecret=6]="InvalidClientSecret",e[e.InvalidClientIdOrSecret=7]="InvalidClientIdOrSecret",e[e.InvalidRedirectUri=8]="InvalidRedirectUri",e[e.InvalidOAuthFlow=9]="InvalidOAuthFlow",e[e.UserNotActive=10]="UserNotActive",e[e.EmailNotVerified=11]="EmailNotVerified",e[e.TwoFactorIncomplete=12]="TwoFactorIncomplete",e[e.Unauthorized=13]="Unauthorized",e[e.UnauthorizedClient=14]="UnauthorizedClient",e[e.InvalidScope=15]="InvalidScope",e[e.InsufficientScope=16]="InsufficientScope",e[e.InsufficientPriviledges=17]="InsufficientPriviledges",e[e.Forbidden=18]="Forbidden",e[e.InvalidKey=19]="InvalidKey",e[e.InvalidCsrf=20]="InvalidCsrf",e[e.InvalidSession=21]="InvalidSession",e[e.Expired=22]="Expired",e[e.Connection=23]="Connection",e[e.InvalidHash=24]="InvalidHash",e[e.UnsupportedAlgorithm=25]="UnsupportedAlgorithm",e[e.KeyExists=26]="KeyExists",e[e.PasswordChangeNeeded=27]="PasswordChangeNeeded",e[e.PasswordResetNeeded=28]="PasswordResetNeeded",e[e.Factor2ResetNeeded=29]="Factor2ResetNeeded",e[e.Configuration=30]="Configuration",e[e.InvalidEmail=31]="InvalidEmail",e[e.InvalidPhoneNumber=32]="InvalidPhoneNumber",e[e.InvalidUsername=33]="InvalidUsername",e[e.PasswordMatch=34]="PasswordMatch",e[e.InvalidToken=35]="InvalidToken",e[e.MfaRequired=36]="MfaRequired",e[e.PasswordFormat=37]="PasswordFormat",e[e.DataFormat=38]="DataFormat",e[e.FetchError=39]="FetchError",e[e.UserExists=40]="UserExists",e[e.FormEntry=41]="FormEntry",e[e.BadRequest=42]="BadRequest",e[e.AuthorizationPending=43]="AuthorizationPending",e[e.SlowDown=44]="SlowDown",e[e.ExpiredToken=45]="ExpiredToken",e[e.ConstraintViolation=46]="ConstraintViolation",e[e.NotImplemented=47]="NotImplemented",e[e.UnknownError=48]="UnknownError",e))(_||{});class m extends Error{constructor(r,n=void 0){let i,o=500;r==0?(i="User does not exist",o=401):r==1?(i="Password doesn't match",o=401):r==3?(i="Username or password incorrect",o=401):r==4?(i="Client id is invalid",o=401):r==5?(i="Client ID or name already exists",o=500):r==6?(i="Client secret is invalid",o=401):r==7?(i="Client id or secret is invalid",o=401):r==8?(i="Redirect Uri is not registered",o=401):r==9?(i="Invalid OAuth flow type",o=500):r==2?(i="No user exists with that email address",o=401):r==10?(i="Account is not active",o=403):r==33?(i="Username is not in an allowed format",o=400):r==31?(i="Email is not in an allowed format",o=400):r==32?(i="Phone number is not in an allowed format",o=400):r==11?(i="Email address has not been verified",o=403):r==12?(i="Two-factor setup is not complete",o=403):r==13?(i="Not authorized",o=401):r==14?(i="Client not authorized",o=401):r==15?(i="Invalid scope",o=403):r==16?(i="Insufficient scope",o=403):r==23?i="Connection failure":r==22?(i="Token has expired",o=401):r==24?i="Hash is not in a valid format":r==19?(i="Key is invalid",o=401):r==18?(i="You do not have permission to access this resource",o=403):r==17?(i="You do not have the right privileges to access this resource",o=401):r==20?(i="CSRF token is invalid",o=401):r==21?(i="Session cookie is invalid",o=401):r==25?i="Algorithm not supported":r==26?i="Attempt to create a key that already exists":r==27?(i="User must change password",o=403):r==28?(i="User must reset password",o=403):r==29?(i="User must reset 2FA",o=403):r==30?i="There was an error in the configuration":r==34?(i="Passwords do not match",o=401):r==35?(i="Token is not valid",o=401):r==36?(i="MFA is required",o=401):r==37?(i="Password format was incorrect",o=401):r==40?(i="User already exists",o=400):r==42?(i="The request is invalid",o=400):r==38?(i="Session data has unexpected format",o=500):r==39?(i="Couldn't execute a fetch",o=500):r==43?(i="Waiting for authorization",o=200):r==44?(i="Slow polling down by 5 seconds",o=200):r==45?(i="Token has expired",o=401):r==46?(i="Database update/insert caused a constraint violation",o=500):r==47?(i="This method has not been implemented",o=500):(i="Unknown error",o=500),n!=null&&!Array.isArray(n)?i=n:Array.isArray(n)&&(i=n.join(". "));super(i);c(this,"isCrossauthError",!0);c(this,"httpStatus");c(this,"code");c(this,"codeName");c(this,"messages");this.code=r,this.codeName=_[r],this.httpStatus=o,this.name="CrossauthError",Array.isArray(n)?this.messages=n:this.messages=[i],Object.setPrototypeOf(this,m.prototype)}static fromOAuthError(r,n){let i;switch(r){case"invalid_request":i=42;break;case"unauthorized_client":i=14;break;case"access_denied":i=13;break;case"unsupported_response_type":i=42;break;case"invalid_scope":i=15;break;case"server_error":i=48;break;case"temporarily_unavailable":i=23;break;case"invalid_token":i=35;break;case"expired_token":i=45;break;case"insufficient_scope":i=35;break;case"mfa_required":i=36;break;case"authorization_pending":i=43;break;case"slow_down":i=44;break;default:i=48}return new m(i,n)}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(r,n){if(r instanceof Error)return"isCrossauthError"in r?r:new m(48,r.message);if("errorCode"in r){let o=48;try{o=Number(r.errorCode)??48}catch{}let s=n??_[o];return"errorMessage"in r?s=r.errorMessage:"message"in r&&(s=r.message),new m(o,s)}let i=n??_[48];return"message"in r&&(i=r.message),new m(48,i)}}function ye(e){return typeof e=="number"&&(e=""+e),e in B?B[e]:B[500]}const B={200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Unused",307:"Temporary Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Required",413:"Request Entry Too Large",414:"Request-URI Too Long",415:"Unsupported Media Type",416:"Requested Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",429:"Too Many Requests",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported"},b=class b{constructor(t){c(this,"level");if(t)this.level=t;else if(typeof process<"u"&&"CROSSAUTH_LOG_LEVEL"in process.env){const r=(process.env.CROSSAUTH_LOG_LEVEL??"ERROR").toUpperCase();b.levelName.includes(r)?this.level=b.levelName.indexOf(r):this.level=b.Error}else this.level=b.Error}static get logger(){return globalThis.crossauthLogger}setLevel(t){this.level=t}log(t,r){t<=this.level&&(typeof r=="string"?console.log("Crossauth "+b.levelName[t]+" "+new Date().toISOString(),r):console.log(JSON.stringify({level:b.levelName[t],time:new Date().toISOString(),...r})))}error(t){this.log(b.Error,t)}warn(t){this.log(b.Warn,t)}info(t){this.log(b.Info,t)}debug(t){this.log(b.Debug,t)}static setLogger(t,r){globalThis.crossauthLogger=t,globalThis.crossauthLoggerAcceptsJson=r}};c(b,"None",0),c(b,"Error",1),c(b,"Warn",2),c(b,"Info",3),c(b,"Debug",4),c(b,"levelName",["NONE","ERROR","WARN","INFO","DEBUG"]);let l=b;function u(e){let t;typeof e=="object"&&"err"in e&&typeof e.err=="object"&&(t=e.err.stack);try{typeof e=="object"&&"err"in e&&typeof e.err=="object"&&e.err&&"message"in e.err&&!("msg"in e)&&(e.msg=e.err.message)}catch{}try{typeof e=="object"&&"err"in e&&typeof e.err=="object"&&(e.err={...e.err,stack:t})}catch{}try{typeof e=="object"&&"err"in e&&!("msg"in e)&&(e.msg=e.msg="An unknown error occurred")}catch{}try{typeof e=="object"&&"cerr"in e&&"isCrossauthError"in e.cerr&&e.cerr&&(e.errorCode=e.cerr.code,e.errorCodeName=e.cerr.codeName,e.httpStatus=e.cerr.httpStatus,"msg"in e||(e.msg=e.cerr.message),delete e.cerr)}catch{}return typeof e=="string"||globalThis.crossauthLoggerAcceptsJson?e:JSON.stringify(e)}globalThis.crossauthLogger=new l,globalThis.crossauthLoggerAcceptsJson=!0;const V={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},L=crypto,Z=e=>e instanceof CryptoKey,F=new TextEncoder,z=new TextDecoder;function me(...e){const t=e.reduce((i,{length:o})=>i+o,0),r=new Uint8Array(t);let n=0;for(const i of e)r.set(i,n),n+=i.length;return r}const we=e=>{const t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r},P=e=>{let t=e;t instanceof Uint8Array&&(t=z.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return we(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class A extends Error{constructor(t,r){var n;super(t,r),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(n=Error.captureStackTrace)==null||n.call(Error,this,this.constructor)}}A.code="ERR_JOSE_GENERIC";class _e extends A{constructor(t,r,n="unspecified",i="unspecified"){super(t,{cause:{claim:n,reason:i,payload:r}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=n,this.reason=i,this.payload=r}}_e.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class ve extends A{constructor(t,r,n="unspecified",i="unspecified"){super(t,{cause:{claim:n,reason:i,payload:r}}),this.code="ERR_JWT_EXPIRED",this.claim=n,this.reason=i,this.payload=r}}ve.code="ERR_JWT_EXPIRED";class Se extends A{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}Se.code="ERR_JOSE_ALG_NOT_ALLOWED";class T extends A{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}T.code="ERR_JOSE_NOT_SUPPORTED";class be extends A{constructor(t="decryption operation failed",r){super(t,r),this.code="ERR_JWE_DECRYPTION_FAILED"}}be.code="ERR_JWE_DECRYPTION_FAILED";class Ce extends A{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}Ce.code="ERR_JWE_INVALID";class S extends A{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}S.code="ERR_JWS_INVALID";class k extends A{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}k.code="ERR_JWT_INVALID";class Ae extends A{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}Ae.code="ERR_JWK_INVALID";class Ie extends A{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}Ie.code="ERR_JWKS_INVALID";class Ee extends A{constructor(t="no applicable key found in the JSON Web Key Set",r){super(t,r),this.code="ERR_JWKS_NO_MATCHING_KEY"}}Ee.code="ERR_JWKS_NO_MATCHING_KEY";class Te extends A{constructor(t="multiple matching keys found in the JSON Web Key Set",r){super(t,r),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}Te.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class Re extends A{constructor(t="request timed out",r){super(t,r),this.code="ERR_JWKS_TIMEOUT"}}Re.code="ERR_JWKS_TIMEOUT";class ee extends A{constructor(t="signature verification failed",r){super(t,r),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}ee.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function R(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function H(e,t){return e.name===t}function j(e){return parseInt(e.name.slice(4),10)}function Pe(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function ke(e,t){if(t.length&&!t.some(r=>e.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(t.length>2){const n=t.pop();r+=`one of ${t.join(", ")}, or ${n}.`}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}function Ke(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!H(e.algorithm,"HMAC"))throw R("HMAC");const n=parseInt(t.slice(2),10);if(j(e.algorithm.hash)!==n)throw R(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!H(e.algorithm,"RSASSA-PKCS1-v1_5"))throw R("RSASSA-PKCS1-v1_5");const n=parseInt(t.slice(2),10);if(j(e.algorithm.hash)!==n)throw R(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!H(e.algorithm,"RSA-PSS"))throw R("RSA-PSS");const n=parseInt(t.slice(2),10);if(j(e.algorithm.hash)!==n)throw R(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw R("Ed25519 or Ed448");break}case"Ed25519":{if(!H(e.algorithm,"Ed25519"))throw R("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!H(e.algorithm,"ECDSA"))throw R("ECDSA");const n=Pe(t);if(e.algorithm.namedCurve!==n)throw R(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}ke(e,r)}function te(e,t,...r){var n;if(r=r.filter(Boolean),r.length>2){const i=r.pop();e+=`one of type ${r.join(", ")}, or ${i}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&(n=t.constructor)!=null&&n.name&&(e+=` Received an instance of ${t.constructor.name}`),e}const re=(e,...t)=>te("Key must be ",e,...t);function ie(e,t,...r){return te(`Key for the ${e} algorithm must be `,t,...r)}const ne=e=>Z(e)?!0:(e==null?void 0:e[Symbol.toStringTag])==="KeyObject",q=["CryptoKey"],Oe=(...e)=>{const t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(const n of t){const i=Object.keys(n);if(!r||r.size===0){r=new Set(i);continue}for(const o of i){if(r.has(o))return!1;r.add(o)}}return!0};function Ne(e){return typeof e=="object"&&e!==null}function W(e){if(!Ne(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}const We=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};function J(e){return W(e)&&typeof e.kty=="string"}function Je(e){return e.kty!=="oct"&&typeof e.d=="string"}function Ue(e){return e.kty!=="oct"&&typeof e.d>"u"}function De(e){return J(e)&&e.kty==="oct"&&typeof e.k=="string"}function xe(e){let t,r;switch(e.kty){case"RSA":{switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new T('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new T('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(e.alg){case"Ed25519":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"EdDSA":t={name:e.crv},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new T('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new T('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}const oe=async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:r}=xe(e),n=[t,e.ext??!1,e.key_ops??r],i={...e};return delete i.alg,delete i.use,L.subtle.importKey("jwk",i,...n)},se=e=>P(e);let U,D;const ae=e=>(e==null?void 0:e[Symbol.toStringTag])==="KeyObject",$=async(e,t,r,n,i=!1)=>{let o=e.get(t);if(o!=null&&o[n])return o[n];const s=await oe({...r,alg:n});return i&&Object.freeze(t),o?o[n]=s:e.set(t,{[n]:s}),s},ze={normalizePublicKey:(e,t)=>{if(ae(e)){let r=e.export({format:"jwk"});return delete r.d,delete r.dp,delete r.dq,delete r.p,delete r.q,delete r.qi,r.k?se(r.k):(D||(D=new WeakMap),$(D,e,r,t))}return J(e)?e.k?P(e.k):(D||(D=new WeakMap),$(D,e,e,t,!0)):e},normalizePrivateKey:(e,t)=>{if(ae(e)){let r=e.export({format:"jwk"});return r.k?se(r.k):(U||(U=new WeakMap),$(U,e,r,t))}return J(e)?e.k?P(e.k):(U||(U=new WeakMap),$(U,e,e,t,!0)):e}},K=(e,t,r=0)=>{r===0&&(t.unshift(t.length),t.unshift(6));const n=e.indexOf(t[0],r);if(n===-1)return!1;const i=e.subarray(n,n+t.length);return i.length!==t.length?!1:i.every((o,s)=>o===t[s])||K(e,t,n+1)},ce=e=>{switch(!0){case K(e,[42,134,72,206,61,3,1,7]):return"P-256";case K(e,[43,129,4,0,34]):return"P-384";case K(e,[43,129,4,0,35]):return"P-521";case K(e,[43,101,110]):return"X25519";case K(e,[43,101,111]):return"X448";case K(e,[43,101,112]):return"Ed25519";case K(e,[43,101,113]):return"Ed448";default:throw new T("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},de=async(e,t,r,n,i)=>{let o,s;const a=new Uint8Array(atob(r.replace(e,"")).split("").map(f=>f.charCodeAt(0))),d=t==="spki";switch(n){case"PS256":case"PS384":case"PS512":o={name:"RSA-PSS",hash:`SHA-${n.slice(-3)}`},s=d?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":o={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.slice(-3)}`},s=d?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":o={name:"RSA-OAEP",hash:`SHA-${parseInt(n.slice(-3),10)||1}`},s=d?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":o={name:"ECDSA",namedCurve:"P-256"},s=d?["verify"]:["sign"];break;case"ES384":o={name:"ECDSA",namedCurve:"P-384"},s=d?["verify"]:["sign"];break;case"ES512":o={name:"ECDSA",namedCurve:"P-521"},s=d?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{const f=ce(a);o=f.startsWith("P-")?{name:"ECDH",namedCurve:f}:{name:f},s=d?[]:["deriveBits"];break}case"Ed25519":o={name:"Ed25519"},s=d?["verify"]:["sign"];break;case"EdDSA":o={name:ce(a)},s=d?["verify"]:["sign"];break;default:throw new T('Invalid or unsupported "alg" (Algorithm) value')}return L.subtle.importKey(t,a,o,!1,s)},He=(e,t,r)=>de(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t),Me=(e,t,r)=>de(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",e,t);async function Le(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return Me(e,t)}async function Fe(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return He(e,t)}async function G(e,t){if(!W(e))throw new TypeError("JWK must be an object");switch(t||(t=e.alg),e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return P(e.k);case"RSA":if("oth"in e&&e.oth!==void 0)throw new T('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return oe({...e,alg:t});default:throw new T('Unsupported "kty" (Key Type) Parameter value')}}const x=e=>e==null?void 0:e[Symbol.toStringTag],Y=(e,t,r)=>{var n,i;if(t.use!==void 0&&t.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(t.key_ops!==void 0&&((i=(n=t.key_ops).includes)==null?void 0:i.call(n,r))!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},qe=(e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&J(t)){if(De(t)&&Y(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!ne(t))throw new TypeError(ie(e,t,...q,"Uint8Array",n?"JSON Web Key":null));if(t.type!=="secret")throw new TypeError(`${x(t)} instances for symmetric algorithms must be of type "secret"`)}},$e=(e,t,r,n)=>{if(n&&J(t))switch(r){case"sign":if(Je(t)&&Y(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(Ue(t)&&Y(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!ne(t))throw new TypeError(ie(e,t,...q,n?"JSON Web Key":null));if(t.type==="secret")throw new TypeError(`${x(t)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${x(t)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${x(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${x(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${x(t)} instances for asymmetric algorithm encryption must be of type "public"`)};function le(e,t,r,n){t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?qe(t,r,n,e):$e(t,r,n,e)}le.bind(void 0,!1);const ue=le.bind(void 0,!0);function Be(e,t,r,n,i){if(i.crit!==void 0&&(n==null?void 0:n.crit)===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(s=>typeof s!="string"||s.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let o;o=t;for(const s of n.crit){if(!o.has(s))throw new T(`Extension Header Parameter "${s}" is not recognized`);if(i[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(o.get(s)&&n[s]===void 0)throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return new Set(n.crit)}function Ve(e,t){const r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:t.name};default:throw new T(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function je(e,t,r){if(t=await ze.normalizePublicKey(t,e),Z(t))return Ke(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(re(t,...q));return L.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(re(t,...q,"Uint8Array","JSON Web Key"))}const Ge=async(e,t,r,n)=>{const i=await je(e,t,"verify");We(e,i);const o=Ve(e,i.algorithm);try{return await L.subtle.verify(o,i,r,n)}catch{return!1}};async function Ye(e,t,r){if(!W(e))throw new S("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new S('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new S("JWS Protected Header incorrect type");if(e.payload===void 0)throw new S("JWS Payload missing");if(typeof e.signature!="string")throw new S("JWS Signature missing or incorrect type");if(e.header!==void 0&&!W(e.header))throw new S("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{const tt=P(e.protected);n=JSON.parse(z.decode(tt))}catch{throw new S("JWS Protected Header is invalid")}if(!Oe(n,e.header))throw new S("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const i={...n,...e.header},o=Be(S,new Map([["b64",!0]]),r==null?void 0:r.crit,n,i);let s=!0;if(o.has("b64")&&(s=n.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 e.payload!="string")throw new S("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new S("JWS Payload must be a string or an Uint8Array instance");let d=!1;typeof t=="function"?(t=await t(n,e),d=!0,ue(a,t,"verify"),J(t)&&(t=await G(t,a))):ue(a,t,"verify");const f=me(F.encode(e.protected??""),F.encode("."),typeof e.payload=="string"?F.encode(e.payload):e.payload);let v;try{v=P(e.signature)}catch{throw new S("Failed to base64url decode the signature")}if(!await Ge(a,t,v,f))throw new ee;let E;if(s)try{E=P(e.payload)}catch{throw new S("Failed to base64url decode the payload")}else typeof e.payload=="string"?E=F.encode(e.payload):E=e.payload;const N={payload:E};return e.protected!==void 0&&(N.protectedHeader=n),e.header!==void 0&&(N.unprotectedHeader=e.header),d?{...N,key:t}:N}async function Xe(e,t,r){if(e instanceof Uint8Array&&(e=z.decode(e)),typeof e!="string")throw new S("Compact JWS must be a string or Uint8Array");const{0:n,1:i,2:o,length:s}=e.split(".");if(s!==3)throw new S("Invalid Compact JWS");const a=await Ye({payload:i,protected:n,signature:o},t,r),d={payload:a.payload,protectedHeader:a.protectedHeader};return typeof t=="function"?{...d,key:a.key}:d}const he=P;function fe(e){let t;if(typeof e=="string"){const r=e.split(".");(r.length===3||r.length===5)&&([t]=r)}else if(typeof e=="object"&&e)if("protected"in e)t=e.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof t!="string"||!t)throw new Error;const r=JSON.parse(z.decode(he(t)));if(!W(r))throw new Error;return r}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}function Qe(e){if(typeof e!="string")throw new k("JWTs must use Compact JWS serialization, JWT must be a string");const{1:t,length:r}=e.split(".");if(r===5)throw new k("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new k("Invalid JWT");if(!t)throw new k("JWTs must contain a payload");let n;try{n=he(t)}catch{throw new k("Failed to base64url decode the payload")}let i;try{i=JSON.parse(z.decode(n))}catch{throw new k("Failed to parse the decoded payload as JSON")}if(!W(i))throw new k("Invalid JWT Claims Set");return i}const h=class h{static flowNames(t){let r={};return t.forEach(n=>{n in h.flowName&&(r[n]=h.flowName[n])}),r}static isValidFlow(t){return h.allFlows().includes(t)}static areAllValidFlows(t){let r=!0;return t.forEach(n=>{h.isValidFlow(n)||(r=!1)}),r}static allFlows(){return[h.AuthorizationCode,h.AuthorizationCodeWithPKCE,h.ClientCredentials,h.RefreshToken,h.DeviceCode,h.Password,h.PasswordMfa,h.OidcAuthorizationCode]}static grantType(t){switch(t){case h.AuthorizationCode:case h.AuthorizationCodeWithPKCE:case h.OidcAuthorizationCode:return["authorization_code"];case h.ClientCredentials:return["client_credentials"];case h.RefreshToken:return["refresh_token"];case h.Password:return["password"];case h.PasswordMfa:return["http://auth0.com/oauth/grant-type/mfa-otp","http://auth0.com/oauth/grant-type/mfa-oob"];case h.DeviceCode:return["urn:ietf:params:oauth:grant-type:device_code"]}}};c(h,"All","all"),c(h,"AuthorizationCode","authorizationCode"),c(h,"AuthorizationCodeWithPKCE","authorizationCodeWithPKCE"),c(h,"ClientCredentials","clientCredentials"),c(h,"RefreshToken","refreshToken"),c(h,"DeviceCode","deviceCode"),c(h,"Password","password"),c(h,"PasswordMfa","passwordMfa"),c(h,"OidcAuthorizationCode","oidcAuthorizationCode"),c(h,"flowName",{[h.AuthorizationCode]:"Authorization Code",[h.AuthorizationCodeWithPKCE]:"Authorization Code with PKCE",[h.ClientCredentials]:"Client Credentials",[h.RefreshToken]:"Refresh Token",[h.DeviceCode]:"Device Code",[h.Password]:"Password",[h.PasswordMfa]:"Password MFA",[h.OidcAuthorizationCode]:"OIDC Authorization Code"});let X=h;class Ze{constructor({authServerBaseUrl:t,client_id:r,client_secret:n,redirect_uri:i,codeChallengeMethod:o,stateLength:s,verifierLength:a,tokenConsumer:d,authServerCredentials:f,authServerMode:v,authServerHeaders:O}){c(this,"authServerBaseUrl","");Q(this,C);Q(this,I);c(this,"codeChallengeMethod","S256");c(this,"verifierLength",32);c(this,"redirect_uri");c(this,"stateLength",32);c(this,"authzCode","");c(this,"oidcConfig");c(this,"tokenConsumer");c(this,"authServerHeaders",{});c(this,"authServerMode");c(this,"authServerCredentials");c(this,"oauthPostType","json");c(this,"oauthLogFetch",!1);c(this,"oauthUseUserInfoEndpoint",!1);c(this,"oauthAuthorizeRedirect");this.tokenConsumer=d,this.authServerBaseUrl=t,a&&(this.verifierLength=a),s&&(this.stateLength=s),r&&M(this,C,r),n&&M(this,I,n),i&&(this.redirect_uri=i),o&&(this.codeChallengeMethod=o),this.authServerBaseUrl=t,f&&(this.authServerCredentials=f),v&&(this.authServerMode=v),O&&(this.authServerHeaders=O)}set client_id(t){M(this,C,t)}set client_secret(t){M(this,I,t)}async loadConfig(t){if(t){l.logger.debug(u({msg:"Reading OIDC config locally"})),this.oidcConfig=t;return}let r;try{const n=new URL(this.authServerBaseUrl+"/.well-known/openid-configuration");l.logger.debug(u({msg:`Fetching OIDC config from ${n}`}));let i={headers:this.authServerHeaders};this.authServerMode&&(i.mode=this.authServerMode),this.authServerCredentials&&(i.credentials=this.authServerCredentials),r=await fetch(n,i)}catch(n){l.logger.error(u({err:n}))}if(!r||!r.ok)throw new m(_.Connection,"Couldn't get OIDC configuration from URL"+this.authServerBaseUrl+"/.well-known/openid-configuration");this.oidcConfig={...V};try{const n=await r.json();for(const[i,o]of Object.entries(n))this.oidcConfig[i]=o}catch{throw new m(_.Connection,"Unrecognized response from OIDC configuration endpoint")}}getOidcConfig(){return this.oidcConfig}async startAuthorizationCodeFlow(t,{scope:r,codeChallenge:n,pkce:i=!1,upstream:o}){var d,f,v;if(l.logger.debug(u({msg:"Starting authorization code flow, scope "+r})),this.oidcConfig||await this.loadConfig(),!((d=this.oidcConfig)!=null&&d.response_types_supported.includes("code"))||!((f=this.oidcConfig)!=null&&f.response_modes_supported.includes("query")))return{error:"invalid_request",error_description:"Server does not support authorization code flow"};if(!((v=this.oidcConfig)!=null&&v.authorization_endpoint))return{error:"server_error",error_description:"Cannot get authorize endpoint"};if(!w(this,C))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 s=this.oidcConfig.authorization_endpoint;this.oauthAuthorizeRedirect&&(s=this.oauthAuthorizeRedirect);let a=s+"?response_type=code&client_id="+encodeURIComponent(w(this,C))+"&state="+encodeURIComponent(t)+"&redirect_uri="+encodeURIComponent(this.redirect_uri);return r&&(a+="&scope="+encodeURIComponent(r)),i&&n&&(a+="&code_challenge="+n),{url:a}}async codeChallengeAndVerifier(){const t=this.randomValue(this.verifierLength);return{codeChallenge:this.codeChallengeMethod=="plain"?t:await this.sha256(t),codeVerifier:t}}async getIdPayload(t,r){let n,i;try{let o;if(o=await this.validateIdToken(t),!o)return n="access_denied",i="Invalid ID token received",{error:n,error_description:i};if(r&&this.oauthUseUserInfoEndpoint){const s=await this.userInfoEndpoint(r);if(s.error)return n=s.error,i="Failed getting user info: "+(s.error_description??"unknown error"),{error:n,error_description:i};o={...o,...s}}return{payload:o}}catch(o){const s=m.asCrossauthError(o);return l.logger.debug(u({err:s})),l.logger.error(u({msg:"Couldn't get user info",cerr:s})),n=s.oauthErrorCode,i="Couldn't get user info: "+s.message,{error:n,error_description:i}}}async getAccessPayload(t,r){let n,i;try{let o;return o=await this.validateAccessToken(t,r),o?{payload:o}:(n="access_denied",i="Invalid access token received",{error:n,error_description:i})}catch(o){const s=m.asCrossauthError(o);return l.logger.debug(u({err:s})),l.logger.error(u({msg:"Couldn't get user info",cerr:s})),n=s.oauthErrorCode,i="Couldn't get user info: "+s.message,{error:n,error_description:i}}}async redirectEndpoint({code:t,scope:r,codeVerifier:n,error:i,errorDescription:o}){var v,O;if(this.oidcConfig||await this.loadConfig(),i||!t)return i||(i="server_error"),o||(o="Unknown error"),{error:i,error_description:o};if(this.authzCode=t,!((v=this.oidcConfig)!=null&&v.grant_types_supported.includes("authorization_code")))return{error:"invalid_request",error_description:"Server does not support authorization code grant"};if(!((O=this.oidcConfig)!=null&&O.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const s=this.oidcConfig.token_endpoint;let a,d;a="authorization_code",d=w(this,I);let f={grant_type:a,client_id:w(this,C),code:this.authzCode,redirect_uri:this.redirect_uri};r&&(f.scope=r),d&&(f.client_secret=d),n&&(f.code_verifier=n);try{let E=await this.post(s,f,this.authServerHeaders);if(E.id_token){const N=await this.getIdPayload(E.id_token,E.access_token);if(N.error)return N;E.id_payload=N.payload}return E}catch(E){return l.logger.error(u({err:E})),{error:"server_error",error_description:"Unable to get access token from server"}}}async clientCredentialsFlow(t){var i,o;if(l.logger.debug(u({msg:"Starting client credentials flow"})),this.oidcConfig||await this.loadConfig(),!((i=this.oidcConfig)!=null&&i.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,C))return{error:"invalid_request",error_description:"Cannot make client credentials flow without client id"};const r=this.oidcConfig.token_endpoint;let n={grant_type:"client_credentials",client_id:w(this,C),client_secret:w(this,I)};t&&(n.scope=t);try{let s=await this.post(r,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 l.logger.error(u({err:s})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async passwordFlow(t,r,n){var s,a;if(l.logger.debug(u({msg:"Starting password flow"})),this.oidcConfig||await this.loadConfig(),!((s=this.oidcConfig)!=null&&s.grant_types_supported.includes("password")))return{error:"invalid_request",error_description:"Server does not support password grant"};if(!((a=this.oidcConfig)!=null&&a.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const i=this.oidcConfig.token_endpoint;let o={grant_type:"password",client_id:w(this,C),client_secret:w(this,I),username:t,password:r};n&&(o.scope=n);try{let d=await this.post(i,o,this.authServerHeaders);if(d.id_token){const f=await this.getIdPayload(d.id_token,d.access_token);if(f.error)return f;d.id_payload=f.payload}return d}catch(d){return l.logger.error(u({err:d})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async mfaAuthenticators(t){var o,s,a;if(l.logger.debug(u({msg:"Getting valid MFA authenticators"})),this.oidcConfig||await this.loadConfig(),!((o=this.oidcConfig)!=null&&o.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp"))&&((s=this.oidcConfig)!=null&&s.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-oob")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((a=this.oidcConfig)!=null&&a.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const r=this.oidcConfig.issuer+(this.oidcConfig.issuer.endsWith("/")?"":"/")+"mfa/authenticators",n=await this.get(r,{authorization:"Bearer "+t,...this.authServerHeaders});if(!Array.isArray(n))return{error:"server_error",error_description:"Expected array of authenticators in mfa/authenticators response"};let i=[];for(let d=0;d<n.length;++d){const f=n[d];if(!f.id||!f.authenticator_type||!f.active)return{error:"server_error",error_description:"Invalid mfa/authenticators response"};i.push({id:f.id,authenticator_type:f.authenticator_type,active:f.active,name:f.name,oob_channel:f.oob_channel})}return{authenticators:i}}async mfaOtpRequest(t,r){var o,s;if(l.logger.debug(u({msg:"Making MFA OTB request"})),this.oidcConfig||await this.loadConfig(),!((o=this.oidcConfig)!=null&&o.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((s=this.oidcConfig)!=null&&s.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const n=this.oidcConfig.issuer+(this.oidcConfig.issuer.endsWith("/")?"":"/")+"mfa/challenge",i=await this.post(n,{client_id:w(this,C),client_secret:w(this,I),challenge_type:"otp",mfa_token:t,authenticator_id:r},this.authServerHeaders);return i.challenge_type!="otp"?{error:i.error??"server_error",error_description:i.error_description??"Invalid OTP challenge response"}:i}async mfaOtpComplete(t,r,n){var s,a;if(l.logger.debug(u({msg:"Completing MFA OTP request"})),this.oidcConfig||await this.loadConfig(),!((s=this.oidcConfig)!=null&&s.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((a=this.oidcConfig)!=null&&a.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const i=this.oidcConfig.token_endpoint,o=await this.post(i,{grant_type:"http://auth0.com/oauth/grant-type/mfa-otp",client_id:w(this,C),client_secret:w(this,I),challenge_type:"otp",mfa_token:t,otp:r,scope:n},this.authServerHeaders);if(o.id_token){const d=await this.getIdPayload(o.id_token,o.access_token);if(d.error)return d;o.id_payload=d.payload}return{id_token:o.id_token,access_token:o.access_token,refresh_token:o.refresh_token,expires_in:Number(o.expires_in),scope:o.scope,token_type:o.token_type,error:o.error,error_description:o.error_description}}async mfaOobRequest(t,r){var o,s;if(l.logger.debug(u({msg:"Making MFA OOB request"})),this.oidcConfig||await this.loadConfig(),!((o=this.oidcConfig)!=null&&o.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((s=this.oidcConfig)!=null&&s.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const n=this.oidcConfig.issuer+(this.oidcConfig.issuer.endsWith("/")?"":"/")+"mfa/challenge",i=await this.post(n,{client_id:w(this,C),client_secret:w(this,I),challenge_type:"oob",mfa_token:t,authenticator_id:r},this.authServerHeaders);return i.challenge_type!="oob"||!i.oob_code||!i.binding_method?{error:i.error??"server_error",error_description:i.error_description??"Invalid OOB challenge response"}:{challenge_type:i.challenge_type,oob_code:i.oob_code,binding_method:i.binding_method,error:i.error,error_description:i.error_description}}async mfaOobComplete(t,r,n,i){var a,d;if(l.logger.debug(u({msg:"Completing MFA OOB request"})),this.oidcConfig||await this.loadConfig(),!((a=this.oidcConfig)!=null&&a.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(!((d=this.oidcConfig)!=null&&d.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const o=this.oidcConfig.token_endpoint,s=await this.post(o,{grant_type:"http://auth0.com/oauth/grant-type/mfa-oob",client_id:w(this,C),client_secret:w(this,I),challenge_type:"otp",mfa_token:t,oob_code:r,binding_code:n,scope:i},this.authServerHeaders);if(s.error)return{error:s.error,error_description:s.error_description};if(s.id_token){const f=await this.getIdPayload(s.id_token,s.access_token);if(f.error)return f;s.id_payload=f.payload}return{id_token:s.id_token,access_token:s.access_token,refresh_token:s.refresh_token,expires_in:"expires_in"in s?Number(s.expires_in):void 0,scope:s.scope,token_type:s.token_type}}async refreshTokenFlow(t){var o,s;if(l.logger.debug(u({msg:"Starting refresh token flow"})),this.oidcConfig||await this.loadConfig(),!((o=this.oidcConfig)!=null&&o.grant_types_supported.includes("refresh_token")))return{error:"invalid_request",error_description:"Server does not support refresh_token grant"};if(!((s=this.oidcConfig)!=null&&s.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const r=this.oidcConfig.token_endpoint;let n;n=w(this,I);let i={grant_type:"refresh_token",refresh_token:t,client_id:w(this,C)};n&&(i.client_secret=n);try{let a=await this.post(r,i,this.authServerHeaders);if(a.id_token){const d=await this.getIdPayload(a.id_token,a.access_token);if(d!=null&&d.error)return d;a.id_payload=d==null?void 0:d.payload}return a}catch(a){return l.logger.error(u({err:a})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async startDeviceCodeFlow(t,r){var i;if(l.logger.debug(u({msg:"Starting device code flow"})),this.oidcConfig||await this.loadConfig(),!((i=this.oidcConfig)!=null&&i.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 n={grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:w(this,C),client_secret:w(this,I)};r&&(n.scope=r);try{let o=await this.post(t,n,this.authServerHeaders);return o.id_token&&!await this.validateIdToken(o.id_token)?{error:"access_denied",error_description:"Invalid ID token"}:o}catch(o){return l.logger.error(u({err:o})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async pollDeviceCodeFlow(t){var n,i,o;if(l.logger.debug(u({msg:"Starting device code flow"})),this.oidcConfig||await this.loadConfig(),!((n=this.oidcConfig)!=null&&n.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(!((i=this.oidcConfig)!=null&&i.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};let r={grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:w(this,C),client_secret:w(this,I),device_code:t};try{const s=await this.post((o=this.oidcConfig)==null?void 0:o.token_endpoint,r,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 l.logger.error(u({err:s})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async userInfoEndpoint(t){var i;if(!((i=this.oidcConfig)!=null&&i.userinfo_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const r=this.oidcConfig.userinfo_endpoint;return await this.post(r,{},{authorization:"Bearer "+t})}async post(t,r,n={},i){l.logger.debug(u({msg:"Fetch POST",url:t,params:Object.keys(r)}));let o={};this.authServerCredentials&&(o.credentials=this.authServerCredentials),this.authServerMode&&(o.mode=this.authServerMode);let s="",a="";if(this.oauthPostType=="json")s=JSON.stringify(r),a="application/json";else{s="";for(let v in r)s!=""&&(s+="&"),s+=encodeURIComponent(v)+"="+encodeURIComponent(r[v]);a="application/x-www-form-urlencoded"}this.oauthLogFetch&&l.logger.debug(u({msg:"OAuth fetch",method:"POST",url:t,body:s}));let d={};i&&(d=i);const f=await fetch(t,{method:"POST",...o,headers:{Accept:"application/json","Content-Type":a,...n},...d,body:s});try{const v=await f.clone().json();return this.oauthLogFetch&&l.logger.debug(u({msg:"OAuth fetch response",body:JSON.stringify(v)})),await f.json(),v}catch(v){let O=m.asCrossauthError(v);throw s=await f.text(),l.logger.debug(u({msg:"Response is not JSON",response:s})),O}}async get(t,r={}){l.logger.debug(u({msg:"Fetch GET",url:t}));let n={};this.authServerCredentials&&(n.credentials=this.authServerCredentials),this.authServerMode&&(n.mode=this.authServerMode),this.oauthLogFetch&&l.logger.debug(u({msg:"OAuth fetch",method:"GET",url:t}));const o=await(await fetch(t,{method:"GET",...n,headers:{Accept:"application/json",...r}})).json();return this.oauthLogFetch&&l.logger.debug(u({msg:"OAuth fetch response",body:JSON.stringify(o)})),o}async validateIdToken(t){try{return await this.tokenConsumer.tokenAuthorized(t,"id")}catch(r){l.logger.debug(u({err:r})),l.logger.error(u({msg:"Id token invalid",cerr:r}));return}}async validateAccessToken(t,r){try{return await this.tokenConsumer.tokenAuthorized(t,"access",r)}catch(n){l.logger.debug(u({err:n})),l.logger.error(u({msg:"Access token invalid",cerr:n}));return}}async idTokenAuthorized(t,r){try{return await this.tokenConsumer.tokenAuthorized(t,"id",r)}catch(n){l.logger.warn(u({err:n})),l.logger.debug(u({err:n}));return}}getTokenPayload(t){return Qe(t)}}C=new WeakMap,I=new WeakMap;class et{constructor(t,r={}){c(this,"audience");c(this,"jwtKeyType");c(this,"jwtSecretKey");c(this,"jwtPublicKey");c(this,"clockTolerance",10);c(this,"authServerBaseUrl","");c(this,"oidcConfig");c(this,"keys",{});if(this.audience=t,r.authServerBaseUrl&&(this.authServerBaseUrl=r.authServerBaseUrl),r.jwtKeyType&&(this.jwtKeyType=r.jwtKeyType),r.jwtSecretKey&&(this.jwtSecretKey=r.jwtSecretKey),r.jwtPublicKey&&(this.jwtPublicKey=r.jwtPublicKey),r.clockTolerance&&(this.clockTolerance=r.clockTolerance),r.oidcConfig&&(this.oidcConfig=r.oidcConfig),this.jwtPublicKey&&!this.jwtKeyType)throw new m(_.Configuration,"If specifying jwtPublic key, must also specify jwtKeyType")}async loadKeys(t){try{if(this.jwtSecretKey){if(!this.jwtKeyType)throw new m(_.Configuration,"Must specify jwtKeyType if setting jwtSecretKey");this.keys._default=await Fe(this.jwtSecretKey,this.jwtKeyType)}else if(this.jwtPublicKey){if(!this.jwtKeyType)throw new m(_.Configuration,"Must specify jwtKeyType if setting jwtPublicKey");const r=await Le(this.jwtPublicKey,this.jwtKeyType);this.keys._default=r}else{if(this.oidcConfig||await this.loadConfig(),!this.oidcConfig)throw new m(_.Connection,"Load OIDC config before Jwks");await this.loadJwks(void 0,t)}}catch(r){throw l.logger.debug(u({err:r})),new m(_.Connection,"Couldn't load keys")}}async loadConfig(t){if(t){this.oidcConfig=t;return}if(!this.authServerBaseUrl)throw new m(_.Connection,"Couldn't get OIDC configuration. Either set authServerBaseUrl or set config manually");let r;try{let n=this.authServerBaseUrl;n.endsWith("/")||(n+="/"),r=await fetch(new URL(".well-known/openid-configuration",n))}catch(n){l.logger.error(u({err:n}))}if(!r||!r.ok)throw new m(_.Connection,"Couldn't get OIDC configuration");this.oidcConfig={...V};try{const n=await r.json();for(const[i,o]of Object.entries(n))this.oidcConfig[i]=o}catch{throw new m(_.Connection,"Unrecognized response from OIDC configuration endpoint")}}async loadJwks(t,r){if(t){this.keys={};for(let n=0;n<t.keys.length;++n){const i=t.keys[n],o="kid"in i&&i.kid?i.kid:"_default";this.keys[o]=await G(t.keys[n])}}else{if(!this.oidcConfig)throw new m(_.Connection,"Load OIDC config before Jwks");let n;try{n=await fetch(new URL(this.oidcConfig.jwks_uri))}catch(i){l.logger.error(u({err:i}))}if(!n||!n.ok)throw new m(_.Connection,"Couldn't get OIDC configuration");this.keys={};try{const i=await n.json();if(!("keys"in i)||!Array.isArray(i.keys))throw new m(_.Connection,"Couldn't fetch keys");for(let o=0;o<i.keys.length;++o)try{let s="_default",a={...i.keys[o]};if("kid"in a&&typeof a.kid=="string"&&(s=String(a.kid)),a&&!a.alg&&!a.jwk_alg&&r)if(r.startsWith("RS")&&a.kty=="RSA")a.alg=r;else{l.logger.debug(u({msg:"Skipping key with "+a.kty}));continue}const d=await G(a);this.keys[s]=d}catch(s){throw l.logger.error(u({err:s})),new m(_.Connection,"Couldn't load keys")}}catch(i){throw l.logger.error(u({err:i})),new m(_.Connection,"Unrecognized response from OIDC jwks endpoint")}}}async tokenAuthorized(t,r,n){if(!this.keys||Object.keys(this.keys).length==0){const o=fe(t);await this.loadKeys(o.alg)}const i=await this.validateToken(t);if(i){if(i.iss!=this.authServerBaseUrl){const o=i.jti?i.jti:i.sid?i.sid:"";l.logger.error(u({msg:`Invalid issuer ${i.iss} ${r} token`,hashedAccessToken:await this.hash(o)}));return}if(n!=!1&&i.aud){const o=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){l.logger.error(u({msg:`Invalid audience ${i.aud} in ${r} token`,hashedAccessToken:await this.hash(o)}));return}}return i}}async validateToken(t){(!this.keys||Object.keys(this.keys).length==0)&&l.logger.warn("No keys loaded so cannot validate tokens");let r;try{r=fe(t).kid}catch{l.logger.warn(u({msg:"Invalid access token format"}));return}let n;for(let i in this.keys)if(r==i){n=this.keys[i];break}if(!n&&"_default"in this.keys&&(n=this.keys._default),!n){l.logger.warn(u({msg:"No matching keys found for access token"}));return}try{const{payload:i}=await Xe(t,n),o=JSON.parse(new TextDecoder().decode(i));if(o.exp*1e3<Date.now()+this.clockTolerance){l.logger.warn(u({msg:"Access token has expired"}));return}return o}catch(i){const o=m.asCrossauthError(i);l.logger.debug(u({err:o})),l.logger.warn(u({msg:"Access token did not validate",cerr:o}));return}}}return p.CrossauthError=m,p.CrossauthLogger=l,p.DEFAULT_OIDCCONFIG=V,p.ErrorCode=_,p.KeyPrefix=y,p.OAuthClientBase=Ze,p.OAuthFlows=X,p.OAuthTokenConsumerBase=et,p.UserState=g,p.httpStatus=ye,p.j=u,Object.defineProperty(p,Symbol.toStringTag,{value:"Module"}),p}({});
1
+ var crossauth_common=function(p){"use strict";var rt=Object.defineProperty;var pe=p=>{throw TypeError(p)};var it=(p,g,y)=>g in p?rt(p,g,{enumerable:!0,configurable:!0,writable:!0,value:y}):p[g]=y;var c=(p,g,y)=>it(p,typeof g!="symbol"?g+"":g,y),ge=(p,g,y)=>g.has(p)||pe("Cannot "+y);var w=(p,g,y)=>(ge(p,g,"read from private field"),y?y.call(p):g.get(p)),Q=(p,g,y)=>g.has(p)?pe("Cannot add the same private member more than once"):g instanceof WeakSet?g.add(p):g.set(p,y),M=(p,g,y,_)=>(ge(p,g,"write to private field"),_?_.call(p,y):g.set(p,y),y);var b,I;class g{}c(g,"active","active"),c(g,"disabled","disabled"),c(g,"awaitingTwoFactorSetup","awaitingtwofactorsetup"),c(g,"awaitingTwoFactorSetupAndEmailVerification","awaitingtwofactorsetupandemailverification"),c(g,"awaitingEmailVerification","awaitingemailverification"),c(g,"passwordChangeNeeded","passwordchangeneeded"),c(g,"passwordResetNeeded","passwordresetneeded"),c(g,"factor2ResetNeeded","factor2resetneeded"),c(g,"passwordAndFactor2ResetNeeded","passwordandfactor2resetneeded");class y{}c(y,"session","s:"),c(y,"passwordResetToken","p:"),c(y,"emailVerificationToken","e:"),c(y,"apiKey","api:"),c(y,"authorizationCode","authz:"),c(y,"accessToken","access:"),c(y,"refreshToken","refresh:"),c(y,"mfaToken","omfa:"),c(y,"deviceCode","dc:"),c(y,"userCode","uc:");var _=(e=>(e[e.UserNotExist=0]="UserNotExist",e[e.PasswordInvalid=1]="PasswordInvalid",e[e.EmailNotExist=2]="EmailNotExist",e[e.UsernameOrPasswordInvalid=3]="UsernameOrPasswordInvalid",e[e.InvalidClientId=4]="InvalidClientId",e[e.ClientExists=5]="ClientExists",e[e.InvalidClientSecret=6]="InvalidClientSecret",e[e.InvalidClientIdOrSecret=7]="InvalidClientIdOrSecret",e[e.InvalidRedirectUri=8]="InvalidRedirectUri",e[e.InvalidOAuthFlow=9]="InvalidOAuthFlow",e[e.UserNotActive=10]="UserNotActive",e[e.EmailNotVerified=11]="EmailNotVerified",e[e.TwoFactorIncomplete=12]="TwoFactorIncomplete",e[e.Unauthorized=13]="Unauthorized",e[e.UnauthorizedClient=14]="UnauthorizedClient",e[e.InvalidScope=15]="InvalidScope",e[e.InsufficientScope=16]="InsufficientScope",e[e.InsufficientPriviledges=17]="InsufficientPriviledges",e[e.Forbidden=18]="Forbidden",e[e.InvalidKey=19]="InvalidKey",e[e.InvalidCsrf=20]="InvalidCsrf",e[e.InvalidSession=21]="InvalidSession",e[e.Expired=22]="Expired",e[e.Connection=23]="Connection",e[e.InvalidHash=24]="InvalidHash",e[e.UnsupportedAlgorithm=25]="UnsupportedAlgorithm",e[e.KeyExists=26]="KeyExists",e[e.PasswordChangeNeeded=27]="PasswordChangeNeeded",e[e.PasswordResetNeeded=28]="PasswordResetNeeded",e[e.Factor2ResetNeeded=29]="Factor2ResetNeeded",e[e.Configuration=30]="Configuration",e[e.InvalidEmail=31]="InvalidEmail",e[e.InvalidPhoneNumber=32]="InvalidPhoneNumber",e[e.InvalidUsername=33]="InvalidUsername",e[e.PasswordMatch=34]="PasswordMatch",e[e.InvalidToken=35]="InvalidToken",e[e.MfaRequired=36]="MfaRequired",e[e.PasswordFormat=37]="PasswordFormat",e[e.DataFormat=38]="DataFormat",e[e.FetchError=39]="FetchError",e[e.UserExists=40]="UserExists",e[e.FormEntry=41]="FormEntry",e[e.BadRequest=42]="BadRequest",e[e.AuthorizationPending=43]="AuthorizationPending",e[e.SlowDown=44]="SlowDown",e[e.ExpiredToken=45]="ExpiredToken",e[e.ConstraintViolation=46]="ConstraintViolation",e[e.NotImplemented=47]="NotImplemented",e[e.UnknownError=48]="UnknownError",e))(_||{});class m extends Error{constructor(r,n=void 0){let i,o=500;r==0?(i="User does not exist",o=401):r==1?(i="Password doesn't match",o=401):r==3?(i="Username or password incorrect",o=401):r==4?(i="Client id is invalid",o=401):r==5?(i="Client ID or name already exists",o=500):r==6?(i="Client secret is invalid",o=401):r==7?(i="Client id or secret is invalid",o=401):r==8?(i="Redirect Uri is not registered",o=401):r==9?(i="Invalid OAuth flow type",o=500):r==2?(i="No user exists with that email address",o=401):r==10?(i="Account is not active",o=403):r==33?(i="Username is not in an allowed format",o=400):r==31?(i="Email is not in an allowed format",o=400):r==32?(i="Phone number is not in an allowed format",o=400):r==11?(i="Email address has not been verified",o=403):r==12?(i="Two-factor setup is not complete",o=403):r==13?(i="Not authorized",o=401):r==14?(i="Client not authorized",o=401):r==15?(i="Invalid scope",o=403):r==16?(i="Insufficient scope",o=403):r==23?i="Connection failure":r==22?(i="Token has expired",o=401):r==24?i="Hash is not in a valid format":r==19?(i="Key is invalid",o=401):r==18?(i="You do not have permission to access this resource",o=403):r==17?(i="You do not have the right privileges to access this resource",o=401):r==20?(i="CSRF token is invalid",o=401):r==21?(i="Session cookie is invalid",o=401):r==25?i="Algorithm not supported":r==26?i="Attempt to create a key that already exists":r==27?(i="User must change password",o=403):r==28?(i="User must reset password",o=403):r==29?(i="User must reset 2FA",o=403):r==30?i="There was an error in the configuration":r==34?(i="Passwords do not match",o=401):r==35?(i="Token is not valid",o=401):r==36?(i="MFA is required",o=401):r==37?(i="Password format was incorrect",o=401):r==40?(i="User already exists",o=400):r==42?(i="The request is invalid",o=400):r==38?(i="Session data has unexpected format",o=500):r==39?(i="Couldn't execute a fetch",o=500):r==43?(i="Waiting for authorization",o=200):r==44?(i="Slow polling down by 5 seconds",o=200):r==45?(i="Token has expired",o=401):r==46?(i="Database update/insert caused a constraint violation",o=500):r==47?(i="This method has not been implemented",o=500):(i="Unknown error",o=500),n!=null&&!Array.isArray(n)?i=n:Array.isArray(n)&&(i=n.join(". "));super(i);c(this,"isCrossauthError",!0);c(this,"httpStatus");c(this,"code");c(this,"codeName");c(this,"messages");this.code=r,this.codeName=_[r],this.httpStatus=o,this.name="CrossauthError",Array.isArray(n)?this.messages=n:this.messages=[i],Object.setPrototypeOf(this,m.prototype)}static fromOAuthError(r,n){let i;switch(r){case"invalid_request":i=42;break;case"unauthorized_client":i=14;break;case"access_denied":i=13;break;case"unsupported_response_type":i=42;break;case"invalid_scope":i=15;break;case"server_error":i=48;break;case"temporarily_unavailable":i=23;break;case"invalid_token":i=35;break;case"expired_token":i=45;break;case"insufficient_scope":i=35;break;case"mfa_required":i=36;break;case"authorization_pending":i=43;break;case"slow_down":i=44;break;default:i=48}return new m(i,n)}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(r,n){if(r instanceof Error)return"isCrossauthError"in r?r:new m(48,r.message);if("errorCode"in r){let o=48;try{o=Number(r.errorCode)??48}catch{}let s=n??_[o];return"errorMessage"in r?s=r.errorMessage:"message"in r&&(s=r.message),new m(o,s)}let i=n??_[48];return"message"in r&&(i=r.message),new m(48,i)}}function ye(e){return typeof e=="number"&&(e=""+e),e in B?B[e]:B[500]}const B={200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Unused",307:"Temporary Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Required",413:"Request Entry Too Large",414:"Request-URI Too Long",415:"Unsupported Media Type",416:"Requested Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",429:"Too Many Requests",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported"},S=class S{constructor(t){c(this,"level");if(t)this.level=t;else if(typeof process<"u"&&"CROSSAUTH_LOG_LEVEL"in process.env){const r=(process.env.CROSSAUTH_LOG_LEVEL??"ERROR").toUpperCase();S.levelName.includes(r)?this.level=S.levelName.indexOf(r):this.level=S.Error}else this.level=S.Error}static get logger(){return globalThis.crossauthLogger}setLevel(t){this.level=t}log(t,r){t<=this.level&&(typeof r=="string"?console.log("Crossauth "+S.levelName[t]+" "+new Date().toISOString(),r):console.log(JSON.stringify({level:S.levelName[t],time:new Date().toISOString(),...r})))}error(t){this.log(S.Error,t)}warn(t){this.log(S.Warn,t)}info(t){this.log(S.Info,t)}debug(t){this.log(S.Debug,t)}static setLogger(t,r){globalThis.crossauthLogger=t,globalThis.crossauthLoggerAcceptsJson=r}};c(S,"None",0),c(S,"Error",1),c(S,"Warn",2),c(S,"Info",3),c(S,"Debug",4),c(S,"levelName",["NONE","ERROR","WARN","INFO","DEBUG"]);let l=S;function u(e){let t;typeof e=="object"&&"err"in e&&typeof e.err=="object"&&(t=e.err.stack);try{typeof e=="object"&&"err"in e&&typeof e.err=="object"&&e.err&&"message"in e.err&&!("msg"in e)&&(e.msg=e.err.message)}catch{}try{typeof e=="object"&&"err"in e&&typeof e.err=="object"&&(e.err={...e.err,stack:t})}catch{}try{typeof e=="object"&&"err"in e&&!("msg"in e)&&(e.msg=e.msg="An unknown error occurred")}catch{}try{typeof e=="object"&&"cerr"in e&&"isCrossauthError"in e.cerr&&e.cerr&&(e.errorCode=e.cerr.code,e.errorCodeName=e.cerr.codeName,e.httpStatus=e.cerr.httpStatus,"msg"in e||(e.msg=e.cerr.message),delete e.cerr)}catch{}return typeof e=="string"||globalThis.crossauthLoggerAcceptsJson?e:JSON.stringify(e)}globalThis.crossauthLogger=new l,globalThis.crossauthLoggerAcceptsJson=!0;const V={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},L=crypto,Z=e=>e instanceof CryptoKey,F=new TextEncoder,z=new TextDecoder;function me(...e){const t=e.reduce((i,{length:o})=>i+o,0),r=new Uint8Array(t);let n=0;for(const i of e)r.set(i,n),n+=i.length;return r}const we=e=>{const t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r},P=e=>{let t=e;t instanceof Uint8Array&&(t=z.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return we(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class A extends Error{constructor(t,r){var n;super(t,r),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(n=Error.captureStackTrace)==null||n.call(Error,this,this.constructor)}}A.code="ERR_JOSE_GENERIC";class _e extends A{constructor(t,r,n="unspecified",i="unspecified"){super(t,{cause:{claim:n,reason:i,payload:r}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=n,this.reason=i,this.payload=r}}_e.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class ve extends A{constructor(t,r,n="unspecified",i="unspecified"){super(t,{cause:{claim:n,reason:i,payload:r}}),this.code="ERR_JWT_EXPIRED",this.claim=n,this.reason=i,this.payload=r}}ve.code="ERR_JWT_EXPIRED";class Se extends A{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}Se.code="ERR_JOSE_ALG_NOT_ALLOWED";class T extends A{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}T.code="ERR_JOSE_NOT_SUPPORTED";class be extends A{constructor(t="decryption operation failed",r){super(t,r),this.code="ERR_JWE_DECRYPTION_FAILED"}}be.code="ERR_JWE_DECRYPTION_FAILED";class Ce extends A{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}Ce.code="ERR_JWE_INVALID";class v extends A{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}v.code="ERR_JWS_INVALID";class k extends A{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}k.code="ERR_JWT_INVALID";class Ae extends A{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}Ae.code="ERR_JWK_INVALID";class Ie extends A{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}Ie.code="ERR_JWKS_INVALID";class Ee extends A{constructor(t="no applicable key found in the JSON Web Key Set",r){super(t,r),this.code="ERR_JWKS_NO_MATCHING_KEY"}}Ee.code="ERR_JWKS_NO_MATCHING_KEY";class Te extends A{constructor(t="multiple matching keys found in the JSON Web Key Set",r){super(t,r),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}Te.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class Re extends A{constructor(t="request timed out",r){super(t,r),this.code="ERR_JWKS_TIMEOUT"}}Re.code="ERR_JWKS_TIMEOUT";class ee extends A{constructor(t="signature verification failed",r){super(t,r),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}ee.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function R(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function H(e,t){return e.name===t}function j(e){return parseInt(e.name.slice(4),10)}function Pe(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function ke(e,t){if(t.length&&!t.some(r=>e.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(t.length>2){const n=t.pop();r+=`one of ${t.join(", ")}, or ${n}.`}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}function Ke(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!H(e.algorithm,"HMAC"))throw R("HMAC");const n=parseInt(t.slice(2),10);if(j(e.algorithm.hash)!==n)throw R(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!H(e.algorithm,"RSASSA-PKCS1-v1_5"))throw R("RSASSA-PKCS1-v1_5");const n=parseInt(t.slice(2),10);if(j(e.algorithm.hash)!==n)throw R(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!H(e.algorithm,"RSA-PSS"))throw R("RSA-PSS");const n=parseInt(t.slice(2),10);if(j(e.algorithm.hash)!==n)throw R(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw R("Ed25519 or Ed448");break}case"Ed25519":{if(!H(e.algorithm,"Ed25519"))throw R("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!H(e.algorithm,"ECDSA"))throw R("ECDSA");const n=Pe(t);if(e.algorithm.namedCurve!==n)throw R(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}ke(e,r)}function te(e,t,...r){var n;if(r=r.filter(Boolean),r.length>2){const i=r.pop();e+=`one of type ${r.join(", ")}, or ${i}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&(n=t.constructor)!=null&&n.name&&(e+=` Received an instance of ${t.constructor.name}`),e}const re=(e,...t)=>te("Key must be ",e,...t);function ie(e,t,...r){return te(`Key for the ${e} algorithm must be `,t,...r)}const ne=e=>Z(e)?!0:(e==null?void 0:e[Symbol.toStringTag])==="KeyObject",q=["CryptoKey"],Oe=(...e)=>{const t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(const n of t){const i=Object.keys(n);if(!r||r.size===0){r=new Set(i);continue}for(const o of i){if(r.has(o))return!1;r.add(o)}}return!0};function Ne(e){return typeof e=="object"&&e!==null}function W(e){if(!Ne(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}const We=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};function J(e){return W(e)&&typeof e.kty=="string"}function Je(e){return e.kty!=="oct"&&typeof e.d=="string"}function Ue(e){return e.kty!=="oct"&&typeof e.d>"u"}function De(e){return J(e)&&e.kty==="oct"&&typeof e.k=="string"}function xe(e){let t,r;switch(e.kty){case"RSA":{switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new T('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new T('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(e.alg){case"Ed25519":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"EdDSA":t={name:e.crv},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new T('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new T('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}const oe=async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:r}=xe(e),n=[t,e.ext??!1,e.key_ops??r],i={...e};return delete i.alg,delete i.use,L.subtle.importKey("jwk",i,...n)},se=e=>P(e);let U,D;const ae=e=>(e==null?void 0:e[Symbol.toStringTag])==="KeyObject",$=async(e,t,r,n,i=!1)=>{let o=e.get(t);if(o!=null&&o[n])return o[n];const s=await oe({...r,alg:n});return i&&Object.freeze(t),o?o[n]=s:e.set(t,{[n]:s}),s},ze={normalizePublicKey:(e,t)=>{if(ae(e)){let r=e.export({format:"jwk"});return delete r.d,delete r.dp,delete r.dq,delete r.p,delete r.q,delete r.qi,r.k?se(r.k):(D||(D=new WeakMap),$(D,e,r,t))}return J(e)?e.k?P(e.k):(D||(D=new WeakMap),$(D,e,e,t,!0)):e},normalizePrivateKey:(e,t)=>{if(ae(e)){let r=e.export({format:"jwk"});return r.k?se(r.k):(U||(U=new WeakMap),$(U,e,r,t))}return J(e)?e.k?P(e.k):(U||(U=new WeakMap),$(U,e,e,t,!0)):e}},K=(e,t,r=0)=>{r===0&&(t.unshift(t.length),t.unshift(6));const n=e.indexOf(t[0],r);if(n===-1)return!1;const i=e.subarray(n,n+t.length);return i.length!==t.length?!1:i.every((o,s)=>o===t[s])||K(e,t,n+1)},ce=e=>{switch(!0){case K(e,[42,134,72,206,61,3,1,7]):return"P-256";case K(e,[43,129,4,0,34]):return"P-384";case K(e,[43,129,4,0,35]):return"P-521";case K(e,[43,101,110]):return"X25519";case K(e,[43,101,111]):return"X448";case K(e,[43,101,112]):return"Ed25519";case K(e,[43,101,113]):return"Ed448";default:throw new T("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},de=async(e,t,r,n,i)=>{let o,s;const a=new Uint8Array(atob(r.replace(e,"")).split("").map(f=>f.charCodeAt(0))),d=t==="spki";switch(n){case"PS256":case"PS384":case"PS512":o={name:"RSA-PSS",hash:`SHA-${n.slice(-3)}`},s=d?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":o={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.slice(-3)}`},s=d?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":o={name:"RSA-OAEP",hash:`SHA-${parseInt(n.slice(-3),10)||1}`},s=d?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":o={name:"ECDSA",namedCurve:"P-256"},s=d?["verify"]:["sign"];break;case"ES384":o={name:"ECDSA",namedCurve:"P-384"},s=d?["verify"]:["sign"];break;case"ES512":o={name:"ECDSA",namedCurve:"P-521"},s=d?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{const f=ce(a);o=f.startsWith("P-")?{name:"ECDH",namedCurve:f}:{name:f},s=d?[]:["deriveBits"];break}case"Ed25519":o={name:"Ed25519"},s=d?["verify"]:["sign"];break;case"EdDSA":o={name:ce(a)},s=d?["verify"]:["sign"];break;default:throw new T('Invalid or unsupported "alg" (Algorithm) value')}return L.subtle.importKey(t,a,o,!1,s)},He=(e,t,r)=>de(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t),Me=(e,t,r)=>de(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",e,t);async function Le(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return Me(e,t)}async function Fe(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return He(e,t)}async function G(e,t){if(!W(e))throw new TypeError("JWK must be an object");switch(t||(t=e.alg),e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return P(e.k);case"RSA":if("oth"in e&&e.oth!==void 0)throw new T('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return oe({...e,alg:t});default:throw new T('Unsupported "kty" (Key Type) Parameter value')}}const x=e=>e==null?void 0:e[Symbol.toStringTag],Y=(e,t,r)=>{var n,i;if(t.use!==void 0&&t.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(t.key_ops!==void 0&&((i=(n=t.key_ops).includes)==null?void 0:i.call(n,r))!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},qe=(e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&J(t)){if(De(t)&&Y(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!ne(t))throw new TypeError(ie(e,t,...q,"Uint8Array",n?"JSON Web Key":null));if(t.type!=="secret")throw new TypeError(`${x(t)} instances for symmetric algorithms must be of type "secret"`)}},$e=(e,t,r,n)=>{if(n&&J(t))switch(r){case"sign":if(Je(t)&&Y(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(Ue(t)&&Y(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!ne(t))throw new TypeError(ie(e,t,...q,n?"JSON Web Key":null));if(t.type==="secret")throw new TypeError(`${x(t)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${x(t)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${x(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${x(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${x(t)} instances for asymmetric algorithm encryption must be of type "public"`)};function le(e,t,r,n){t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?qe(t,r,n,e):$e(t,r,n,e)}le.bind(void 0,!1);const ue=le.bind(void 0,!0);function Be(e,t,r,n,i){if(i.crit!==void 0&&(n==null?void 0:n.crit)===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(s=>typeof s!="string"||s.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let o;o=t;for(const s of n.crit){if(!o.has(s))throw new T(`Extension Header Parameter "${s}" is not recognized`);if(i[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(o.get(s)&&n[s]===void 0)throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return new Set(n.crit)}function Ve(e,t){const r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:t.name};default:throw new T(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function je(e,t,r){if(t=await ze.normalizePublicKey(t,e),Z(t))return Ke(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(re(t,...q));return L.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(re(t,...q,"Uint8Array","JSON Web Key"))}const Ge=async(e,t,r,n)=>{const i=await je(e,t,"verify");We(e,i);const o=Ve(e,i.algorithm);try{return await L.subtle.verify(o,i,r,n)}catch{return!1}};async function Ye(e,t,r){if(!W(e))throw new v("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new v('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new v("JWS Protected Header incorrect type");if(e.payload===void 0)throw new v("JWS Payload missing");if(typeof e.signature!="string")throw new v("JWS Signature missing or incorrect type");if(e.header!==void 0&&!W(e.header))throw new v("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{const tt=P(e.protected);n=JSON.parse(z.decode(tt))}catch{throw new v("JWS Protected Header is invalid")}if(!Oe(n,e.header))throw new v("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const i={...n,...e.header},o=Be(v,new Map([["b64",!0]]),r==null?void 0:r.crit,n,i);let s=!0;if(o.has("b64")&&(s=n.b64,typeof s!="boolean"))throw new v('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=i;if(typeof a!="string"||!a)throw new v('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(s){if(typeof e.payload!="string")throw new v("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new v("JWS Payload must be a string or an Uint8Array instance");let d=!1;typeof t=="function"?(t=await t(n,e),d=!0,ue(a,t,"verify"),J(t)&&(t=await G(t,a))):ue(a,t,"verify");const f=me(F.encode(e.protected??""),F.encode("."),typeof e.payload=="string"?F.encode(e.payload):e.payload);let C;try{C=P(e.signature)}catch{throw new v("Failed to base64url decode the signature")}if(!await Ge(a,t,C,f))throw new ee;let E;if(s)try{E=P(e.payload)}catch{throw new v("Failed to base64url decode the payload")}else typeof e.payload=="string"?E=F.encode(e.payload):E=e.payload;const N={payload:E};return e.protected!==void 0&&(N.protectedHeader=n),e.header!==void 0&&(N.unprotectedHeader=e.header),d?{...N,key:t}:N}async function Xe(e,t,r){if(e instanceof Uint8Array&&(e=z.decode(e)),typeof e!="string")throw new v("Compact JWS must be a string or Uint8Array");const{0:n,1:i,2:o,length:s}=e.split(".");if(s!==3)throw new v("Invalid Compact JWS");const a=await Ye({payload:i,protected:n,signature:o},t,r),d={payload:a.payload,protectedHeader:a.protectedHeader};return typeof t=="function"?{...d,key:a.key}:d}const he=P;function fe(e){let t;if(typeof e=="string"){const r=e.split(".");(r.length===3||r.length===5)&&([t]=r)}else if(typeof e=="object"&&e)if("protected"in e)t=e.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof t!="string"||!t)throw new Error;const r=JSON.parse(z.decode(he(t)));if(!W(r))throw new Error;return r}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}function Qe(e){if(typeof e!="string")throw new k("JWTs must use Compact JWS serialization, JWT must be a string");const{1:t,length:r}=e.split(".");if(r===5)throw new k("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new k("Invalid JWT");if(!t)throw new k("JWTs must contain a payload");let n;try{n=he(t)}catch{throw new k("Failed to base64url decode the payload")}let i;try{i=JSON.parse(z.decode(n))}catch{throw new k("Failed to parse the decoded payload as JSON")}if(!W(i))throw new k("Invalid JWT Claims Set");return i}const h=class h{static flowNames(t){let r={};return t.forEach(n=>{n in h.flowName&&(r[n]=h.flowName[n])}),r}static isValidFlow(t){return h.allFlows().includes(t)}static areAllValidFlows(t){let r=!0;return t.forEach(n=>{h.isValidFlow(n)||(r=!1)}),r}static allFlows(){return[h.AuthorizationCode,h.AuthorizationCodeWithPKCE,h.ClientCredentials,h.RefreshToken,h.DeviceCode,h.Password,h.PasswordMfa,h.OidcAuthorizationCode]}static grantType(t){switch(t){case h.AuthorizationCode:case h.AuthorizationCodeWithPKCE:case h.OidcAuthorizationCode:return["authorization_code"];case h.ClientCredentials:return["client_credentials"];case h.RefreshToken:return["refresh_token"];case h.Password:return["password"];case h.PasswordMfa:return["http://auth0.com/oauth/grant-type/mfa-otp","http://auth0.com/oauth/grant-type/mfa-oob"];case h.DeviceCode:return["urn:ietf:params:oauth:grant-type:device_code"]}}};c(h,"All","all"),c(h,"AuthorizationCode","authorizationCode"),c(h,"AuthorizationCodeWithPKCE","authorizationCodeWithPKCE"),c(h,"ClientCredentials","clientCredentials"),c(h,"RefreshToken","refreshToken"),c(h,"DeviceCode","deviceCode"),c(h,"Password","password"),c(h,"PasswordMfa","passwordMfa"),c(h,"OidcAuthorizationCode","oidcAuthorizationCode"),c(h,"flowName",{[h.AuthorizationCode]:"Authorization Code",[h.AuthorizationCodeWithPKCE]:"Authorization Code with PKCE",[h.ClientCredentials]:"Client Credentials",[h.RefreshToken]:"Refresh Token",[h.DeviceCode]:"Device Code",[h.Password]:"Password",[h.PasswordMfa]:"Password MFA",[h.OidcAuthorizationCode]:"OIDC Authorization Code"});let X=h;class Ze{constructor({authServerBaseUrl:t,client_id:r,client_secret:n,redirect_uri:i,codeChallengeMethod:o,stateLength:s,verifierLength:a,tokenConsumer:d,authServerCredentials:f,authServerMode:C,authServerHeaders:O}){c(this,"authServerBaseUrl","");Q(this,b);Q(this,I);c(this,"codeChallengeMethod","S256");c(this,"verifierLength",32);c(this,"redirect_uri");c(this,"stateLength",32);c(this,"authzCode","");c(this,"oidcConfig");c(this,"tokenConsumer");c(this,"authServerHeaders",{});c(this,"authServerMode");c(this,"authServerCredentials");c(this,"oauthPostType","json");c(this,"oauthLogFetch",!1);c(this,"oauthUseUserInfoEndpoint",!1);c(this,"oauthAuthorizeRedirect");this.tokenConsumer=d,this.authServerBaseUrl=t,a&&(this.verifierLength=a),s&&(this.stateLength=s),r&&M(this,b,r),n&&M(this,I,n),i&&(this.redirect_uri=i),o&&(this.codeChallengeMethod=o),this.authServerBaseUrl=t,f&&(this.authServerCredentials=f),C&&(this.authServerMode=C),O&&(this.authServerHeaders=O)}set client_id(t){M(this,b,t)}set client_secret(t){M(this,I,t)}async loadConfig(t){if(t){l.logger.debug(u({msg:"Reading OIDC config locally"})),this.oidcConfig=t;return}let r;try{const n=new URL(this.authServerBaseUrl+"/.well-known/openid-configuration");l.logger.debug(u({msg:`Fetching OIDC config from ${n}`}));let i={headers:this.authServerHeaders};this.authServerMode&&(i.mode=this.authServerMode),this.authServerCredentials&&(i.credentials=this.authServerCredentials),r=await fetch(n,i)}catch(n){l.logger.error(u({err:n}))}if(!r||!r.ok)throw new m(_.Connection,"Couldn't get OIDC configuration from URL"+this.authServerBaseUrl+"/.well-known/openid-configuration");this.oidcConfig={...V};try{const n=await r.json();for(const[i,o]of Object.entries(n))this.oidcConfig[i]=o}catch{throw new m(_.Connection,"Unrecognized response from OIDC configuration endpoint")}}getOidcConfig(){return this.oidcConfig}async startAuthorizationCodeFlow(t,{scope:r,codeChallenge:n,pkce:i=!1}){var a,d,f;if(l.logger.debug(u({msg:"Starting authorization code flow, scope "+r})),this.oidcConfig||await this.loadConfig(),!((a=this.oidcConfig)!=null&&a.response_types_supported.includes("code"))||!((d=this.oidcConfig)!=null&&d.response_modes_supported.includes("query")))return{error:"invalid_request",error_description:"Server does not support authorization code flow"};if(!((f=this.oidcConfig)!=null&&f.authorization_endpoint))return{error:"server_error",error_description:"Cannot get authorize endpoint"};if(!w(this,b))return{error:"invalid_request",error_description:"Cannot make authorization code flow without client id"};if(!this.redirect_uri)return{error:"invalid_request",error_description:"Cannot make authorization code flow without Redirect Uri"};let o=this.oidcConfig.authorization_endpoint;this.oauthAuthorizeRedirect&&(o=this.oauthAuthorizeRedirect);let s=o+"?response_type=code&client_id="+encodeURIComponent(w(this,b))+"&state="+encodeURIComponent(t)+"&redirect_uri="+encodeURIComponent(this.redirect_uri);return r&&(s+="&scope="+encodeURIComponent(r)),i&&n&&(s+="&code_challenge="+n),{url:s}}async codeChallengeAndVerifier(){const t=this.randomValue(this.verifierLength);return{codeChallenge:this.codeChallengeMethod=="plain"?t:await this.sha256(t),codeVerifier:t}}async getIdPayload(t,r){let n,i;try{let o;if(o=await this.validateIdToken(t),!o)return n="access_denied",i="Invalid ID token received",{error:n,error_description:i};if(r&&this.oauthUseUserInfoEndpoint){const s=await this.userInfoEndpoint(r);if(s.error)return n=s.error,i="Failed getting user info: "+(s.error_description??"unknown error"),{error:n,error_description:i};o={...o,...s}}return{payload:o}}catch(o){const s=m.asCrossauthError(o);return l.logger.debug(u({err:s})),l.logger.error(u({msg:"Couldn't get user info",cerr:s})),n=s.oauthErrorCode,i="Couldn't get user info: "+s.message,{error:n,error_description:i}}}async getAccessPayload(t,r){let n,i;try{let o;return o=await this.validateAccessToken(t,r),o?{payload:o}:(n="access_denied",i="Invalid access token received",{error:n,error_description:i})}catch(o){const s=m.asCrossauthError(o);return l.logger.debug(u({err:s})),l.logger.error(u({msg:"Couldn't get user info",cerr:s})),n=s.oauthErrorCode,i="Couldn't get user info: "+s.message,{error:n,error_description:i}}}async redirectEndpoint({code:t,scope:r,codeVerifier:n,error:i,errorDescription:o}){var C,O;if(this.oidcConfig||await this.loadConfig(),i||!t)return i||(i="server_error"),o||(o="Unknown error"),{error:i,error_description:o};if(this.authzCode=t,!((C=this.oidcConfig)!=null&&C.grant_types_supported.includes("authorization_code")))return{error:"invalid_request",error_description:"Server does not support authorization code grant"};if(!((O=this.oidcConfig)!=null&&O.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const s=this.oidcConfig.token_endpoint;let a,d;a="authorization_code",d=w(this,I);let f={grant_type:a,client_id:w(this,b),code:this.authzCode,redirect_uri:this.redirect_uri};r&&(f.scope=r),d&&(f.client_secret=d),n&&(f.code_verifier=n);try{let E=await this.post(s,f,this.authServerHeaders);if(E.id_token){const N=await this.getIdPayload(E.id_token,E.access_token);if(N.error)return N;E.id_payload=N.payload}return E}catch(E){return l.logger.error(u({err:E})),{error:"server_error",error_description:"Unable to get access token from server"}}}async clientCredentialsFlow(t){var i,o;if(l.logger.debug(u({msg:"Starting client credentials flow"})),this.oidcConfig||await this.loadConfig(),!((i=this.oidcConfig)!=null&&i.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,b))return{error:"invalid_request",error_description:"Cannot make client credentials flow without client id"};const r=this.oidcConfig.token_endpoint;let n={grant_type:"client_credentials",client_id:w(this,b),client_secret:w(this,I)};t&&(n.scope=t);try{let s=await this.post(r,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 l.logger.error(u({err:s})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async passwordFlow(t,r,n){var s,a;if(l.logger.debug(u({msg:"Starting password flow"})),this.oidcConfig||await this.loadConfig(),!((s=this.oidcConfig)!=null&&s.grant_types_supported.includes("password")))return{error:"invalid_request",error_description:"Server does not support password grant"};if(!((a=this.oidcConfig)!=null&&a.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const i=this.oidcConfig.token_endpoint;let o={grant_type:"password",client_id:w(this,b),client_secret:w(this,I),username:t,password:r};n&&(o.scope=n);try{let d=await this.post(i,o,this.authServerHeaders);if(d.id_token){const f=await this.getIdPayload(d.id_token,d.access_token);if(f.error)return f;d.id_payload=f.payload}return d}catch(d){return l.logger.error(u({err:d})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async mfaAuthenticators(t){var o,s,a;if(l.logger.debug(u({msg:"Getting valid MFA authenticators"})),this.oidcConfig||await this.loadConfig(),!((o=this.oidcConfig)!=null&&o.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp"))&&((s=this.oidcConfig)!=null&&s.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-oob")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((a=this.oidcConfig)!=null&&a.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const r=this.oidcConfig.issuer+(this.oidcConfig.issuer.endsWith("/")?"":"/")+"mfa/authenticators",n=await this.get(r,{authorization:"Bearer "+t,...this.authServerHeaders});if(!Array.isArray(n))return{error:"server_error",error_description:"Expected array of authenticators in mfa/authenticators response"};let i=[];for(let d=0;d<n.length;++d){const f=n[d];if(!f.id||!f.authenticator_type||!f.active)return{error:"server_error",error_description:"Invalid mfa/authenticators response"};i.push({id:f.id,authenticator_type:f.authenticator_type,active:f.active,name:f.name,oob_channel:f.oob_channel})}return{authenticators:i}}async mfaOtpRequest(t,r){var o,s;if(l.logger.debug(u({msg:"Making MFA OTB request"})),this.oidcConfig||await this.loadConfig(),!((o=this.oidcConfig)!=null&&o.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((s=this.oidcConfig)!=null&&s.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const n=this.oidcConfig.issuer+(this.oidcConfig.issuer.endsWith("/")?"":"/")+"mfa/challenge",i=await this.post(n,{client_id:w(this,b),client_secret:w(this,I),challenge_type:"otp",mfa_token:t,authenticator_id:r},this.authServerHeaders);return i.challenge_type!="otp"?{error:i.error??"server_error",error_description:i.error_description??"Invalid OTP challenge response"}:i}async mfaOtpComplete(t,r,n){var s,a;if(l.logger.debug(u({msg:"Completing MFA OTP request"})),this.oidcConfig||await this.loadConfig(),!((s=this.oidcConfig)!=null&&s.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((a=this.oidcConfig)!=null&&a.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const i=this.oidcConfig.token_endpoint,o=await this.post(i,{grant_type:"http://auth0.com/oauth/grant-type/mfa-otp",client_id:w(this,b),client_secret:w(this,I),challenge_type:"otp",mfa_token:t,otp:r,scope:n},this.authServerHeaders);if(o.id_token){const d=await this.getIdPayload(o.id_token,o.access_token);if(d.error)return d;o.id_payload=d.payload}return{id_token:o.id_token,access_token:o.access_token,refresh_token:o.refresh_token,expires_in:Number(o.expires_in),scope:o.scope,token_type:o.token_type,error:o.error,error_description:o.error_description}}async mfaOobRequest(t,r){var o,s;if(l.logger.debug(u({msg:"Making MFA OOB request"})),this.oidcConfig||await this.loadConfig(),!((o=this.oidcConfig)!=null&&o.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((s=this.oidcConfig)!=null&&s.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const n=this.oidcConfig.issuer+(this.oidcConfig.issuer.endsWith("/")?"":"/")+"mfa/challenge",i=await this.post(n,{client_id:w(this,b),client_secret:w(this,I),challenge_type:"oob",mfa_token:t,authenticator_id:r},this.authServerHeaders);return i.challenge_type!="oob"||!i.oob_code||!i.binding_method?{error:i.error??"server_error",error_description:i.error_description??"Invalid OOB challenge response"}:{challenge_type:i.challenge_type,oob_code:i.oob_code,binding_method:i.binding_method,error:i.error,error_description:i.error_description}}async mfaOobComplete(t,r,n,i){var a,d;if(l.logger.debug(u({msg:"Completing MFA OOB request"})),this.oidcConfig||await this.loadConfig(),!((a=this.oidcConfig)!=null&&a.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(!((d=this.oidcConfig)!=null&&d.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const o=this.oidcConfig.token_endpoint,s=await this.post(o,{grant_type:"http://auth0.com/oauth/grant-type/mfa-oob",client_id:w(this,b),client_secret:w(this,I),challenge_type:"otp",mfa_token:t,oob_code:r,binding_code:n,scope:i},this.authServerHeaders);if(s.error)return{error:s.error,error_description:s.error_description};if(s.id_token){const f=await this.getIdPayload(s.id_token,s.access_token);if(f.error)return f;s.id_payload=f.payload}return{id_token:s.id_token,access_token:s.access_token,refresh_token:s.refresh_token,expires_in:"expires_in"in s?Number(s.expires_in):void 0,scope:s.scope,token_type:s.token_type}}async refreshTokenFlow(t){var o,s;if(l.logger.debug(u({msg:"Starting refresh token flow"})),this.oidcConfig||await this.loadConfig(),!((o=this.oidcConfig)!=null&&o.grant_types_supported.includes("refresh_token")))return{error:"invalid_request",error_description:"Server does not support refresh_token grant"};if(!((s=this.oidcConfig)!=null&&s.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const r=this.oidcConfig.token_endpoint;let n;n=w(this,I);let i={grant_type:"refresh_token",refresh_token:t,client_id:w(this,b)};n&&(i.client_secret=n);try{let a=await this.post(r,i,this.authServerHeaders);if(a.id_token){const d=await this.getIdPayload(a.id_token,a.access_token);if(d!=null&&d.error)return d;a.id_payload=d==null?void 0:d.payload}return a}catch(a){return l.logger.error(u({err:a})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async startDeviceCodeFlow(t,r){var i;if(l.logger.debug(u({msg:"Starting device code flow"})),this.oidcConfig||await this.loadConfig(),!((i=this.oidcConfig)!=null&&i.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 n={grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:w(this,b),client_secret:w(this,I)};r&&(n.scope=r);try{let o=await this.post(t,n,this.authServerHeaders);return o.id_token&&!await this.validateIdToken(o.id_token)?{error:"access_denied",error_description:"Invalid ID token"}:o}catch(o){return l.logger.error(u({err:o})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async pollDeviceCodeFlow(t){var n,i,o;if(l.logger.debug(u({msg:"Starting device code flow"})),this.oidcConfig||await this.loadConfig(),!((n=this.oidcConfig)!=null&&n.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(!((i=this.oidcConfig)!=null&&i.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};let r={grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:w(this,b),client_secret:w(this,I),device_code:t};try{const s=await this.post((o=this.oidcConfig)==null?void 0:o.token_endpoint,r,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 l.logger.error(u({err:s})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async userInfoEndpoint(t){var i;if(!((i=this.oidcConfig)!=null&&i.userinfo_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const r=this.oidcConfig.userinfo_endpoint;return await this.post(r,{},{authorization:"Bearer "+t})}async post(t,r,n={},i){l.logger.debug(u({msg:"Fetch POST",url:t,params:Object.keys(r)}));let o={};this.authServerCredentials&&(o.credentials=this.authServerCredentials),this.authServerMode&&(o.mode=this.authServerMode);let s="",a="";if(this.oauthPostType=="json")s=JSON.stringify(r),a="application/json";else{s="";for(let C in r)s!=""&&(s+="&"),s+=encodeURIComponent(C)+"="+encodeURIComponent(r[C]);a="application/x-www-form-urlencoded"}this.oauthLogFetch&&l.logger.debug(u({msg:"OAuth fetch",method:"POST",url:t,body:s}));let d={};i&&(d=i);const f=await fetch(t,{method:"POST",...o,headers:{Accept:"application/json","Content-Type":a,...n},...d,body:s});try{const C=await f.clone().json();return this.oauthLogFetch&&l.logger.debug(u({msg:"OAuth fetch response",body:JSON.stringify(C)})),await f.json(),C}catch(C){let O=m.asCrossauthError(C);throw s=await f.text(),l.logger.debug(u({msg:"Response is not JSON",response:s})),O}}async get(t,r={}){l.logger.debug(u({msg:"Fetch GET",url:t}));let n={};this.authServerCredentials&&(n.credentials=this.authServerCredentials),this.authServerMode&&(n.mode=this.authServerMode),this.oauthLogFetch&&l.logger.debug(u({msg:"OAuth fetch",method:"GET",url:t}));const o=await(await fetch(t,{method:"GET",...n,headers:{Accept:"application/json",...r}})).json();return this.oauthLogFetch&&l.logger.debug(u({msg:"OAuth fetch response",body:JSON.stringify(o)})),o}async validateIdToken(t){try{return await this.tokenConsumer.tokenAuthorized(t,"id")}catch(r){l.logger.debug(u({err:r})),l.logger.error(u({msg:"Id token invalid",cerr:r}));return}}async validateAccessToken(t,r){try{return await this.tokenConsumer.tokenAuthorized(t,"access",r)}catch(n){l.logger.debug(u({err:n})),l.logger.error(u({msg:"Access token invalid",cerr:n}));return}}async idTokenAuthorized(t,r){try{return await this.tokenConsumer.tokenAuthorized(t,"id",r)}catch(n){l.logger.warn(u({err:n})),l.logger.debug(u({err:n}));return}}getTokenPayload(t){return Qe(t)}}b=new WeakMap,I=new WeakMap;class et{constructor(t,r={}){c(this,"audience");c(this,"jwtKeyType");c(this,"jwtSecretKey");c(this,"jwtPublicKey");c(this,"clockTolerance",10);c(this,"authServerBaseUrl","");c(this,"oidcConfig");c(this,"keys",{});if(this.audience=t,r.authServerBaseUrl&&(this.authServerBaseUrl=r.authServerBaseUrl),r.jwtKeyType&&(this.jwtKeyType=r.jwtKeyType),r.jwtSecretKey&&(this.jwtSecretKey=r.jwtSecretKey),r.jwtPublicKey&&(this.jwtPublicKey=r.jwtPublicKey),r.clockTolerance&&(this.clockTolerance=r.clockTolerance),r.oidcConfig&&(this.oidcConfig=r.oidcConfig),this.jwtPublicKey&&!this.jwtKeyType)throw new m(_.Configuration,"If specifying jwtPublic key, must also specify jwtKeyType")}async loadKeys(t){try{if(this.jwtSecretKey){if(!this.jwtKeyType)throw new m(_.Configuration,"Must specify jwtKeyType if setting jwtSecretKey");this.keys._default=await Fe(this.jwtSecretKey,this.jwtKeyType)}else if(this.jwtPublicKey){if(!this.jwtKeyType)throw new m(_.Configuration,"Must specify jwtKeyType if setting jwtPublicKey");const r=await Le(this.jwtPublicKey,this.jwtKeyType);this.keys._default=r}else{if(this.oidcConfig||await this.loadConfig(),!this.oidcConfig)throw new m(_.Connection,"Load OIDC config before Jwks");await this.loadJwks(void 0,t)}}catch(r){throw l.logger.debug(u({err:r})),new m(_.Connection,"Couldn't load keys")}}async loadConfig(t){if(t){this.oidcConfig=t;return}if(!this.authServerBaseUrl)throw new m(_.Connection,"Couldn't get OIDC configuration. Either set authServerBaseUrl or set config manually");let r;try{let n=this.authServerBaseUrl;n.endsWith("/")||(n+="/"),r=await fetch(new URL(".well-known/openid-configuration",n))}catch(n){l.logger.error(u({err:n}))}if(!r||!r.ok)throw new m(_.Connection,"Couldn't get OIDC configuration");this.oidcConfig={...V};try{const n=await r.json();for(const[i,o]of Object.entries(n))this.oidcConfig[i]=o}catch{throw new m(_.Connection,"Unrecognized response from OIDC configuration endpoint")}}async loadJwks(t,r){if(t){this.keys={};for(let n=0;n<t.keys.length;++n){const i=t.keys[n],o="kid"in i&&i.kid?i.kid:"_default";this.keys[o]=await G(t.keys[n])}}else{if(!this.oidcConfig)throw new m(_.Connection,"Load OIDC config before Jwks");let n;try{n=await fetch(new URL(this.oidcConfig.jwks_uri))}catch(i){l.logger.error(u({err:i}))}if(!n||!n.ok)throw new m(_.Connection,"Couldn't get OIDC configuration");this.keys={};try{const i=await n.json();if(!("keys"in i)||!Array.isArray(i.keys))throw new m(_.Connection,"Couldn't fetch keys");for(let o=0;o<i.keys.length;++o)try{let s="_default",a={...i.keys[o]};if("kid"in a&&typeof a.kid=="string"&&(s=String(a.kid)),a&&!a.alg&&!a.jwk_alg&&r)if(r.startsWith("RS")&&a.kty=="RSA")a.alg=r;else{l.logger.debug(u({msg:"Skipping key with "+a.kty}));continue}const d=await G(a);this.keys[s]=d}catch(s){throw l.logger.error(u({err:s})),new m(_.Connection,"Couldn't load keys")}}catch(i){throw l.logger.error(u({err:i})),new m(_.Connection,"Unrecognized response from OIDC jwks endpoint")}}}async tokenAuthorized(t,r,n){if(!this.keys||Object.keys(this.keys).length==0){const o=fe(t);await this.loadKeys(o.alg)}const i=await this.validateToken(t);if(i){if(i.iss!=this.authServerBaseUrl){const o=i.jti?i.jti:i.sid?i.sid:"";l.logger.error(u({msg:`Invalid issuer ${i.iss} ${r} token`,hashedAccessToken:await this.hash(o)}));return}if(n!=!1&&i.aud){const o=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){l.logger.error(u({msg:`Invalid audience ${i.aud} in ${r} token`,hashedAccessToken:await this.hash(o)}));return}}return i}}async validateToken(t){(!this.keys||Object.keys(this.keys).length==0)&&l.logger.warn("No keys loaded so cannot validate tokens");let r;try{r=fe(t).kid}catch{l.logger.warn(u({msg:"Invalid access token format"}));return}let n;for(let i in this.keys)if(r==i){n=this.keys[i];break}if(!n&&"_default"in this.keys&&(n=this.keys._default),!n){l.logger.warn(u({msg:"No matching keys found for access token"}));return}try{const{payload:i}=await Xe(t,n),o=JSON.parse(new TextDecoder().decode(i));if(o.exp*1e3<Date.now()+this.clockTolerance){l.logger.warn(u({msg:"Access token has expired"}));return}return o}catch(i){const o=m.asCrossauthError(i);l.logger.debug(u({err:o})),l.logger.warn(u({msg:"Access token did not validate",cerr:o}));return}}}return p.CrossauthError=m,p.CrossauthLogger=l,p.DEFAULT_OIDCCONFIG=V,p.ErrorCode=_,p.KeyPrefix=y,p.OAuthClientBase=Ze,p.OAuthFlows=X,p.OAuthTokenConsumerBase=et,p.UserState=g,p.httpStatus=ye,p.j=u,Object.defineProperty(p,Symbol.toStringTag,{value:"Module"}),p}({});
package/dist/index.js CHANGED
@@ -69,7 +69,7 @@ c(I, "refreshToken", "refresh:"), /** OAuth MFA key (used by the password MFA fl
69
69
  c(I, "mfaToken", "omfa:"), /** Device code device code */
70
70
  c(I, "deviceCode", "dc:"), /** Device code flow user code */
71
71
  c(I, "userCode", "uc:");
72
- var m = /* @__PURE__ */ ((e) => (e[e.UserNotExist = 0] = "UserNotExist", e[e.PasswordInvalid = 1] = "PasswordInvalid", e[e.EmailNotExist = 2] = "EmailNotExist", e[e.UsernameOrPasswordInvalid = 3] = "UsernameOrPasswordInvalid", e[e.InvalidClientId = 4] = "InvalidClientId", e[e.ClientExists = 5] = "ClientExists", e[e.InvalidClientSecret = 6] = "InvalidClientSecret", e[e.InvalidClientIdOrSecret = 7] = "InvalidClientIdOrSecret", e[e.InvalidRedirectUri = 8] = "InvalidRedirectUri", e[e.InvalidOAuthFlow = 9] = "InvalidOAuthFlow", e[e.UserNotActive = 10] = "UserNotActive", e[e.EmailNotVerified = 11] = "EmailNotVerified", e[e.TwoFactorIncomplete = 12] = "TwoFactorIncomplete", e[e.Unauthorized = 13] = "Unauthorized", e[e.UnauthorizedClient = 14] = "UnauthorizedClient", e[e.InvalidScope = 15] = "InvalidScope", e[e.InsufficientScope = 16] = "InsufficientScope", e[e.InsufficientPriviledges = 17] = "InsufficientPriviledges", e[e.Forbidden = 18] = "Forbidden", e[e.InvalidKey = 19] = "InvalidKey", e[e.InvalidCsrf = 20] = "InvalidCsrf", e[e.InvalidSession = 21] = "InvalidSession", e[e.Expired = 22] = "Expired", e[e.Connection = 23] = "Connection", e[e.InvalidHash = 24] = "InvalidHash", e[e.UnsupportedAlgorithm = 25] = "UnsupportedAlgorithm", e[e.KeyExists = 26] = "KeyExists", e[e.PasswordChangeNeeded = 27] = "PasswordChangeNeeded", e[e.PasswordResetNeeded = 28] = "PasswordResetNeeded", e[e.Factor2ResetNeeded = 29] = "Factor2ResetNeeded", e[e.Configuration = 30] = "Configuration", e[e.InvalidEmail = 31] = "InvalidEmail", e[e.InvalidPhoneNumber = 32] = "InvalidPhoneNumber", e[e.InvalidUsername = 33] = "InvalidUsername", e[e.PasswordMatch = 34] = "PasswordMatch", e[e.InvalidToken = 35] = "InvalidToken", e[e.MfaRequired = 36] = "MfaRequired", e[e.PasswordFormat = 37] = "PasswordFormat", e[e.DataFormat = 38] = "DataFormat", e[e.FetchError = 39] = "FetchError", e[e.UserExists = 40] = "UserExists", e[e.FormEntry = 41] = "FormEntry", e[e.BadRequest = 42] = "BadRequest", e[e.AuthorizationPending = 43] = "AuthorizationPending", e[e.SlowDown = 44] = "SlowDown", e[e.ExpiredToken = 45] = "ExpiredToken", e[e.ConstraintViolation = 46] = "ConstraintViolation", e[e.NotImplemented = 47] = "NotImplemented", e[e.UnknownError = 48] = "UnknownError", e))(m || {});
72
+ var y = /* @__PURE__ */ ((e) => (e[e.UserNotExist = 0] = "UserNotExist", e[e.PasswordInvalid = 1] = "PasswordInvalid", e[e.EmailNotExist = 2] = "EmailNotExist", e[e.UsernameOrPasswordInvalid = 3] = "UsernameOrPasswordInvalid", e[e.InvalidClientId = 4] = "InvalidClientId", e[e.ClientExists = 5] = "ClientExists", e[e.InvalidClientSecret = 6] = "InvalidClientSecret", e[e.InvalidClientIdOrSecret = 7] = "InvalidClientIdOrSecret", e[e.InvalidRedirectUri = 8] = "InvalidRedirectUri", e[e.InvalidOAuthFlow = 9] = "InvalidOAuthFlow", e[e.UserNotActive = 10] = "UserNotActive", e[e.EmailNotVerified = 11] = "EmailNotVerified", e[e.TwoFactorIncomplete = 12] = "TwoFactorIncomplete", e[e.Unauthorized = 13] = "Unauthorized", e[e.UnauthorizedClient = 14] = "UnauthorizedClient", e[e.InvalidScope = 15] = "InvalidScope", e[e.InsufficientScope = 16] = "InsufficientScope", e[e.InsufficientPriviledges = 17] = "InsufficientPriviledges", e[e.Forbidden = 18] = "Forbidden", e[e.InvalidKey = 19] = "InvalidKey", e[e.InvalidCsrf = 20] = "InvalidCsrf", e[e.InvalidSession = 21] = "InvalidSession", e[e.Expired = 22] = "Expired", e[e.Connection = 23] = "Connection", e[e.InvalidHash = 24] = "InvalidHash", e[e.UnsupportedAlgorithm = 25] = "UnsupportedAlgorithm", e[e.KeyExists = 26] = "KeyExists", e[e.PasswordChangeNeeded = 27] = "PasswordChangeNeeded", e[e.PasswordResetNeeded = 28] = "PasswordResetNeeded", e[e.Factor2ResetNeeded = 29] = "Factor2ResetNeeded", e[e.Configuration = 30] = "Configuration", e[e.InvalidEmail = 31] = "InvalidEmail", e[e.InvalidPhoneNumber = 32] = "InvalidPhoneNumber", e[e.InvalidUsername = 33] = "InvalidUsername", e[e.PasswordMatch = 34] = "PasswordMatch", e[e.InvalidToken = 35] = "InvalidToken", e[e.MfaRequired = 36] = "MfaRequired", e[e.PasswordFormat = 37] = "PasswordFormat", e[e.DataFormat = 38] = "DataFormat", e[e.FetchError = 39] = "FetchError", e[e.UserExists = 40] = "UserExists", e[e.FormEntry = 41] = "FormEntry", e[e.BadRequest = 42] = "BadRequest", e[e.AuthorizationPending = 43] = "AuthorizationPending", e[e.SlowDown = 44] = "SlowDown", e[e.ExpiredToken = 45] = "ExpiredToken", e[e.ConstraintViolation = 46] = "ConstraintViolation", e[e.NotImplemented = 47] = "NotImplemented", e[e.UnknownError = 48] = "UnknownError", e))(y || {});
73
73
  class p extends Error {
74
74
  /**
75
75
  * Creates a new error to throw,
@@ -96,7 +96,7 @@ class p extends Error {
96
96
  * it will be a concatenation of them with `". "` in between.
97
97
  */
98
98
  c(this, "messages");
99
- this.code = r, this.codeName = m[r], this.httpStatus = o, this.name = "CrossauthError", Array.isArray(n) ? this.messages = n : this.messages = [i], Object.setPrototypeOf(this, p.prototype);
99
+ this.code = r, this.codeName = y[r], this.httpStatus = o, this.name = "CrossauthError", Array.isArray(n) ? this.messages = n : this.messages = [i], Object.setPrototypeOf(this, p.prototype);
100
100
  }
101
101
  /**
102
102
  * OAuth defines certain error types. To convert the error in an OAuth
@@ -201,10 +201,10 @@ class p extends Error {
201
201
  o = Number(r.errorCode) ?? 48;
202
202
  } catch {
203
203
  }
204
- let s = n ?? m[o];
204
+ let s = n ?? y[o];
205
205
  return "errorMessage" in r ? s = r.errorMessage : "message" in r && (s = r.message), new p(o, s);
206
206
  }
207
- let i = n ?? m[
207
+ let i = n ?? y[
208
208
  48
209
209
  /* UnknownError */
210
210
  ];
@@ -256,7 +256,7 @@ const B = {
256
256
  503: "Service Unavailable",
257
257
  504: "Gateway Timeout",
258
258
  505: "HTTP Version Not Supported"
259
- }, w = class w {
259
+ }, m = class m {
260
260
  /**
261
261
  * Create a logger with the given level
262
262
  * @param level the level to report to
@@ -267,9 +267,9 @@ const B = {
267
267
  if (t) this.level = t;
268
268
  else if (typeof process < "u" && "CROSSAUTH_LOG_LEVEL" in process.env) {
269
269
  const r = (process.env.CROSSAUTH_LOG_LEVEL ?? "ERROR").toUpperCase();
270
- w.levelName.includes(r) ? this.level = w.levelName.indexOf(r) : this.level = w.Error;
270
+ m.levelName.includes(r) ? this.level = m.levelName.indexOf(r) : this.level = m.Error;
271
271
  } else
272
- this.level = w.Error;
272
+ this.level = m.Error;
273
273
  }
274
274
  /**
275
275
  * Return the singleton instance of the logger.
@@ -282,35 +282,35 @@ const B = {
282
282
  this.level = t;
283
283
  }
284
284
  log(t, r) {
285
- t <= this.level && (typeof r == "string" ? console.log("Crossauth " + w.levelName[t] + " " + (/* @__PURE__ */ new Date()).toISOString(), r) : console.log(JSON.stringify({ level: w.levelName[t], time: (/* @__PURE__ */ new Date()).toISOString(), ...r })));
285
+ t <= this.level && (typeof r == "string" ? console.log("Crossauth " + m.levelName[t] + " " + (/* @__PURE__ */ new Date()).toISOString(), r) : console.log(JSON.stringify({ level: m.levelName[t], time: (/* @__PURE__ */ new Date()).toISOString(), ...r })));
286
286
  }
287
287
  /**
288
288
  * Report an error
289
289
  * @param output object to output
290
290
  */
291
291
  error(t) {
292
- this.log(w.Error, t);
292
+ this.log(m.Error, t);
293
293
  }
294
294
  /**
295
295
  * Report an warning
296
296
  * @param output object to output
297
297
  */
298
298
  warn(t) {
299
- this.log(w.Warn, t);
299
+ this.log(m.Warn, t);
300
300
  }
301
301
  /**
302
302
  * Report information
303
303
  * @param output object to output
304
304
  */
305
305
  info(t) {
306
- this.log(w.Info, t);
306
+ this.log(m.Info, t);
307
307
  }
308
308
  /**
309
309
  * Print a debugging message
310
310
  * @param output object to output
311
311
  */
312
312
  debug(t) {
313
- this.log(w.Debug, t);
313
+ this.log(m.Debug, t);
314
314
  }
315
315
  /**
316
316
  * Override the default logger.
@@ -327,12 +327,12 @@ const B = {
327
327
  }
328
328
  };
329
329
  /** Don't log anything */
330
- c(w, "None", 0), /** Only log errors */
331
- c(w, "Error", 1), /** Log errors and warning */
332
- c(w, "Warn", 2), /** Log errors, warnings and info messages */
333
- c(w, "Info", 3), /** Log everything */
334
- c(w, "Debug", 4), c(w, "levelName", ["NONE", "ERROR", "WARN", "INFO", "DEBUG"]);
335
- let l = w;
330
+ c(m, "None", 0), /** Only log errors */
331
+ c(m, "Error", 1), /** Log errors and warning */
332
+ c(m, "Warn", 2), /** Log errors, warnings and info messages */
333
+ c(m, "Info", 3), /** Log everything */
334
+ c(m, "Debug", 4), c(m, "levelName", ["NONE", "ERROR", "WARN", "INFO", "DEBUG"]);
335
+ let l = m;
336
336
  function u(e) {
337
337
  let t;
338
338
  typeof e == "object" && "err" in e && typeof e.err == "object" && (t = e.err.stack);
@@ -436,12 +436,12 @@ class Ae extends b {
436
436
  }
437
437
  }
438
438
  Ae.code = "ERR_JWE_INVALID";
439
- class _ extends b {
439
+ class w extends b {
440
440
  constructor() {
441
441
  super(...arguments), this.code = "ERR_JWS_INVALID";
442
442
  }
443
443
  }
444
- _.code = "ERR_JWS_INVALID";
444
+ w.code = "ERR_JWS_INVALID";
445
445
  class k extends b {
446
446
  constructor() {
447
447
  super(...arguments), this.code = "ERR_JWT_INVALID";
@@ -963,59 +963,59 @@ const Qe = async (e, t, r, n) => {
963
963
  };
964
964
  async function Ze(e, t, r) {
965
965
  if (!x(e))
966
- throw new _("Flattened JWS must be an object");
966
+ throw new w("Flattened JWS must be an object");
967
967
  if (e.protected === void 0 && e.header === void 0)
968
- throw new _('Flattened JWS must have either of the "protected" or "header" members');
968
+ throw new w('Flattened JWS must have either of the "protected" or "header" members');
969
969
  if (e.protected !== void 0 && typeof e.protected != "string")
970
- throw new _("JWS Protected Header incorrect type");
970
+ throw new w("JWS Protected Header incorrect type");
971
971
  if (e.payload === void 0)
972
- throw new _("JWS Payload missing");
972
+ throw new w("JWS Payload missing");
973
973
  if (typeof e.signature != "string")
974
- throw new _("JWS Signature missing or incorrect type");
974
+ throw new w("JWS Signature missing or incorrect type");
975
975
  if (e.header !== void 0 && !x(e.header))
976
- throw new _("JWS Unprotected Header incorrect type");
976
+ throw new w("JWS Unprotected Header incorrect type");
977
977
  let n = {};
978
978
  if (e.protected)
979
979
  try {
980
980
  const ge = O(e.protected);
981
981
  n = JSON.parse(H.decode(ge));
982
982
  } catch {
983
- throw new _("JWS Protected Header is invalid");
983
+ throw new w("JWS Protected Header is invalid");
984
984
  }
985
985
  if (!Ne(n, e.header))
986
- throw new _("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
986
+ throw new w("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
987
987
  const i = {
988
988
  ...n,
989
989
  ...e.header
990
- }, o = Ge(_, /* @__PURE__ */ new Map([["b64", !0]]), r == null ? void 0 : r.crit, n, i);
990
+ }, o = Ge(w, /* @__PURE__ */ new Map([["b64", !0]]), r == null ? void 0 : r.crit, n, i);
991
991
  let s = !0;
992
992
  if (o.has("b64") && (s = n.b64, typeof s != "boolean"))
993
- throw new _('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
993
+ throw new w('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
994
994
  const { alg: a } = i;
995
995
  if (typeof a != "string" || !a)
996
- throw new _('JWS "alg" (Algorithm) Header Parameter missing or invalid');
996
+ throw new w('JWS "alg" (Algorithm) Header Parameter missing or invalid');
997
997
  if (s) {
998
998
  if (typeof e.payload != "string")
999
- throw new _("JWS Payload must be a string");
999
+ throw new w("JWS Payload must be a string");
1000
1000
  } else if (typeof e.payload != "string" && !(e.payload instanceof Uint8Array))
1001
- throw new _("JWS Payload must be a string or an Uint8Array instance");
1001
+ throw new w("JWS Payload must be a string or an Uint8Array instance");
1002
1002
  let d = !1;
1003
1003
  typeof t == "function" ? (t = await t(n, e), d = !0, ee(a, t, "verify"), U(t) && (t = await j(t, a))) : ee(a, t, "verify");
1004
1004
  const f = we(M.encode(e.protected ?? ""), M.encode("."), typeof e.payload == "string" ? M.encode(e.payload) : e.payload);
1005
- let y;
1005
+ let v;
1006
1006
  try {
1007
- y = O(e.signature);
1007
+ v = O(e.signature);
1008
1008
  } catch {
1009
- throw new _("Failed to base64url decode the signature");
1009
+ throw new w("Failed to base64url decode the signature");
1010
1010
  }
1011
- if (!await Qe(a, t, y, f))
1011
+ if (!await Qe(a, t, v, f))
1012
1012
  throw new oe();
1013
1013
  let C;
1014
1014
  if (s)
1015
1015
  try {
1016
1016
  C = O(e.payload);
1017
1017
  } catch {
1018
- throw new _("Failed to base64url decode the payload");
1018
+ throw new w("Failed to base64url decode the payload");
1019
1019
  }
1020
1020
  else typeof e.payload == "string" ? C = M.encode(e.payload) : C = e.payload;
1021
1021
  const P = { payload: C };
@@ -1023,10 +1023,10 @@ async function Ze(e, t, r) {
1023
1023
  }
1024
1024
  async function et(e, t, r) {
1025
1025
  if (e instanceof Uint8Array && (e = H.decode(e)), typeof e != "string")
1026
- throw new _("Compact JWS must be a string or Uint8Array");
1026
+ throw new w("Compact JWS must be a string or Uint8Array");
1027
1027
  const { 0: n, 1: i, 2: o, length: s } = e.split(".");
1028
1028
  if (s !== 3)
1029
- throw new _("Invalid Compact JWS");
1029
+ throw new w("Invalid Compact JWS");
1030
1030
  const a = await Ze({ payload: i, protected: n, signature: o }, t, r), d = { payload: a.payload, protectedHeader: a.protectedHeader };
1031
1031
  return typeof t == "function" ? { ...d, key: a.key } : d;
1032
1032
  }
@@ -1175,7 +1175,7 @@ c(h, "flowName", {
1175
1175
  [h.OidcAuthorizationCode]: "OIDC Authorization Code"
1176
1176
  });
1177
1177
  let re = h;
1178
- var v, S;
1178
+ var _, S;
1179
1179
  class nt {
1180
1180
  /**
1181
1181
  * Constructor.
@@ -1214,11 +1214,11 @@ class nt {
1214
1214
  verifierLength: a,
1215
1215
  tokenConsumer: d,
1216
1216
  authServerCredentials: f,
1217
- authServerMode: y,
1217
+ authServerMode: v,
1218
1218
  authServerHeaders: T
1219
1219
  }) {
1220
1220
  c(this, "authServerBaseUrl", "");
1221
- $(this, v);
1221
+ $(this, _);
1222
1222
  $(this, S);
1223
1223
  c(this, "codeChallengeMethod", "S256");
1224
1224
  c(this, "verifierLength", 32);
@@ -1234,10 +1234,10 @@ class nt {
1234
1234
  c(this, "oauthLogFetch", !1);
1235
1235
  c(this, "oauthUseUserInfoEndpoint", !1);
1236
1236
  c(this, "oauthAuthorizeRedirect");
1237
- this.tokenConsumer = d, this.authServerBaseUrl = t, a && (this.verifierLength = a), s && (this.stateLength = s), r && D(this, v, r), n && D(this, S, n), i && (this.redirect_uri = i), o && (this.codeChallengeMethod = o), this.authServerBaseUrl = t, f && (this.authServerCredentials = f), y && (this.authServerMode = y), T && (this.authServerHeaders = T);
1237
+ this.tokenConsumer = d, this.authServerBaseUrl = t, a && (this.verifierLength = a), s && (this.stateLength = s), r && D(this, _, r), n && D(this, S, n), i && (this.redirect_uri = i), o && (this.codeChallengeMethod = o), this.authServerBaseUrl = t, f && (this.authServerCredentials = f), v && (this.authServerMode = v), T && (this.authServerHeaders = T);
1238
1238
  }
1239
1239
  set client_id(t) {
1240
- D(this, v, t);
1240
+ D(this, _, t);
1241
1241
  }
1242
1242
  set client_secret(t) {
1243
1243
  D(this, S, t);
@@ -1271,7 +1271,7 @@ class nt {
1271
1271
  }
1272
1272
  if (!r || !r.ok)
1273
1273
  throw new p(
1274
- m.Connection,
1274
+ y.Connection,
1275
1275
  "Couldn't get OIDC configuration from URL" + this.authServerBaseUrl + "/.well-known/openid-configuration"
1276
1276
  );
1277
1277
  this.oidcConfig = { ...ie };
@@ -1281,7 +1281,7 @@ class nt {
1281
1281
  this.oidcConfig[i] = o;
1282
1282
  } catch {
1283
1283
  throw new p(
1284
- m.Connection,
1284
+ y.Connection,
1285
1285
  "Unrecognized response from OIDC configuration endpoint"
1286
1286
  );
1287
1287
  }
@@ -1311,21 +1311,20 @@ class nt {
1311
1311
  async startAuthorizationCodeFlow(t, {
1312
1312
  scope: r,
1313
1313
  codeChallenge: n,
1314
- pkce: i = !1,
1315
- upstream: o
1314
+ pkce: i = !1
1316
1315
  }) {
1317
- var d, f, y;
1318
- if (l.logger.debug(u({ msg: "Starting authorization code flow, scope " + r })), this.oidcConfig || await this.loadConfig(), !((d = this.oidcConfig) != null && d.response_types_supported.includes("code")) || !((f = this.oidcConfig) != null && f.response_modes_supported.includes("query")))
1316
+ var a, d, f;
1317
+ if (l.logger.debug(u({ msg: "Starting authorization code flow, scope " + r })), this.oidcConfig || await this.loadConfig(), !((a = this.oidcConfig) != null && a.response_types_supported.includes("code")) || !((d = this.oidcConfig) != null && d.response_modes_supported.includes("query")))
1319
1318
  return {
1320
1319
  error: "invalid_request",
1321
1320
  error_description: "Server does not support authorization code flow"
1322
1321
  };
1323
- if (!((y = this.oidcConfig) != null && y.authorization_endpoint))
1322
+ if (!((f = this.oidcConfig) != null && f.authorization_endpoint))
1324
1323
  return {
1325
1324
  error: "server_error",
1326
1325
  error_description: "Cannot get authorize endpoint"
1327
1326
  };
1328
- if (!g(this, v)) return {
1327
+ if (!g(this, _)) return {
1329
1328
  error: "invalid_request",
1330
1329
  error_description: "Cannot make authorization code flow without client id"
1331
1330
  };
@@ -1333,10 +1332,10 @@ class nt {
1333
1332
  error: "invalid_request",
1334
1333
  error_description: "Cannot make authorization code flow without Redirect Uri"
1335
1334
  };
1336
- let s = this.oidcConfig.authorization_endpoint;
1337
- this.oauthAuthorizeRedirect && (s = this.oauthAuthorizeRedirect);
1338
- let a = s + "?response_type=code&client_id=" + encodeURIComponent(g(this, v)) + "&state=" + encodeURIComponent(t) + "&redirect_uri=" + encodeURIComponent(this.redirect_uri);
1339
- return r && (a += "&scope=" + encodeURIComponent(r)), i && n && (a += "&code_challenge=" + n), { url: a };
1335
+ let o = this.oidcConfig.authorization_endpoint;
1336
+ this.oauthAuthorizeRedirect && (o = this.oauthAuthorizeRedirect);
1337
+ let s = o + "?response_type=code&client_id=" + encodeURIComponent(g(this, _)) + "&state=" + encodeURIComponent(t) + "&redirect_uri=" + encodeURIComponent(this.redirect_uri);
1338
+ return r && (s += "&scope=" + encodeURIComponent(r)), i && n && (s += "&code_challenge=" + n), { url: s };
1340
1339
  }
1341
1340
  async codeChallengeAndVerifier() {
1342
1341
  const t = this.randomValue(this.verifierLength);
@@ -1397,10 +1396,10 @@ class nt {
1397
1396
  error: i,
1398
1397
  errorDescription: o
1399
1398
  }) {
1400
- var y, T;
1399
+ var v, T;
1401
1400
  if (this.oidcConfig || await this.loadConfig(), i || !t)
1402
1401
  return i || (i = "server_error"), o || (o = "Unknown error"), { error: i, error_description: o };
1403
- if (this.authzCode = t, !((y = this.oidcConfig) != null && y.grant_types_supported.includes("authorization_code")))
1402
+ if (this.authzCode = t, !((v = this.oidcConfig) != null && v.grant_types_supported.includes("authorization_code")))
1404
1403
  return {
1405
1404
  error: "invalid_request",
1406
1405
  error_description: "Server does not support authorization code grant"
@@ -1415,7 +1414,7 @@ class nt {
1415
1414
  a = "authorization_code", d = g(this, S);
1416
1415
  let f = {
1417
1416
  grant_type: a,
1418
- client_id: g(this, v),
1417
+ client_id: g(this, _),
1419
1418
  code: this.authzCode,
1420
1419
  redirect_uri: this.redirect_uri
1421
1420
  };
@@ -1459,14 +1458,14 @@ class nt {
1459
1458
  };
1460
1459
  if (!((o = this.oidcConfig) != null && o.token_endpoint))
1461
1460
  return { error: "server_error", error_description: "Cannot get token endpoint" };
1462
- if (!g(this, v)) return {
1461
+ if (!g(this, _)) return {
1463
1462
  error: "invalid_request",
1464
1463
  error_description: "Cannot make client credentials flow without client id"
1465
1464
  };
1466
1465
  const r = this.oidcConfig.token_endpoint;
1467
1466
  let n = {
1468
1467
  grant_type: "client_credentials",
1469
- client_id: g(this, v),
1468
+ client_id: g(this, _),
1470
1469
  client_secret: g(this, S)
1471
1470
  };
1472
1471
  t && (n.scope = t);
@@ -1516,7 +1515,7 @@ class nt {
1516
1515
  const i = this.oidcConfig.token_endpoint;
1517
1516
  let o = {
1518
1517
  grant_type: "password",
1519
- client_id: g(this, v),
1518
+ client_id: g(this, _),
1520
1519
  client_secret: g(this, S),
1521
1520
  username: t,
1522
1521
  password: r
@@ -1606,7 +1605,7 @@ class nt {
1606
1605
  if (!((s = this.oidcConfig) != null && s.issuer))
1607
1606
  return { error: "server_error", error_description: "Cannot get issuer" };
1608
1607
  const n = this.oidcConfig.issuer + (this.oidcConfig.issuer.endsWith("/") ? "" : "/") + "mfa/challenge", i = await this.post(n, {
1609
- client_id: g(this, v),
1608
+ client_id: g(this, _),
1610
1609
  client_secret: g(this, S),
1611
1610
  challenge_type: "otp",
1612
1611
  mfa_token: t,
@@ -1645,7 +1644,7 @@ class nt {
1645
1644
  return { error: "server_error", error_description: "Cannot get issuer" };
1646
1645
  const i = this.oidcConfig.token_endpoint, o = await this.post(i, {
1647
1646
  grant_type: "http://auth0.com/oauth/grant-type/mfa-otp",
1648
- client_id: g(this, v),
1647
+ client_id: g(this, _),
1649
1648
  client_secret: g(this, S),
1650
1649
  challenge_type: "otp",
1651
1650
  mfa_token: t,
@@ -1697,7 +1696,7 @@ class nt {
1697
1696
  if (!((s = this.oidcConfig) != null && s.issuer))
1698
1697
  return { error: "server_error", error_description: "Cannot get issuer" };
1699
1698
  const n = this.oidcConfig.issuer + (this.oidcConfig.issuer.endsWith("/") ? "" : "/") + "mfa/challenge", i = await this.post(n, {
1700
- client_id: g(this, v),
1699
+ client_id: g(this, _),
1701
1700
  client_secret: g(this, S),
1702
1701
  challenge_type: "oob",
1703
1702
  mfa_token: t,
@@ -1733,7 +1732,7 @@ class nt {
1733
1732
  return { error: "server_error", error_description: "Cannot get issuer" };
1734
1733
  const o = this.oidcConfig.token_endpoint, s = await this.post(o, {
1735
1734
  grant_type: "http://auth0.com/oauth/grant-type/mfa-oob",
1736
- client_id: g(this, v),
1735
+ client_id: g(this, _),
1737
1736
  client_secret: g(this, S),
1738
1737
  challenge_type: "otp",
1739
1738
  mfa_token: t,
@@ -1781,7 +1780,7 @@ class nt {
1781
1780
  let i = {
1782
1781
  grant_type: "refresh_token",
1783
1782
  refresh_token: t,
1784
- client_id: g(this, v)
1783
+ client_id: g(this, _)
1785
1784
  };
1786
1785
  n && (i.client_secret = n);
1787
1786
  try {
@@ -1817,7 +1816,7 @@ class nt {
1817
1816
  };
1818
1817
  let n = {
1819
1818
  grant_type: "urn:ietf:params:oauth:grant-type:device_code",
1820
- client_id: g(this, v),
1819
+ client_id: g(this, _),
1821
1820
  client_secret: g(this, S)
1822
1821
  };
1823
1822
  r && (n.scope = r);
@@ -1852,7 +1851,7 @@ class nt {
1852
1851
  };
1853
1852
  let r = {
1854
1853
  grant_type: "urn:ietf:params:oauth:grant-type:device_code",
1855
- client_id: g(this, v),
1854
+ client_id: g(this, _),
1856
1855
  client_secret: g(this, S),
1857
1856
  device_code: t
1858
1857
  };
@@ -1906,8 +1905,8 @@ class nt {
1906
1905
  s = JSON.stringify(r), a = "application/json";
1907
1906
  else {
1908
1907
  s = "";
1909
- for (let y in r)
1910
- s != "" && (s += "&"), s += encodeURIComponent(y) + "=" + encodeURIComponent(r[y]);
1908
+ for (let v in r)
1909
+ s != "" && (s += "&"), s += encodeURIComponent(v) + "=" + encodeURIComponent(r[v]);
1911
1910
  a = "application/x-www-form-urlencoded";
1912
1911
  }
1913
1912
  this.oauthLogFetch && l.logger.debug(u({ msg: "OAuth fetch", method: "POST", url: t, body: s }));
@@ -1925,10 +1924,10 @@ class nt {
1925
1924
  body: s
1926
1925
  });
1927
1926
  try {
1928
- const y = await f.clone().json();
1929
- return this.oauthLogFetch && l.logger.debug(u({ msg: "OAuth fetch response", body: JSON.stringify(y) })), await f.json(), y;
1930
- } catch (y) {
1931
- let T = p.asCrossauthError(y);
1927
+ const v = await f.clone().json();
1928
+ return this.oauthLogFetch && l.logger.debug(u({ msg: "OAuth fetch response", body: JSON.stringify(v) })), await f.json(), v;
1929
+ } catch (v) {
1930
+ let T = p.asCrossauthError(v);
1932
1931
  throw s = await f.text(), l.logger.debug(u({ msg: "Response is not JSON", response: s })), T;
1933
1932
  }
1934
1933
  }
@@ -2007,7 +2006,7 @@ class nt {
2007
2006
  return tt(t);
2008
2007
  }
2009
2008
  }
2010
- v = new WeakMap(), S = new WeakMap();
2009
+ _ = new WeakMap(), S = new WeakMap();
2011
2010
  class ot {
2012
2011
  /**
2013
2012
  * Constrctor
@@ -2037,7 +2036,7 @@ class ot {
2037
2036
  c(this, "keys", {});
2038
2037
  if (this.audience = t, r.authServerBaseUrl && (this.authServerBaseUrl = r.authServerBaseUrl), r.jwtKeyType && (this.jwtKeyType = r.jwtKeyType), r.jwtSecretKey && (this.jwtSecretKey = r.jwtSecretKey), r.jwtPublicKey && (this.jwtPublicKey = r.jwtPublicKey), r.clockTolerance && (this.clockTolerance = r.clockTolerance), r.oidcConfig && (this.oidcConfig = r.oidcConfig), this.jwtPublicKey && !this.jwtKeyType)
2039
2038
  throw new p(
2040
- m.Configuration,
2039
+ y.Configuration,
2041
2040
  "If specifying jwtPublic key, must also specify jwtKeyType"
2042
2041
  );
2043
2042
  }
@@ -2054,14 +2053,14 @@ class ot {
2054
2053
  if (this.jwtSecretKey) {
2055
2054
  if (!this.jwtKeyType)
2056
2055
  throw new p(
2057
- m.Configuration,
2056
+ y.Configuration,
2058
2057
  "Must specify jwtKeyType if setting jwtSecretKey"
2059
2058
  );
2060
2059
  this.keys._default = await Be(this.jwtSecretKey, this.jwtKeyType);
2061
2060
  } else if (this.jwtPublicKey) {
2062
2061
  if (!this.jwtKeyType)
2063
2062
  throw new p(
2064
- m.Configuration,
2063
+ y.Configuration,
2065
2064
  "Must specify jwtKeyType if setting jwtPublicKey"
2066
2065
  );
2067
2066
  const r = await $e(this.jwtPublicKey, this.jwtKeyType);
@@ -2069,13 +2068,13 @@ class ot {
2069
2068
  } else {
2070
2069
  if (this.oidcConfig || await this.loadConfig(), !this.oidcConfig)
2071
2070
  throw new p(
2072
- m.Connection,
2071
+ y.Connection,
2073
2072
  "Load OIDC config before Jwks"
2074
2073
  );
2075
2074
  await this.loadJwks(void 0, t);
2076
2075
  }
2077
2076
  } catch (r) {
2078
- throw l.logger.debug(u({ err: r })), new p(m.Connection, "Couldn't load keys");
2077
+ throw l.logger.debug(u({ err: r })), new p(y.Connection, "Couldn't load keys");
2079
2078
  }
2080
2079
  }
2081
2080
  /**
@@ -2093,7 +2092,7 @@ class ot {
2093
2092
  return;
2094
2093
  }
2095
2094
  if (!this.authServerBaseUrl)
2096
- throw new p(m.Connection, "Couldn't get OIDC configuration. Either set authServerBaseUrl or set config manually");
2095
+ throw new p(y.Connection, "Couldn't get OIDC configuration. Either set authServerBaseUrl or set config manually");
2097
2096
  let r;
2098
2097
  try {
2099
2098
  let n = this.authServerBaseUrl;
@@ -2102,14 +2101,14 @@ class ot {
2102
2101
  l.logger.error(u({ err: n }));
2103
2102
  }
2104
2103
  if (!r || !r.ok)
2105
- throw new p(m.Connection, "Couldn't get OIDC configuration");
2104
+ throw new p(y.Connection, "Couldn't get OIDC configuration");
2106
2105
  this.oidcConfig = { ...ie };
2107
2106
  try {
2108
2107
  const n = await r.json();
2109
2108
  for (const [i, o] of Object.entries(n))
2110
2109
  this.oidcConfig[i] = o;
2111
2110
  } catch {
2112
- throw new p(m.Connection, "Unrecognized response from OIDC configuration endpoint");
2111
+ throw new p(y.Connection, "Unrecognized response from OIDC configuration endpoint");
2113
2112
  }
2114
2113
  }
2115
2114
  /**
@@ -2130,7 +2129,7 @@ class ot {
2130
2129
  }
2131
2130
  } else {
2132
2131
  if (!this.oidcConfig)
2133
- throw new p(m.Connection, "Load OIDC config before Jwks");
2132
+ throw new p(y.Connection, "Load OIDC config before Jwks");
2134
2133
  let n;
2135
2134
  try {
2136
2135
  n = await fetch(new URL(this.oidcConfig.jwks_uri));
@@ -2138,12 +2137,12 @@ class ot {
2138
2137
  l.logger.error(u({ err: i }));
2139
2138
  }
2140
2139
  if (!n || !n.ok)
2141
- throw new p(m.Connection, "Couldn't get OIDC configuration");
2140
+ throw new p(y.Connection, "Couldn't get OIDC configuration");
2142
2141
  this.keys = {};
2143
2142
  try {
2144
2143
  const i = await n.json();
2145
2144
  if (!("keys" in i) || !Array.isArray(i.keys))
2146
- throw new p(m.Connection, "Couldn't fetch keys");
2145
+ throw new p(y.Connection, "Couldn't fetch keys");
2147
2146
  for (let o = 0; o < i.keys.length; ++o)
2148
2147
  try {
2149
2148
  let s = "_default", a = { ...i.keys[o] };
@@ -2157,10 +2156,10 @@ class ot {
2157
2156
  const d = await j(a);
2158
2157
  this.keys[s] = d;
2159
2158
  } catch (s) {
2160
- throw l.logger.error(u({ err: s })), new p(m.Connection, "Couldn't load keys");
2159
+ throw l.logger.error(u({ err: s })), new p(y.Connection, "Couldn't load keys");
2161
2160
  }
2162
2161
  } catch (i) {
2163
- throw l.logger.error(u({ err: i })), new p(m.Connection, "Unrecognized response from OIDC jwks endpoint");
2162
+ throw l.logger.error(u({ err: i })), new p(y.Connection, "Unrecognized response from OIDC jwks endpoint");
2164
2163
  }
2165
2164
  }
2166
2165
  }
@@ -2234,7 +2233,7 @@ export {
2234
2233
  p as CrossauthError,
2235
2234
  l as CrossauthLogger,
2236
2235
  ie as DEFAULT_OIDCCONFIG,
2237
- m as ErrorCode,
2236
+ y as ErrorCode,
2238
2237
  I as KeyPrefix,
2239
2238
  nt as OAuthClientBase,
2240
2239
  re as OAuthFlows,
package/dist/logger.d.ts CHANGED
@@ -42,7 +42,7 @@ export interface CrossauthLoggerInterface {
42
42
  * - `emailMessageId` : internal id of any email that is sent
43
43
  * - `email` : email address
44
44
  * - `userid` : sometimes provided in addition to username, or when username not available
45
- * - `hahedApiKey` : a hash of an API key. The unhashed version is not logged for security,
45
+ * - `hashedApiKey` : a hash of an API key. The unhashed version is not logged for security,
46
46
  * but a hash of it is logged for correlation purposes.
47
47
  * - `header` : an HTTP header that relates to an error (eg `Authorization`), only if
48
48
  * it is non-secret or invalid
@@ -239,11 +239,10 @@ export declare abstract class OAuthClientBase {
239
239
  * - `error_description` friendly error message or undefined
240
240
  * if no error
241
241
  */
242
- startAuthorizationCodeFlow(state: string, { scope, codeChallenge, pkce, upstream, }: {
242
+ startAuthorizationCodeFlow(state: string, { scope, codeChallenge, pkce, }: {
243
243
  scope?: string;
244
244
  codeChallenge?: string;
245
245
  pkce?: boolean;
246
- upstream?: string;
247
246
  }): Promise<{
248
247
  url?: string;
249
248
  error?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/oauth/client.ts"],"names":[],"mappings":"AAGA,OAAO,EACH,mBAAmB,EACnB,sBAAsB,EAEtB,KAAK,SAAS,EAAE,MAAM,IAAI,CAAC;AAG/B;;GAEG;AACH,qBAAa,UAAU;IAEnB,4BAA4B;IAC5B,MAAM,CAAC,QAAQ,CAAC,GAAG,SAAS;IAE5B,mDAAmD;IACnD,MAAM,CAAC,QAAQ,CAAC,iBAAiB,uBAAuB;IAExD,8CAA8C;IAC9C,MAAM,CAAC,QAAQ,CAAC,yBAAyB,+BAA+B;IAExE,mCAAmC;IACnC,MAAM,CAAC,QAAQ,CAAC,iBAAiB,uBAAuB;IAExD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HANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@crossauth/common",
3
3
  "private": false,
4
- "version": "1.1.7",
4
+ "version": "1.1.8",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
7
7
  "main": "./dist/index.cjs",