@crossauth/common 1.1.8 → 1.1.9

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"},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
+ "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:"),c(A,"knownDevice","kd:");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 P extends C{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}P.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 ke 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"}}ke.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class Pe extends C{constructor(t="request timed out",r){super(t,r),this.code="ERR_JWKS_TIMEOUT"}}Pe.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 k={payload:b};return e.protected!==void 0&&(k.protectedHeader=n),e.header!==void 0&&(k.unprotectedHeader=e.header),d?{...k,key:t}:k}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 P("JWTs must use Compact JWS serialization, JWT must be a string");const{1:t,length:r}=e.split(".");if(r===5)throw new P("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new P("Invalid JWT");if(!t)throw new P("JWTs must contain a payload");let n;try{n=pe(t)}catch{throw new P("Failed to base64url decode the payload")}let i;try{i=JSON.parse(H.decode(n))}catch{throw new P("Failed to parse the decoded payload as JSON")}if(!U(i))throw new P("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 k=await this.getIdPayload(b.id_token,b.access_token);if(k.error)return k;b.id_payload=k.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 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}({});
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:"),c(y,"knownDevice","kd:");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
@@ -56,19 +56,20 @@ c(R, "factor2ResetNeeded", "factor2resetneeded"), /**
56
56
  * Upon login, the user is redirected to the reset password page.
57
57
  */
58
58
  c(R, "passwordAndFactor2ResetNeeded", "passwordandfactor2resetneeded");
59
- class I {
59
+ class A {
60
60
  }
61
61
  /** Session ID */
62
- c(I, "session", "s:"), /** Password Reset Token */
63
- c(I, "passwordResetToken", "p:"), /** Email verification token */
64
- c(I, "emailVerificationToken", "e:"), /** API key */
65
- c(I, "apiKey", "api:"), /** OAuth authorization code */
66
- c(I, "authorizationCode", "authz:"), /** OAuth access token */
67
- c(I, "accessToken", "access:"), /** OAuth refresh token */
68
- c(I, "refreshToken", "refresh:"), /** OAuth MFA key (used by the password MFA flow) */
69
- c(I, "mfaToken", "omfa:"), /** Device code device code */
70
- c(I, "deviceCode", "dc:"), /** Device code flow user code */
71
- c(I, "userCode", "uc:");
62
+ c(A, "session", "s:"), /** Password Reset Token */
63
+ c(A, "passwordResetToken", "p:"), /** Email verification token */
64
+ c(A, "emailVerificationToken", "e:"), /** API key */
65
+ c(A, "apiKey", "api:"), /** OAuth authorization code */
66
+ c(A, "authorizationCode", "authz:"), /** OAuth access token */
67
+ c(A, "accessToken", "access:"), /** OAuth refresh token */
68
+ c(A, "refreshToken", "refresh:"), /** OAuth MFA key (used by the password MFA flow) */
69
+ c(A, "mfaToken", "omfa:"), /** Device code device code */
70
+ c(A, "deviceCode", "dc:"), /** Device code flow user code */
71
+ c(A, "userCode", "uc:"), /** Device code flow user code */
72
+ c(A, "knownDevice", "kd:");
72
73
  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
74
  class p extends Error {
74
75
  /**
@@ -418,12 +419,12 @@ class be extends b {
418
419
  }
419
420
  }
420
421
  be.code = "ERR_JOSE_ALG_NOT_ALLOWED";
421
- class A extends b {
422
+ class I extends b {
422
423
  constructor() {
423
424
  super(...arguments), this.code = "ERR_JOSE_NOT_SUPPORTED";
424
425
  }
425
426
  }
426
- A.code = "ERR_JOSE_NOT_SUPPORTED";
427
+ I.code = "ERR_JOSE_NOT_SUPPORTED";
427
428
  class Ce extends b {
428
429
  constructor(t = "decryption operation failed", r) {
429
430
  super(t, r), this.code = "ERR_JWE_DECRYPTION_FAILED";
@@ -442,12 +443,12 @@ class w extends b {
442
443
  }
443
444
  }
444
445
  w.code = "ERR_JWS_INVALID";
445
- class k extends b {
446
+ class P extends b {
446
447
  constructor() {
447
448
  super(...arguments), this.code = "ERR_JWT_INVALID";
448
449
  }
449
450
  }
450
- k.code = "ERR_JWT_INVALID";
451
+ P.code = "ERR_JWT_INVALID";
451
452
  class Ie extends b {
452
453
  constructor() {
453
454
  super(...arguments), this.code = "ERR_JWK_INVALID";
@@ -472,12 +473,12 @@ class Te extends b {
472
473
  }
473
474
  }
474
475
  Te.code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
475
- class Pe extends b {
476
+ class ke extends b {
476
477
  constructor(t = "request timed out", r) {
477
478
  super(t, r), this.code = "ERR_JWKS_TIMEOUT";
478
479
  }
479
480
  }
480
- Pe.code = "ERR_JWKS_TIMEOUT";
481
+ ke.code = "ERR_JWKS_TIMEOUT";
481
482
  class oe extends b {
482
483
  constructor(t = "signature verification failed", r) {
483
484
  super(t, r), this.code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
@@ -493,7 +494,7 @@ function z(e, t) {
493
494
  function V(e) {
494
495
  return parseInt(e.name.slice(4), 10);
495
496
  }
496
- function ke(e) {
497
+ function Pe(e) {
497
498
  switch (e) {
498
499
  case "ES256":
499
500
  return "P-256";
@@ -562,7 +563,7 @@ function Oe(e, t, ...r) {
562
563
  case "ES512": {
563
564
  if (!z(e.algorithm, "ECDSA"))
564
565
  throw E("ECDSA");
565
- const n = ke(t);
566
+ const n = Pe(t);
566
567
  if (e.algorithm.namedCurve !== n)
567
568
  throw E(n, "algorithm.namedCurve");
568
569
  break;
@@ -660,7 +661,7 @@ function ze(e) {
660
661
  }, r = e.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"];
661
662
  break;
662
663
  default:
663
- throw new A('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
664
+ throw new I('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
664
665
  }
665
666
  break;
666
667
  }
@@ -682,7 +683,7 @@ function ze(e) {
682
683
  t = { name: "ECDH", namedCurve: e.crv }, r = e.d ? ["deriveBits"] : [];
683
684
  break;
684
685
  default:
685
- throw new A('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
686
+ throw new I('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
686
687
  }
687
688
  break;
688
689
  }
@@ -701,12 +702,12 @@ function ze(e) {
701
702
  t = { name: e.crv }, r = e.d ? ["deriveBits"] : [];
702
703
  break;
703
704
  default:
704
- throw new A('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
705
+ throw new I('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
705
706
  }
706
707
  break;
707
708
  }
708
709
  default:
709
- throw new A('Invalid or unsupported JWK "kty" (Key Type) Parameter value');
710
+ throw new I('Invalid or unsupported JWK "kty" (Key Type) Parameter value');
710
711
  }
711
712
  return { algorithm: t, keyUsages: r };
712
713
  }
@@ -763,7 +764,7 @@ const ue = (e) => (e == null ? void 0 : e[Symbol.toStringTag]) === "KeyObject",
763
764
  case K(e, [43, 101, 113]):
764
765
  return "Ed448";
765
766
  default:
766
- throw new A("Invalid or unsupported EC Key Curve or OKP Key Sub Type");
767
+ throw new I("Invalid or unsupported EC Key Curve or OKP Key Sub Type");
767
768
  }
768
769
  }, he = async (e, t, r, n, i) => {
769
770
  let o, s;
@@ -812,7 +813,7 @@ const ue = (e) => (e == null ? void 0 : e[Symbol.toStringTag]) === "KeyObject",
812
813
  o = { name: Z(a) }, s = d ? ["verify"] : ["sign"];
813
814
  break;
814
815
  default:
815
- throw new A('Invalid or unsupported "alg" (Algorithm) value');
816
+ throw new I('Invalid or unsupported "alg" (Algorithm) value');
816
817
  }
817
818
  return q.subtle.importKey(t, a, o, !1, s);
818
819
  }, Fe = (e, t, r) => he(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, "pkcs8", e, t), qe = (e, t, r) => he(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, "spki", e, t);
@@ -836,12 +837,12 @@ async function j(e, t) {
836
837
  return O(e.k);
837
838
  case "RSA":
838
839
  if ("oth" in e && e.oth !== void 0)
839
- throw new A('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
840
+ throw new I('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
840
841
  case "EC":
841
842
  case "OKP":
842
843
  return de({ ...e, alg: t });
843
844
  default:
844
- throw new A('Unsupported "kty" (Key Type) Parameter value');
845
+ throw new I('Unsupported "kty" (Key Type) Parameter value');
845
846
  }
846
847
  }
847
848
  const J = (e) => e == null ? void 0 : e[Symbol.toStringTag], G = (e, t, r) => {
@@ -906,7 +907,7 @@ function Ge(e, t, r, n, i) {
906
907
  o = t;
907
908
  for (const s of n.crit) {
908
909
  if (!o.has(s))
909
- throw new A(`Extension Header Parameter "${s}" is not recognized`);
910
+ throw new I(`Extension Header Parameter "${s}" is not recognized`);
910
911
  if (i[s] === void 0)
911
912
  throw new e(`Extension Header Parameter "${s}" is missing`);
912
913
  if (o.get(s) && n[s] === void 0)
@@ -938,7 +939,7 @@ function Ye(e, t) {
938
939
  case "EdDSA":
939
940
  return { name: t.name };
940
941
  default:
941
- throw new A(`alg ${e} is not supported either by JOSE or your javascript runtime`);
942
+ throw new I(`alg ${e} is not supported either by JOSE or your javascript runtime`);
942
943
  }
943
944
  }
944
945
  async function Xe(e, t, r) {
@@ -1018,8 +1019,8 @@ async function Ze(e, t, r) {
1018
1019
  throw new w("Failed to base64url decode the payload");
1019
1020
  }
1020
1021
  else typeof e.payload == "string" ? C = M.encode(e.payload) : C = e.payload;
1021
- const P = { payload: C };
1022
- return e.protected !== void 0 && (P.protectedHeader = n), e.header !== void 0 && (P.unprotectedHeader = e.header), d ? { ...P, key: t } : P;
1022
+ const k = { payload: C };
1023
+ return e.protected !== void 0 && (k.protectedHeader = n), e.header !== void 0 && (k.unprotectedHeader = e.header), d ? { ...k, key: t } : k;
1023
1024
  }
1024
1025
  async function et(e, t, r) {
1025
1026
  if (e instanceof Uint8Array && (e = H.decode(e)), typeof e != "string")
@@ -1054,28 +1055,28 @@ function te(e) {
1054
1055
  }
1055
1056
  function tt(e) {
1056
1057
  if (typeof e != "string")
1057
- throw new k("JWTs must use Compact JWS serialization, JWT must be a string");
1058
+ throw new P("JWTs must use Compact JWS serialization, JWT must be a string");
1058
1059
  const { 1: t, length: r } = e.split(".");
1059
1060
  if (r === 5)
1060
- throw new k("Only JWTs using Compact JWS serialization can be decoded");
1061
+ throw new P("Only JWTs using Compact JWS serialization can be decoded");
1061
1062
  if (r !== 3)
1062
- throw new k("Invalid JWT");
1063
+ throw new P("Invalid JWT");
1063
1064
  if (!t)
1064
- throw new k("JWTs must contain a payload");
1065
+ throw new P("JWTs must contain a payload");
1065
1066
  let n;
1066
1067
  try {
1067
1068
  n = pe(t);
1068
1069
  } catch {
1069
- throw new k("Failed to base64url decode the payload");
1070
+ throw new P("Failed to base64url decode the payload");
1070
1071
  }
1071
1072
  let i;
1072
1073
  try {
1073
1074
  i = JSON.parse(H.decode(n));
1074
1075
  } catch {
1075
- throw new k("Failed to parse the decoded payload as JSON");
1076
+ throw new P("Failed to parse the decoded payload as JSON");
1076
1077
  }
1077
1078
  if (!x(i))
1078
- throw new k("Invalid JWT Claims Set");
1079
+ throw new P("Invalid JWT Claims Set");
1079
1080
  return i;
1080
1081
  }
1081
1082
  const h = class h {
@@ -1422,10 +1423,10 @@ class nt {
1422
1423
  try {
1423
1424
  let C = await this.post(s, f, this.authServerHeaders);
1424
1425
  if (C.id_token) {
1425
- const P = await this.getIdPayload(C.id_token, C.access_token);
1426
- if (P.error)
1427
- return P;
1428
- C.id_payload = P.payload;
1426
+ const k = await this.getIdPayload(C.id_token, C.access_token);
1427
+ if (k.error)
1428
+ return k;
1429
+ C.id_payload = k.payload;
1429
1430
  }
1430
1431
  return C;
1431
1432
  } catch (C) {
@@ -2234,7 +2235,7 @@ export {
2234
2235
  l as CrossauthLogger,
2235
2236
  ie as DEFAULT_OIDCCONFIG,
2236
2237
  y as ErrorCode,
2237
- I as KeyPrefix,
2238
+ A as KeyPrefix,
2238
2239
  nt as OAuthClientBase,
2239
2240
  re as OAuthFlows,
2240
2241
  ot as OAuthTokenConsumerBase,
@@ -262,5 +262,7 @@ export declare class KeyPrefix {
262
262
  static readonly deviceCode = "dc:";
263
263
  /** Device code flow user code */
264
264
  static readonly userCode = "uc:";
265
+ /** Device code flow user code */
266
+ static readonly knownDevice = "kd:";
265
267
  }
266
268
  //# sourceMappingURL=interfaces.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"interfaces.d.ts","sourceRoot":"","sources":["../src/interfaces.ts"],"names":[],"mappings":"AAEA;;;;;GAKG;AACH,MAAM,WAAW,GAAG;IAEhB;;;OAGG;IACH,KAAK,EAAG,MAAM,CAAC;IAEf,qEAAqE;IACrE,OAAO,EAAG,IAAI,CAAC;IAEf,oCAAoC;IACpC,OAAO,EAAG,IAAI,GAAG,SAAS,CAAC;IAE3B;;;;;;OAMG;IACH,MAAM,EAAG,MAAM,GAAG,MAAM,GAAG,SAAS,GAAG,IAAI,CAAC;IAE5C;;OAEG;IACH,UAAU,CAAC,EAAG,IAAI,CAAC;IAEnB;;;;;OAKG;IACH,IAAI,CAAC,EAAG,MAAM,CAAC;IAEf;;OAEG;IACH,CAAE,GAAG,EAAG,MAAM,GAAK,GAAG,CAAC;CAE1B;AAED;;;GAGG;AACH,MAAM,WAAW,MAAO,SAAQ,GAAG;IAE/B,6CAA6C;IAC7C,IAAI,EAAG,MAAM,CAAC;CACjB;AAED;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAG,GAAG,GAAI;IAAC,CAAC,GAAG,EAAC,MAAM,GAAE,GAAG,CAAA;CAAC,CAO1D;AAED;;;;;;;;;;;GAWG;AACH,MAAM,WAAW,eAAe;IAE5B;;OAEG;IACH,QAAQ,EAAG,MAAM,CAAC;IAElB;;;OAGG;IACH,KAAK,EAAG,MAAM,CAAC;IAEf;;;OAGG;IACH,KAAK,CAAC,EAAG,MAAM,CAAC;IAEhB;;;OAGG;IACH,KAAK,CAAC,EAAG,OAAO,CAAC;IAEjB;;OAEG;IACH,CAAE,GAAG,EAAG,MAAM,GAAK,GAAG,CAAC;CAC1B;AAED;;;;;;;GAOG;AACH,MAAM,WAAW,IAAK,SAAQ,eAAe;IAEzC,2CAA2C;IAC3C,EAAE,EAAG,MAAM,GAAG,MAAM,CAAC;CACxB;AAED;;;;;;;GAOG;AACH,MAAM,WAAW,sBAAsB;IACnC,QAAQ,CAAC,EAAG,MAAM,CAAC;IACnB,UAAU,CAAC,EAAG,MAAM,CAAC;IACrB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,CAAC,GAAG,EAAC,MAAM,GAAI,GAAG,CAAC;CACtB;AAED;;GAEG;AACH,MAAM,WAAW,WAAY,SAAQ,sBAAsB;IACvD,MAAM,EAAG,MAAM,GAAC,MAAM,CAAC;CAC1B;AAED,sDAAsD;AACtD,MAAM,WAAW,WAAW;IAExB,2DAA2D;IAC3D,SAAS,EAAG,MAAM,CAAC;IAEnB;wCACoC;IACpC,YAAY,EAAG,OAAO,CAAC;IAEvB;;;OAGG;IACH,WAAW,EAAG,MAAM,CAAC;IAErB;;;;;;;;;;OAUG;IACH,aAAa,CAAC,EAAG,MAAM,GAAC,IAAI,CAAC;IAE7B;;OAEG;IACH,YAAY,EAAG,MAAM,EAAE,CAAC;IAExB;;;;OAIG;IACH,UAAU,EAAG,MAAM,EAAE,CAAC;IAGtB;;;;;;;;;;OAUG;IACH,MAAM,CAAC,EAAG,MAAM,GAAC,MAAM,GAAC,IAAI,CAAC;IAC7B,CAAE,GAAG,EAAG,MAAM,GAAK,GAAG,CAAC;CAC1B;AAED;;;GAGG;AACH,qBAAa,SAAS;IAElB,kDAAkD;IAClD,MAAM,CAAC,QAAQ,CAAC,MAAM,YAAY;IAElC,+CAA+C;IAC/C,MAAM,CAAC,QAAQ,CAAC,QAAQ,cAAc;IAEtC;;;;;OAKG;IACH,MAAM,CAAC,QAAQ,CAAC,sBAAsB,4BAA4B;IAElE;;;;;OAKG;IACH,MAAM,CAAC,QAAQ,CAAC,0CAA0C,gDAAgD;IAE1G;;;OAGG;IACH,MAAM,CAAC,QAAQ,CAAC,yBAAyB,+BAA+B;IAExE;;;;;OAKG;IACH,MAAM,CAAC,QAAQ,CAAC,oBAAoB,0BAA0B;IAE9D;;;;;OAKG;IACH,MAAM,CAAC,QAAQ,CAAC,mBAAmB,yBAAyB;IAE5D;;;;;;;;;;OAUG;IACH,MAAM,CAAC,QAAQ,CAAC,kBAAkB,wBAAwB;IAE1D;;;;;;OAMG;IACH,MAAM,CAAC,QAAQ,CAAC,6BAA6B,mCAAmC;CACnF;AAED;;;;GAIG;AACH,qBAAa,SAAS;IAElB,iBAAiB;IACjB,MAAM,CAAC,QAAQ,CAAC,OAAO,QAAO;IAE9B,2BAA2B;IAC3B,MAAM,CAAC,QAAQ,CAAC,kBAAkB,QAAO;IAEzC,+BAA+B;IAC/B,MAAM,CAAC,QAAQ,CAAC,sBAAsB,QAAO;IAE7C,cAAc;IACd,MAAM,CAAC,QAAQ,CAAC,MAAM,UAAS;IAE/B,+BAA+B;IAC/B,MAAM,CAAC,QAAQ,CAAC,iBAAiB,YAAY;IAE7C,yBAAyB;IACzB,MAAM,CAAC,QAAQ,CAAC,WAAW,aAAa;IAExC,0BAA0B;IAC1B,MAAM,CAAC,QAAQ,CAAC,YAAY,cAAc;IAE1C,oDAAoD;IACpD,MAAM,CAAC,QAAQ,CAAC,QAAQ,WAAW;IAEnC,8BAA8B;IAC9B,MAAM,CAAC,QAAQ,CAAC,UAAU,SAAQ;IAElC,iCAAiC;IACjC,MAAM,CAAC,QAAQ,CAAC,QAAQ,SAAQ;CACnC"}
1
+ {"version":3,"file":"interfaces.d.ts","sourceRoot":"","sources":["../src/interfaces.ts"],"names":[],"mappings":"AAEA;;;;;GAKG;AACH,MAAM,WAAW,GAAG;IAEhB;;;OAGG;IACH,KAAK,EAAG,MAAM,CAAC;IAEf,qEAAqE;IACrE,OAAO,EAAG,IAAI,CAAC;IAEf,oCAAoC;IACpC,OAAO,EAAG,IAAI,GAAG,SAAS,CAAC;IAE3B;;;;;;OAMG;IACH,MAAM,EAAG,MAAM,GAAG,MAAM,GAAG,SAAS,GAAG,IAAI,CAAC;IAE5C;;OAEG;IACH,UAAU,CAAC,EAAG,IAAI,CAAC;IAEnB;;;;;OAKG;IACH,IAAI,CAAC,EAAG,MAAM,CAAC;IAEf;;OAEG;IACH,CAAE,GAAG,EAAG,MAAM,GAAK,GAAG,CAAC;CAE1B;AAED;;;GAGG;AACH,MAAM,WAAW,MAAO,SAAQ,GAAG;IAE/B,6CAA6C;IAC7C,IAAI,EAAG,MAAM,CAAC;CACjB;AAED;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAG,GAAG,GAAI;IAAC,CAAC,GAAG,EAAC,MAAM,GAAE,GAAG,CAAA;CAAC,CAO1D;AAED;;;;;;;;;;;GAWG;AACH,MAAM,WAAW,eAAe;IAE5B;;OAEG;IACH,QAAQ,EAAG,MAAM,CAAC;IAElB;;;OAGG;IACH,KAAK,EAAG,MAAM,CAAC;IAEf;;;OAGG;IACH,KAAK,CAAC,EAAG,MAAM,CAAC;IAEhB;;;OAGG;IACH,KAAK,CAAC,EAAG,OAAO,CAAC;IAEjB;;OAEG;IACH,CAAE,GAAG,EAAG,MAAM,GAAK,GAAG,CAAC;CAC1B;AAED;;;;;;;GAOG;AACH,MAAM,WAAW,IAAK,SAAQ,eAAe;IAEzC,2CAA2C;IAC3C,EAAE,EAAG,MAAM,GAAG,MAAM,CAAC;CACxB;AAED;;;;;;;GAOG;AACH,MAAM,WAAW,sBAAsB;IACnC,QAAQ,CAAC,EAAG,MAAM,CAAC;IACnB,UAAU,CAAC,EAAG,MAAM,CAAC;IACrB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,CAAC,GAAG,EAAC,MAAM,GAAI,GAAG,CAAC;CACtB;AAED;;GAEG;AACH,MAAM,WAAW,WAAY,SAAQ,sBAAsB;IACvD,MAAM,EAAG,MAAM,GAAC,MAAM,CAAC;CAC1B;AAED,sDAAsD;AACtD,MAAM,WAAW,WAAW;IAExB,2DAA2D;IAC3D,SAAS,EAAG,MAAM,CAAC;IAEnB;wCACoC;IACpC,YAAY,EAAG,OAAO,CAAC;IAEvB;;;OAGG;IACH,WAAW,EAAG,MAAM,CAAC;IAErB;;;;;;;;;;OAUG;IACH,aAAa,CAAC,EAAG,MAAM,GAAC,IAAI,CAAC;IAE7B;;OAEG;IACH,YAAY,EAAG,MAAM,EAAE,CAAC;IAExB;;;;OAIG;IACH,UAAU,EAAG,MAAM,EAAE,CAAC;IAGtB;;;;;;;;;;OAUG;IACH,MAAM,CAAC,EAAG,MAAM,GAAC,MAAM,GAAC,IAAI,CAAC;IAC7B,CAAE,GAAG,EAAG,MAAM,GAAK,GAAG,CAAC;CAC1B;AAED;;;GAGG;AACH,qBAAa,SAAS;IAElB,kDAAkD;IAClD,MAAM,CAAC,QAAQ,CAAC,MAAM,YAAY;IAElC,+CAA+C;IAC/C,MAAM,CAAC,QAAQ,CAAC,QAAQ,cAAc;IAEtC;;;;;OAKG;IACH,MAAM,CAAC,QAAQ,CAAC,sBAAsB,4BAA4B;IAElE;;;;;OAKG;IACH,MAAM,CAAC,QAAQ,CAAC,0CAA0C,gDAAgD;IAE1G;;;OAGG;IACH,MAAM,CAAC,QAAQ,CAAC,yBAAyB,+BAA+B;IAExE;;;;;OAKG;IACH,MAAM,CAAC,QAAQ,CAAC,oBAAoB,0BAA0B;IAE9D;;;;;OAKG;IACH,MAAM,CAAC,QAAQ,CAAC,mBAAmB,yBAAyB;IAE5D;;;;;;;;;;OAUG;IACH,MAAM,CAAC,QAAQ,CAAC,kBAAkB,wBAAwB;IAE1D;;;;;;OAMG;IACH,MAAM,CAAC,QAAQ,CAAC,6BAA6B,mCAAmC;CACnF;AAED;;;;GAIG;AACH,qBAAa,SAAS;IAElB,iBAAiB;IACjB,MAAM,CAAC,QAAQ,CAAC,OAAO,QAAO;IAE9B,2BAA2B;IAC3B,MAAM,CAAC,QAAQ,CAAC,kBAAkB,QAAO;IAEzC,+BAA+B;IAC/B,MAAM,CAAC,QAAQ,CAAC,sBAAsB,QAAO;IAE7C,cAAc;IACd,MAAM,CAAC,QAAQ,CAAC,MAAM,UAAS;IAE/B,+BAA+B;IAC/B,MAAM,CAAC,QAAQ,CAAC,iBAAiB,YAAY;IAE7C,yBAAyB;IACzB,MAAM,CAAC,QAAQ,CAAC,WAAW,aAAa;IAExC,0BAA0B;IAC1B,MAAM,CAAC,QAAQ,CAAC,YAAY,cAAc;IAE1C,oDAAoD;IACpD,MAAM,CAAC,QAAQ,CAAC,QAAQ,WAAW;IAEnC,8BAA8B;IAC9B,MAAM,CAAC,QAAQ,CAAC,UAAU,SAAQ;IAElC,iCAAiC;IACjC,MAAM,CAAC,QAAQ,CAAC,QAAQ,SAAQ;IAEhC,iCAAiC;IACjC,MAAM,CAAC,QAAQ,CAAC,WAAW,SAAQ;CACtC"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@crossauth/common",
3
3
  "private": false,
4
- "version": "1.1.8",
4
+ "version": "1.1.9",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
7
7
  "main": "./dist/index.cjs",