@crossauth/common
Advanced tools
Comparing version 0.0.36 to 0.0.37
@@ -1,1 +0,1 @@ | ||
var crossauth_common=function(p){"use strict";var Je=Object.defineProperty;var de=p=>{throw TypeError(p)};var Fe=(p,g,y)=>g in p?Je(p,g,{enumerable:!0,configurable:!0,writable:!0,value:y}):p[g]=y;var a=(p,g,y)=>Fe(p,typeof g!="symbol"?g+"":g,y),le=(p,g,y)=>g.has(p)||de("Cannot "+y);var m=(p,g,y)=>(le(p,g,"read from private field"),y?y.call(p):g.get(p)),V=(p,g,y)=>g.has(p)?de("Cannot add the same private member more than once"):g instanceof WeakSet?g.add(p):g.set(p,y),z=(p,g,y,w)=>(le(p,g,"write to private field"),w?w.call(p,y):g.set(p,y),y);var S,b;class g{}a(g,"active","active"),a(g,"disabled","disabled"),a(g,"awaitingTwoFactorSetup","awaitingtwofactorsetup"),a(g,"awaitingEmailVerification","awaitingemailverification"),a(g,"passwordChangeNeeded","passwordchangeneeded"),a(g,"passwordResetNeeded","passwordresetneeded"),a(g,"factor2ResetNeeded","factor2resetneeded"),a(g,"passwordAndFactor2ResetNeeded","passwordandfactor2resetneeded");class y{}a(y,"session","s:"),a(y,"passwordResetToken","p:"),a(y,"emailVerificationToken","e:"),a(y,"apiKey","api:"),a(y,"authorizationCode","authz:"),a(y,"accessToken","access:"),a(y,"refreshToken","refresh:"),a(y,"mfaToken","omfa:"),a(y,"deviceCode","dc:"),a(y,"userCode","uc:");var w=(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))(w||{});class v extends Error{constructor(t,n=void 0){let i,o=500;t==0?(i="User does not exist",o=401):t==1?(i="Password doesn't match",o=401):t==3?(i="Username or password incorrect",o=401):t==4?(i="Client id is invalid",o=401):t==5?(i="Client ID or name already exists",o=500):t==6?(i="Client secret is invalid",o=401):t==7?(i="Client id or secret is invalid",o=401):t==8?(i="Redirect Uri is not registered",o=401):t==9?(i="Invalid OAuth flow type",o=500):t==2?(i="No user exists with that email address",o=401):t==10?(i="Account is not active",o=403):t==33?(i="Username is not in an allowed format",o=400):t==31?(i="Email is not in an allowed format",o=400):t==32?(i="Phone number is not in an allowed format",o=400):t==11?(i="Email address has not been verified",o=403):t==12?(i="Two-factor setup is not complete",o=403):t==13?(i="Not authorized",o=401):t==14?(i="Client not authorized",o=401):t==15?(i="Invalid scope",o=403):t==16?(i="Insufficient scope",o=403):t==23?i="Connection failure":t==22?(i="Token has expired",o=401):t==24?i="Hash is not in a valid format":t==19?(i="Key is invalid",o=401):t==18?(i="You do not have permission to access this resource",o=403):t==17?(i="You do not have the right privileges to access this resource",o=401):t==20?(i="CSRF token is invalid",o=401):t==21?(i="Session cookie is invalid",o=401):t==25?i="Algorithm not supported":t==26?i="Attempt to create a key that already exists":t==27?(i="User must change password",o=403):t==28?(i="User must reset password",o=403):t==29?(i="User must reset 2FA",o=403):t==30?i="There was an error in the configuration":t==34?(i="Passwords do not match",o=401):t==35?(i="Token is not valid",o=401):t==36?(i="MFA is required",o=401):t==37?(i="Password format was incorrect",o=401):t==40?(i="User already exists",o=400):t==42?(i="The request is invalid",o=400):t==38?(i="Session data has unexpected format",o=500):t==39?(i="Couldn't execute a fetch",o=500):t==43?(i="Waiting for authorization",o=200):t==44?(i="Slow polling down by 5 seconds",o=200):t==45?(i="Token has expired",o=401):t==46?(i="Database update/insert caused a constraint violation",o=500):t==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);a(this,"isCrossauthError",!0);a(this,"httpStatus");a(this,"code");a(this,"codeName");a(this,"messages");this.code=t,this.codeName=w[t],this.httpStatus=o,this.name="CrossauthError",Array.isArray(n)?this.messages=n:this.messages=[i],Object.setPrototypeOf(this,v.prototype)}static fromOAuthError(t,n){let i;switch(t){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 v(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(t,n){if(t instanceof Error)return"isCrossauthError"in t?t:new v(48,t.message);if("errorCode"in t){let o=48;try{o=Number(t.errorCode)??48}catch{}let s=n??w[o];return"errorMessage"in t?s=t.errorMessage:"message"in t&&(s=t.message),new v(o,s)}let i=n??w[48];return"message"in t&&(i=t.message),new v(48,i)}}function ue(e){return typeof e=="number"&&(e=""+e),e in q?q[e]:q[500]}const q={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"},_=class _{constructor(r){a(this,"level");if(r)this.level=r;else if(typeof process<"u"&&"CROSSAUTH_LOG_LEVEL"in process.env){const t=(process.env.CROSSAUTH_LOG_LEVEL??"ERROR").toUpperCase();_.levelName.includes(t)?this.level=_.levelName.indexOf(t):this.level=_.Error}else this.level=_.Error}static get logger(){return globalThis.crossauthLogger}setLevel(r){this.level=r}log(r,t){r<=this.level&&(typeof t=="string"?console.log("Crossauth "+_.levelName[r]+" "+new Date().toISOString(),t):console.log(JSON.stringify({level:_.levelName[r],time:new Date().toISOString(),...t})))}error(r){this.log(_.Error,r)}warn(r){this.log(_.Warn,r)}info(r){this.log(_.Info,r)}debug(r){this.log(_.Debug,r)}static setLogger(r,t){globalThis.crossauthLogger=r,globalThis.crossauthLoggerAcceptsJson=t}};a(_,"None",0),a(_,"Error",1),a(_,"Warn",2),a(_,"Info",3),a(_,"Debug",4),a(_,"levelName",["NONE","ERROR","WARN","INFO","DEBUG"]);let l=_;function u(e){let r;typeof e=="object"&&"err"in e&&typeof e.err=="object"&&(r=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:r})}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(l.None),globalThis.crossauthLoggerAcceptsJson=!0;const M={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},x=crypto,G=e=>e instanceof CryptoKey,D=new TextEncoder,U=new TextDecoder;function he(...e){const r=e.reduce((i,{length:o})=>i+o,0),t=new Uint8Array(r);let n=0;for(const i of e)t.set(i,n),n+=i.length;return t}const fe=e=>{const r=atob(e),t=new Uint8Array(r.length);for(let n=0;n<r.length;n++)t[n]=r.charCodeAt(n);return t},O=e=>{let r=e;r instanceof Uint8Array&&(r=U.decode(r)),r=r.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return fe(r)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class W extends Error{static get code(){return"ERR_JOSE_GENERIC"}constructor(r){var t;super(r),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(t=Error.captureStackTrace)==null||t.call(Error,this,this.constructor)}}class k extends W{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}}class C extends W{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}}class E extends W{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}static get code(){return"ERR_JWT_INVALID"}}class pe extends W{constructor(){super(...arguments),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED",this.message="signature verification failed"}static get code(){return"ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}function I(e,r="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${r} must be ${e}`)}function H(e,r){return e.name===r}function $(e){return parseInt(e.name.slice(4),10)}function ge(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function ye(e,r){if(r.length&&!r.some(t=>e.usages.includes(t))){let t="CryptoKey does not support this operation, its usages must include ";if(r.length>2){const n=r.pop();t+=`one of ${r.join(", ")}, or ${n}.`}else r.length===2?t+=`one of ${r[0]} or ${r[1]}.`:t+=`${r[0]}.`;throw new TypeError(t)}}function me(e,r,...t){switch(r){case"HS256":case"HS384":case"HS512":{if(!H(e.algorithm,"HMAC"))throw I("HMAC");const n=parseInt(r.slice(2),10);if($(e.algorithm.hash)!==n)throw I(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!H(e.algorithm,"RSASSA-PKCS1-v1_5"))throw I("RSASSA-PKCS1-v1_5");const n=parseInt(r.slice(2),10);if($(e.algorithm.hash)!==n)throw I(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!H(e.algorithm,"RSA-PSS"))throw I("RSA-PSS");const n=parseInt(r.slice(2),10);if($(e.algorithm.hash)!==n)throw I(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw I("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!H(e.algorithm,"ECDSA"))throw I("ECDSA");const n=ge(r);if(e.algorithm.namedCurve!==n)throw I(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}ye(e,t)}function Y(e,r,...t){var n;if(t.length>2){const i=t.pop();e+=`one of type ${t.join(", ")}, or ${i}.`}else t.length===2?e+=`one of type ${t[0]} or ${t[1]}.`:e+=`of type ${t[0]}.`;return r==null?e+=` Received ${r}`:typeof r=="function"&&r.name?e+=` Received function ${r.name}`:typeof r=="object"&&r!=null&&(n=r.constructor)!=null&&n.name&&(e+=` Received an instance of ${r.constructor.name}`),e}const X=(e,...r)=>Y("Key must be ",e,...r);function Q(e,r,...t){return Y(`Key for the ${e} algorithm must be `,r,...t)}const Z=e=>G(e)?!0:(e==null?void 0:e[Symbol.toStringTag])==="KeyObject",J=["CryptoKey"],we=(...e)=>{const r=e.filter(Boolean);if(r.length===0||r.length===1)return!0;let t;for(const n of r){const i=Object.keys(n);if(!t||t.size===0){t=new Set(i);continue}for(const o of i){if(t.has(o))return!1;t.add(o)}}return!0};function ve(e){return typeof e=="object"&&e!==null}function N(e){if(!ve(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let r=e;for(;Object.getPrototypeOf(r)!==null;)r=Object.getPrototypeOf(r);return Object.getPrototypeOf(e)===r}const _e=(e,r)=>{if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:t}=r.algorithm;if(typeof t!="number"||t<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};function Se(e){let r,t;switch(e.kty){case"RSA":{switch(e.alg){case"PS256":case"PS384":case"PS512":r={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},t=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":r={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},t=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":r={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},t=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new k('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(e.alg){case"ES256":r={name:"ECDSA",namedCurve:"P-256"},t=e.d?["sign"]:["verify"];break;case"ES384":r={name:"ECDSA",namedCurve:"P-384"},t=e.d?["sign"]:["verify"];break;case"ES512":r={name:"ECDSA",namedCurve:"P-521"},t=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":r={name:"ECDH",namedCurve:e.crv},t=e.d?["deriveBits"]:[];break;default:throw new k('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(e.alg){case"EdDSA":r={name:e.crv},t=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":r={name:e.crv},t=e.d?["deriveBits"]:[];break;default:throw new k('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new k('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:r,keyUsages:t}}const ee=async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:r,keyUsages:t}=Se(e),n=[r,e.ext??!1,e.key_ops??t],i={...e};return delete i.alg,delete i.use,x.subtle.importKey("jwk",i,...n)},te=e=>O(e);let L,B;const re=e=>(e==null?void 0:e[Symbol.toStringTag])==="KeyObject",ie=async(e,r,t,n)=>{let i=e.get(r);if(i!=null&&i[n])return i[n];const o=await ee({...t,alg:n});return i?i[n]=o:e.set(r,{[n]:o}),o},Ce={normalizePublicKey:(e,r)=>{if(re(e)){let t=e.export({format:"jwk"});return delete t.d,delete t.dp,delete t.dq,delete t.p,delete t.q,delete t.qi,t.k?te(t.k):(B||(B=new WeakMap),ie(B,e,t,r))}return e},normalizePrivateKey:(e,r)=>{if(re(e)){let t=e.export({format:"jwk"});return t.k?te(t.k):(L||(L=new WeakMap),ie(L,e,t,r))}return e}},P=(e,r,t=0)=>{t===0&&(r.unshift(r.length),r.unshift(6));const n=e.indexOf(r[0],t);if(n===-1)return!1;const i=e.subarray(n,n+r.length);return i.length!==r.length?!1:i.every((o,s)=>o===r[s])||P(e,r,n+1)},ne=e=>{switch(!0){case P(e,[42,134,72,206,61,3,1,7]):return"P-256";case P(e,[43,129,4,0,34]):return"P-384";case P(e,[43,129,4,0,35]):return"P-521";case P(e,[43,101,110]):return"X25519";case P(e,[43,101,111]):return"X448";case P(e,[43,101,112]):return"Ed25519";case P(e,[43,101,113]):return"Ed448";default:throw new k("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},oe=async(e,r,t,n,i)=>{let o,s;const c=new Uint8Array(atob(t.replace(e,"")).split("").map(f=>f.charCodeAt(0))),d=r==="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=ne(c);o=f.startsWith("P-")?{name:"ECDH",namedCurve:f}:{name:f},s=d?[]:["deriveBits"];break}case"EdDSA":o={name:ne(c)},s=d?["verify"]:["sign"];break;default:throw new k('Invalid or unsupported "alg" (Algorithm) value')}return x.subtle.importKey(r,c,o,!1,s)},be=(e,r,t)=>oe(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,r),Ae=(e,r,t)=>oe(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",e,r);async function ke(e,r,t){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return Ae(e,r)}async function Ie(e,r,t){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return be(e,r)}async function se(e,r){if(!N(e))throw new TypeError("JWK must be an object");switch(r||(r=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(e.oth!==void 0)throw new k('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return ee({...e,alg:r});default:throw new k('Unsupported "kty" (Key Type) Parameter value')}}const F=e=>e==null?void 0:e[Symbol.toStringTag],Pe=(e,r)=>{if(!(r instanceof Uint8Array)){if(!Z(r))throw new TypeError(Q(e,r,...J,"Uint8Array"));if(r.type!=="secret")throw new TypeError(`${F(r)} instances for symmetric algorithms must be of type "secret"`)}},Te=(e,r,t)=>{if(!Z(r))throw new TypeError(Q(e,r,...J));if(r.type==="secret")throw new TypeError(`${F(r)} instances for asymmetric algorithms must not be of type "secret"`);if(r.algorithm&&t==="verify"&&r.type==="private")throw new TypeError(`${F(r)} instances for asymmetric algorithm verifying must be of type "public"`);if(r.algorithm&&t==="encrypt"&&r.type==="private")throw new TypeError(`${F(r)} instances for asymmetric algorithm encryption must be of type "public"`)},Re=(e,r,t)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?Pe(e,r):Te(e,r,t)};function Ee(e,r,t,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=r;for(const s of n.crit){if(!o.has(s))throw new k(`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 Oe(e,r){const t=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:t,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:t,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:t,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:t,name:"ECDSA",namedCurve:r.namedCurve};case"EdDSA":return{name:r.name};default:throw new k(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function Ke(e,r,t){if(r=await Ce.normalizePublicKey(r,e),G(r))return me(r,e,t),r;if(r instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(X(r,...J));return x.subtle.importKey("raw",r,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[t])}throw new TypeError(X(r,...J,"Uint8Array"))}const Ue=async(e,r,t,n)=>{const i=await Ke(e,r,"verify");_e(e,i);const o=Oe(e,i.algorithm);try{return await x.subtle.verify(o,i,t,n)}catch{return!1}};async function Ne(e,r,t){if(!N(e))throw new C("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new C('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new C("JWS Protected Header incorrect type");if(e.payload===void 0)throw new C("JWS Payload missing");if(typeof e.signature!="string")throw new C("JWS Signature missing or incorrect type");if(e.header!==void 0&&!N(e.header))throw new C("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{const He=O(e.protected);n=JSON.parse(U.decode(He))}catch{throw new C("JWS Protected Header is invalid")}if(!we(n,e.header))throw new C("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const i={...n,...e.header},o=Ee(C,new Map([["b64",!0]]),t==null?void 0:t.crit,n,i);let s=!0;if(o.has("b64")&&(s=n.b64,typeof s!="boolean"))throw new C('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:c}=i;if(typeof c!="string"||!c)throw new C('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(s){if(typeof e.payload!="string")throw new C("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new C("JWS Payload must be a string or an Uint8Array instance");let d=!1;typeof r=="function"&&(r=await r(n,e),d=!0),Re(c,r,"verify");const f=he(D.encode(e.protected??""),D.encode("."),typeof e.payload=="string"?D.encode(e.payload):e.payload);let T;try{T=O(e.signature)}catch{throw new C("Failed to base64url decode the signature")}if(!await Ue(c,r,T,f))throw new pe;let A;if(s)try{A=O(e.payload)}catch{throw new C("Failed to base64url decode the payload")}else typeof e.payload=="string"?A=D.encode(e.payload):A=e.payload;const R={payload:A};return e.protected!==void 0&&(R.protectedHeader=n),e.header!==void 0&&(R.unprotectedHeader=e.header),d?{...R,key:r}:R}async function ze(e,r,t){if(e instanceof Uint8Array&&(e=U.decode(e)),typeof e!="string")throw new C("Compact JWS must be a string or Uint8Array");const{0:n,1:i,2:o,length:s}=e.split(".");if(s!==3)throw new C("Invalid Compact JWS");const c=await Ne({payload:i,protected:n,signature:o},r,t),d={payload:c.payload,protectedHeader:c.protectedHeader};return typeof r=="function"?{...d,key:c.key}:d}const ae=O;function ce(e){let r;if(typeof e=="string"){const t=e.split(".");(t.length===3||t.length===5)&&([r]=t)}else if(typeof e=="object"&&e)if("protected"in e)r=e.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof r!="string"||!r)throw new Error;const t=JSON.parse(U.decode(ae(r)));if(!N(t))throw new Error;return t}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}function xe(e){if(typeof e!="string")throw new E("JWTs must use Compact JWS serialization, JWT must be a string");const{1:r,length:t}=e.split(".");if(t===5)throw new E("Only JWTs using Compact JWS serialization can be decoded");if(t!==3)throw new E("Invalid JWT");if(!r)throw new E("JWTs must contain a payload");let n;try{n=ae(r)}catch{throw new E("Failed to base64url decode the payload")}let i;try{i=JSON.parse(U.decode(n))}catch{throw new E("Failed to parse the decoded payload as JSON")}if(!N(i))throw new E("Invalid JWT Claims Set");return i}const h=class h{static flowNames(r){let t={};return r.forEach(n=>{n in h.flowName&&(t[n]=h.flowName[n])}),t}static isValidFlow(r){return h.allFlows().includes(r)}static areAllValidFlows(r){let t=!0;return r.forEach(n=>{h.isValidFlow(n)||(t=!1)}),t}static allFlows(){return[h.AuthorizationCode,h.AuthorizationCodeWithPKCE,h.ClientCredentials,h.RefreshToken,h.DeviceCode,h.Password,h.PasswordMfa,h.OidcAuthorizationCode]}static grantType(r){switch(r){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"]}}};a(h,"All","all"),a(h,"AuthorizationCode","authorizationCode"),a(h,"AuthorizationCodeWithPKCE","authorizationCodeWithPKCE"),a(h,"ClientCredentials","clientCredentials"),a(h,"RefreshToken","refreshToken"),a(h,"DeviceCode","deviceCode"),a(h,"Password","password"),a(h,"PasswordMfa","passwordMfa"),a(h,"OidcAuthorizationCode","oidcAuthorizationCode"),a(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 j=h;class De{constructor({authServerBaseUrl:r,client_id:t,client_secret:n,redirect_uri:i,codeChallengeMethod:o,stateLength:s,verifierLength:c,tokenConsumer:d,authServerCredentials:f,authServerMode:T,authServerHeaders:K}){a(this,"authServerBaseUrl","");V(this,S);V(this,b);a(this,"codeChallengeMethod","S256");a(this,"verifierLength",32);a(this,"redirect_uri");a(this,"stateLength",32);a(this,"authzCode","");a(this,"oidcConfig");a(this,"tokenConsumer");a(this,"authServerHeaders",{});a(this,"authServerMode");a(this,"authServerCredentials");a(this,"oauthPostType","json");a(this,"oauthLogFetch",!1);a(this,"oauthUseUserInfoEndpoint",!1);a(this,"oauthAuthorizeRedirect");this.tokenConsumer=d,this.authServerBaseUrl=r,c&&(this.verifierLength=c),s&&(this.stateLength=s),t&&z(this,S,t),n&&z(this,b,n),i&&(this.redirect_uri=i),o&&(this.codeChallengeMethod=o),this.authServerBaseUrl=r,f&&(this.authServerCredentials=f),T&&(this.authServerMode=T),K&&(this.authServerHeaders=K)}set client_id(r){z(this,S,r)}set client_secret(r){z(this,b,r)}async loadConfig(r){if(r){l.logger.debug(u({msg:"Reading OIDC config locally"})),this.oidcConfig=r;return}let t;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),t=await fetch(n,i)}catch(n){l.logger.error(u({err:n}))}if(!t||!t.ok)throw new v(w.Connection,"Couldn't get OIDC configuration from URL"+this.authServerBaseUrl+"/.well-known/openid-configuration");this.oidcConfig={...M};try{const n=await t.json();for(const[i,o]of Object.entries(n))this.oidcConfig[i]=o}catch{throw new v(w.Connection,"Unrecognized response from OIDC configuration endpoint")}}getOidcConfig(){return this.oidcConfig}async startAuthorizationCodeFlow(r,t,n,i=!1){var c,d,f;if(l.logger.debug(u({msg:"Starting authorization code flow"})),this.oidcConfig||await this.loadConfig(),!((c=this.oidcConfig)!=null&&c.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(!m(this,S))return{error:"invalid_request",error_description:"Cannot make authorization code flow without client id"};if(!this.redirect_uri)return{error:"invalid_request",error_description:"Cannot make authorization code flow without Redirect Uri"};let o=this.oidcConfig.authorization_endpoint;this.oauthAuthorizeRedirect&&(o=this.oauthAuthorizeRedirect);let s=o+"?response_type=code&client_id="+encodeURIComponent(m(this,S))+"&state="+encodeURIComponent(r)+"&redirect_uri="+encodeURIComponent(this.redirect_uri);return t&&(s+="&scope="+encodeURIComponent(t)),i&&n&&(s+="&code_challenge="+n),{url:s}}async codeChallengeAndVerifier(){const r=this.randomValue(this.verifierLength);return{codeChallenge:this.codeChallengeMethod=="plain"?r:await this.sha256(r),codeVerifier:r}}async getIdPayload(r,t){let n,i;try{let o;if(o=await this.validateIdToken(r),!o)return n="access_denied",i="Invalid ID token received",{error:n,error_description:i};if(t&&this.oauthUseUserInfoEndpoint){const s=await this.userInfoEndpoint(t);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=v.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(r,t,n,i,o){var T,K;if(this.oidcConfig||await this.loadConfig(),i||!r)return i||(i="server_error"),o||(o="Unknown error"),{error:i,error_description:o};if(this.authzCode=r,!((T=this.oidcConfig)!=null&&T.grant_types_supported.includes("authorization_code")))return{error:"invalid_request",error_description:"Server does not support authorization code grant"};if(!((K=this.oidcConfig)!=null&&K.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const s=this.oidcConfig.token_endpoint;let c,d;c="authorization_code",d=m(this,b);let f={grant_type:c,client_id:m(this,S),code:this.authzCode,redirect_uri:this.redirect_uri};t&&(f.scope=t),d&&(f.client_secret=d),n&&(f.code_verifier=n);try{let A=await this.post(s,f,this.authServerHeaders);if(A.id_token){const R=await this.getIdPayload(A.id_token,A.access_token);if(R.error)return R;A.id_payload=R.payload}return A}catch(A){return l.logger.error(u({err:A})),{error:"server_error",error_description:"Unable to get access token from server"}}}async clientCredentialsFlow(r){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(!m(this,S))return{error:"invalid_request",error_description:"Cannot make client credentials flow without client id"};const t=this.oidcConfig.token_endpoint;let n={grant_type:"client_credentials",client_id:m(this,S),client_secret:m(this,b)};r&&(n.scope=r);try{let s=await this.post(t,n,this.authServerHeaders);if(s.id_token){const c=await this.getIdPayload(s.id_token,s.access_token);if(c.error)return c;s.id_payload=c.payload}return s}catch(s){return l.logger.error(u({err:s})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async passwordFlow(r,t,n){var s,c;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(!((c=this.oidcConfig)!=null&&c.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:m(this,S),client_secret:m(this,b),username:r,password:t};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(r){var o,s,c;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(!((c=this.oidcConfig)!=null&&c.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const t=this.oidcConfig.issuer+(this.oidcConfig.issuer.endsWith("/")?"":"/")+"mfa/authenticators",n=await this.get(t,{authorization:"Bearer "+r,...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(r,t){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:m(this,S),client_secret:m(this,b),challenge_type:"otp",mfa_token:r,authenticator_id:t},this.authServerHeaders);return i.challenge_type!="otp"?{error:i.error??"server_error",error_description:i.error_description??"Invalid OTP challenge response"}:i}async mfaOtpComplete(r,t,n){var s,c;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(!((c=this.oidcConfig)!=null&&c.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:m(this,S),client_secret:m(this,b),challenge_type:"otp",mfa_token:r,otp:t,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(r,t){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:m(this,S),client_secret:m(this,b),challenge_type:"oob",mfa_token:r,authenticator_id:t},this.authServerHeaders);return i.challenge_type!="oob"||!i.oob_code||!i.binding_method?{error:i.error??"server_error",error_description:i.error_description??"Invalid OOB challenge response"}:{challenge_type:i.challenge_type,oob_code:i.oob_code,binding_method:i.binding_method,error:i.error,error_description:i.error_description}}async mfaOobComplete(r,t,n,i){var c,d;if(l.logger.debug(u({msg:"Completing MFA OOB request"})),this.oidcConfig||await this.loadConfig(),!((c=this.oidcConfig)!=null&&c.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:m(this,S),client_secret:m(this,b),challenge_type:"otp",mfa_token:r,oob_code:t,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(r){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 t=this.oidcConfig.token_endpoint;let n;n=m(this,b);let i={grant_type:"refresh_token",refresh_token:r,client_id:m(this,S)};n&&(i.client_secret=n);try{let c=await this.post(t,i,this.authServerHeaders);if(c.id_token){const d=await this.getIdPayload(c.id_token,c.access_token);if(d.error)return d;c.id_payload=d.payload}return c}catch(c){return l.logger.error(u({err:c})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async startDeviceCodeFlow(r,t){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:m(this,S),client_secret:m(this,b)};t&&(n.scope=t);try{let o=await this.post(r,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(r){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 t={grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:m(this,S),client_secret:m(this,b),device_code:r};try{const s=await this.post((o=this.oidcConfig)==null?void 0:o.token_endpoint,t,this.authServerHeaders);if(s.error)return s;if(s.id_token){const c=await this.getIdPayload(s.id_token,s.access_token);if(c.error)return c;s.id_payload=c.payload}return s}catch(s){return l.logger.error(u({err:s})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async userInfoEndpoint(r){var i;if(!((i=this.oidcConfig)!=null&&i.userinfo_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const t=this.oidcConfig.userinfo_endpoint;return await this.post(t,{},{authorization:"Bearer "+r})}async post(r,t,n={}){l.logger.debug(u({msg:"Fetch POST",url:r,params:Object.keys(t)}));let i={};this.authServerCredentials&&(i.credentials=this.authServerCredentials),this.authServerMode&&(i.mode=this.authServerMode);let o="",s="";if(this.oauthPostType=="json")o=JSON.stringify(t),s="application/json";else{o="";for(let f in t)o!=""&&(o+="&"),o+=encodeURIComponent(f)+"="+encodeURIComponent(t[f]);s="application/x-www-form-urlencoded"}this.oauthLogFetch&&l.logger.debug(u({msg:"OAuth fetch",method:"POST",url:r,body:o}));const d=await(await fetch(r,{method:"POST",...i,headers:{Accept:"application/json","Content-Type":s,...n},body:o})).json();return this.oauthLogFetch&&l.logger.debug(u({msg:"OAuth fetch response",body:JSON.stringify(d)})),d}async get(r,t={}){l.logger.debug(u({msg:"Fetch GET",url:r}));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:r}));const o=await(await fetch(r,{method:"GET",...n,headers:{Accept:"application/json",...t}})).json();return this.oauthLogFetch&&l.logger.debug(u({msg:"OAuth fetch response",body:JSON.stringify(o)})),o}async validateIdToken(r){try{return await this.tokenConsumer.tokenAuthorized(r,"id")}catch{return}}async idTokenAuthorized(r){try{return await this.tokenConsumer.tokenAuthorized(r,"id")}catch(t){l.logger.warn(u({err:t}));return}}getTokenPayload(r){return xe(r)}}S=new WeakMap,b=new WeakMap;class We{constructor(r,t={}){a(this,"audience");a(this,"jwtKeyType");a(this,"jwtSecretKey");a(this,"jwtPublicKey");a(this,"clockTolerance",10);a(this,"authServerBaseUrl","");a(this,"oidcConfig");a(this,"keys",{});if(this.audience=r,t.authServerBaseUrl&&(this.authServerBaseUrl=t.authServerBaseUrl),t.jwtKeyType&&(this.jwtKeyType=t.jwtKeyType),t.jwtSecretKey&&(this.jwtSecretKey=t.jwtSecretKey),t.jwtPublicKey&&(this.jwtPublicKey=t.jwtPublicKey),t.clockTolerance&&(this.clockTolerance=t.clockTolerance),t.oidcConfig&&(this.oidcConfig=t.oidcConfig),this.jwtPublicKey&&!this.jwtKeyType)throw new v(w.Configuration,"If specifying jwtPublic key, must also specify jwtKeyType")}async loadKeys(r){try{if(this.jwtSecretKey){if(!this.jwtKeyType)throw new v(w.Configuration,"Must specify jwtKeyType if setting jwtSecretKey");this.keys._default=await Ie(this.jwtSecretKey,this.jwtKeyType)}else if(this.jwtPublicKey){if(!this.jwtKeyType)throw new v(w.Configuration,"Must specify jwtKeyType if setting jwtPublicKey");const t=await ke(this.jwtPublicKey,this.jwtKeyType);this.keys._default=t}else{if(this.oidcConfig||await this.loadConfig(),!this.oidcConfig)throw new v(w.Connection,"Load OIDC config before Jwks");await this.loadJwks(void 0,r)}}catch(t){throw l.logger.debug(u({err:t})),new v(w.Connection,"Couldn't load keys")}}async loadConfig(r){if(r){this.oidcConfig=r;return}if(!this.authServerBaseUrl)throw new v(w.Connection,"Couldn't get OIDC configuration. Either set authServerBaseUrl or set config manually");let t;try{t=await fetch(new URL("/.well-known/openid-configuration",this.authServerBaseUrl))}catch(n){l.logger.error(u({err:n}))}if(!t||!t.ok)throw new v(w.Connection,"Couldn't get OIDC configuration");this.oidcConfig={...M};try{const n=await t.json();for(const[i,o]of Object.entries(n))this.oidcConfig[i]=o}catch{throw new v(w.Connection,"Unrecognized response from OIDC configuration endpoint")}}async loadJwks(r,t){if(r){this.keys={};for(let n=0;n<r.keys.length;++n){const i=r.keys[n];this.keys[i.kid??"_default"]=await se(r.keys[n])}}else{if(!this.oidcConfig)throw new v(w.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 v(w.Connection,"Couldn't get OIDC configuration");this.keys={};try{const i=await n.json();if(!("keys"in i)||!Array.isArray(i.keys))throw new v(w.Connection,"Couldn't fetch keys");for(let o=0;o<i.keys.length;++o)try{let s="_default",c={...i.keys[o]};if("kid"in c&&typeof c.kid=="string"&&(s=String(c.kid)),c&&!c.alg&&!c.jwk_alg&&t)if(t.startsWith("RS")&&c.kty=="RSA")c.alg=t;else{l.logger.debug(u({msg:"Skipping key with "+c.kty}));continue}const d=await se(c);this.keys[s]=d}catch(s){throw l.logger.error(u({err:s})),new v(w.Connection,"Couldn't load keys")}}catch(i){throw l.logger.error(u({err:i})),new v(w.Connection,"Unrecognized response from OIDC jwks endpoint")}}}async tokenAuthorized(r,t){if(!this.keys||Object.keys(this.keys).length==0){const i=ce(r);await this.loadKeys(i.alg)}const n=await this.validateToken(r);if(n){if(n.iss!=this.authServerBaseUrl){const i=n.jti?n.jti:n.sid?n.sid:"";l.logger.error(u({msg:`Invalid issuer ${n.iss} in access token`,hashedAccessToken:await this.hash(i)}));return}if(n.aud){const i=n.jti?n.jti:n.sid?n.sid:"";if(Array.isArray(n.aud)&&!n.aud.includes(this.audience)||!Array.isArray(n.aud)&&n.aud!=this.audience){l.logger.error(u({msg:`Invalid audience ${n.aud} in access token`,hashedAccessToken:await this.hash(i)}));return}}return n}}async validateToken(r){(!this.keys||Object.keys(this.keys).length==0)&&l.logger.warn("No keys loaded so cannot validate tokens");let t;try{t=ce(r).kid}catch{l.logger.warn(u({msg:"Invalid access token format"}));return}let n;for(let i in this.keys)if(t==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 ze(r,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{l.logger.warn(u({msg:"Access token did not validate"}));return}}}return p.CrossauthError=v,p.CrossauthLogger=l,p.DEFAULT_OIDCCONFIG=M,p.ErrorCode=w,p.KeyPrefix=y,p.OAuthClientBase=De,p.OAuthFlows=j,p.OAuthTokenConsumerBase=We,p.UserState=g,p.httpStatus=ue,p.j=u,Object.defineProperty(p,Symbol.toStringTag,{value:"Module"}),p}({}); | ||
var crossauth_common=function(p){"use strict";var Je=Object.defineProperty;var de=p=>{throw TypeError(p)};var Fe=(p,g,y)=>g in p?Je(p,g,{enumerable:!0,configurable:!0,writable:!0,value:y}):p[g]=y;var a=(p,g,y)=>Fe(p,typeof g!="symbol"?g+"":g,y),le=(p,g,y)=>g.has(p)||de("Cannot "+y);var m=(p,g,y)=>(le(p,g,"read from private field"),y?y.call(p):g.get(p)),V=(p,g,y)=>g.has(p)?de("Cannot add the same private member more than once"):g instanceof WeakSet?g.add(p):g.set(p,y),z=(p,g,y,w)=>(le(p,g,"write to private field"),w?w.call(p,y):g.set(p,y),y);var S,b;class g{}a(g,"active","active"),a(g,"disabled","disabled"),a(g,"awaitingTwoFactorSetup","awaitingtwofactorsetup"),a(g,"awaitingEmailVerification","awaitingemailverification"),a(g,"passwordChangeNeeded","passwordchangeneeded"),a(g,"passwordResetNeeded","passwordresetneeded"),a(g,"factor2ResetNeeded","factor2resetneeded"),a(g,"passwordAndFactor2ResetNeeded","passwordandfactor2resetneeded");class y{}a(y,"session","s:"),a(y,"passwordResetToken","p:"),a(y,"emailVerificationToken","e:"),a(y,"apiKey","api:"),a(y,"authorizationCode","authz:"),a(y,"accessToken","access:"),a(y,"refreshToken","refresh:"),a(y,"mfaToken","omfa:"),a(y,"deviceCode","dc:"),a(y,"userCode","uc:");var w=(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))(w||{});class v extends Error{constructor(t,n=void 0){let i,o=500;t==0?(i="User does not exist",o=401):t==1?(i="Password doesn't match",o=401):t==3?(i="Username or password incorrect",o=401):t==4?(i="Client id is invalid",o=401):t==5?(i="Client ID or name already exists",o=500):t==6?(i="Client secret is invalid",o=401):t==7?(i="Client id or secret is invalid",o=401):t==8?(i="Redirect Uri is not registered",o=401):t==9?(i="Invalid OAuth flow type",o=500):t==2?(i="No user exists with that email address",o=401):t==10?(i="Account is not active",o=403):t==33?(i="Username is not in an allowed format",o=400):t==31?(i="Email is not in an allowed format",o=400):t==32?(i="Phone number is not in an allowed format",o=400):t==11?(i="Email address has not been verified",o=403):t==12?(i="Two-factor setup is not complete",o=403):t==13?(i="Not authorized",o=401):t==14?(i="Client not authorized",o=401):t==15?(i="Invalid scope",o=403):t==16?(i="Insufficient scope",o=403):t==23?i="Connection failure":t==22?(i="Token has expired",o=401):t==24?i="Hash is not in a valid format":t==19?(i="Key is invalid",o=401):t==18?(i="You do not have permission to access this resource",o=403):t==17?(i="You do not have the right privileges to access this resource",o=401):t==20?(i="CSRF token is invalid",o=401):t==21?(i="Session cookie is invalid",o=401):t==25?i="Algorithm not supported":t==26?i="Attempt to create a key that already exists":t==27?(i="User must change password",o=403):t==28?(i="User must reset password",o=403):t==29?(i="User must reset 2FA",o=403):t==30?i="There was an error in the configuration":t==34?(i="Passwords do not match",o=401):t==35?(i="Token is not valid",o=401):t==36?(i="MFA is required",o=401):t==37?(i="Password format was incorrect",o=401):t==40?(i="User already exists",o=400):t==42?(i="The request is invalid",o=400):t==38?(i="Session data has unexpected format",o=500):t==39?(i="Couldn't execute a fetch",o=500):t==43?(i="Waiting for authorization",o=200):t==44?(i="Slow polling down by 5 seconds",o=200):t==45?(i="Token has expired",o=401):t==46?(i="Database update/insert caused a constraint violation",o=500):t==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);a(this,"isCrossauthError",!0);a(this,"httpStatus");a(this,"code");a(this,"codeName");a(this,"messages");this.code=t,this.codeName=w[t],this.httpStatus=o,this.name="CrossauthError",Array.isArray(n)?this.messages=n:this.messages=[i],Object.setPrototypeOf(this,v.prototype)}static fromOAuthError(t,n){let i;switch(t){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 v(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(t,n){if(t instanceof Error)return"isCrossauthError"in t?t:new v(48,t.message);if("errorCode"in t){let o=48;try{o=Number(t.errorCode)??48}catch{}let s=n??w[o];return"errorMessage"in t?s=t.errorMessage:"message"in t&&(s=t.message),new v(o,s)}let i=n??w[48];return"message"in t&&(i=t.message),new v(48,i)}}function ue(e){return typeof e=="number"&&(e=""+e),e in q?q[e]:q[500]}const q={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"},_=class _{constructor(r){a(this,"level");if(r)this.level=r;else if(typeof process<"u"&&"CROSSAUTH_LOG_LEVEL"in process.env){const t=(process.env.CROSSAUTH_LOG_LEVEL??"ERROR").toUpperCase();_.levelName.includes(t)?this.level=_.levelName.indexOf(t):this.level=_.Error}else this.level=_.Error}static get logger(){return globalThis.crossauthLogger}setLevel(r){this.level=r}log(r,t){r<=this.level&&(typeof t=="string"?console.log("Crossauth "+_.levelName[r]+" "+new Date().toISOString(),t):console.log(JSON.stringify({level:_.levelName[r],time:new Date().toISOString(),...t})))}error(r){this.log(_.Error,r)}warn(r){this.log(_.Warn,r)}info(r){this.log(_.Info,r)}debug(r){this.log(_.Debug,r)}static setLogger(r,t){globalThis.crossauthLogger=r,globalThis.crossauthLoggerAcceptsJson=t}};a(_,"None",0),a(_,"Error",1),a(_,"Warn",2),a(_,"Info",3),a(_,"Debug",4),a(_,"levelName",["NONE","ERROR","WARN","INFO","DEBUG"]);let l=_;function u(e){let r;typeof e=="object"&&"err"in e&&typeof e.err=="object"&&(r=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:r})}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 M={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},x=crypto,G=e=>e instanceof CryptoKey,D=new TextEncoder,U=new TextDecoder;function he(...e){const r=e.reduce((i,{length:o})=>i+o,0),t=new Uint8Array(r);let n=0;for(const i of e)t.set(i,n),n+=i.length;return t}const fe=e=>{const r=atob(e),t=new Uint8Array(r.length);for(let n=0;n<r.length;n++)t[n]=r.charCodeAt(n);return t},O=e=>{let r=e;r instanceof Uint8Array&&(r=U.decode(r)),r=r.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return fe(r)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class W extends Error{static get code(){return"ERR_JOSE_GENERIC"}constructor(r){var t;super(r),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(t=Error.captureStackTrace)==null||t.call(Error,this,this.constructor)}}class k extends W{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}}class C extends W{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}}class E extends W{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}static get code(){return"ERR_JWT_INVALID"}}class pe extends W{constructor(){super(...arguments),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED",this.message="signature verification failed"}static get code(){return"ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}function I(e,r="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${r} must be ${e}`)}function H(e,r){return e.name===r}function $(e){return parseInt(e.name.slice(4),10)}function ge(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function ye(e,r){if(r.length&&!r.some(t=>e.usages.includes(t))){let t="CryptoKey does not support this operation, its usages must include ";if(r.length>2){const n=r.pop();t+=`one of ${r.join(", ")}, or ${n}.`}else r.length===2?t+=`one of ${r[0]} or ${r[1]}.`:t+=`${r[0]}.`;throw new TypeError(t)}}function me(e,r,...t){switch(r){case"HS256":case"HS384":case"HS512":{if(!H(e.algorithm,"HMAC"))throw I("HMAC");const n=parseInt(r.slice(2),10);if($(e.algorithm.hash)!==n)throw I(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!H(e.algorithm,"RSASSA-PKCS1-v1_5"))throw I("RSASSA-PKCS1-v1_5");const n=parseInt(r.slice(2),10);if($(e.algorithm.hash)!==n)throw I(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!H(e.algorithm,"RSA-PSS"))throw I("RSA-PSS");const n=parseInt(r.slice(2),10);if($(e.algorithm.hash)!==n)throw I(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw I("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!H(e.algorithm,"ECDSA"))throw I("ECDSA");const n=ge(r);if(e.algorithm.namedCurve!==n)throw I(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}ye(e,t)}function Y(e,r,...t){var n;if(t.length>2){const i=t.pop();e+=`one of type ${t.join(", ")}, or ${i}.`}else t.length===2?e+=`one of type ${t[0]} or ${t[1]}.`:e+=`of type ${t[0]}.`;return r==null?e+=` Received ${r}`:typeof r=="function"&&r.name?e+=` Received function ${r.name}`:typeof r=="object"&&r!=null&&(n=r.constructor)!=null&&n.name&&(e+=` Received an instance of ${r.constructor.name}`),e}const X=(e,...r)=>Y("Key must be ",e,...r);function Q(e,r,...t){return Y(`Key for the ${e} algorithm must be `,r,...t)}const Z=e=>G(e)?!0:(e==null?void 0:e[Symbol.toStringTag])==="KeyObject",J=["CryptoKey"],we=(...e)=>{const r=e.filter(Boolean);if(r.length===0||r.length===1)return!0;let t;for(const n of r){const i=Object.keys(n);if(!t||t.size===0){t=new Set(i);continue}for(const o of i){if(t.has(o))return!1;t.add(o)}}return!0};function ve(e){return typeof e=="object"&&e!==null}function N(e){if(!ve(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let r=e;for(;Object.getPrototypeOf(r)!==null;)r=Object.getPrototypeOf(r);return Object.getPrototypeOf(e)===r}const _e=(e,r)=>{if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:t}=r.algorithm;if(typeof t!="number"||t<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};function Se(e){let r,t;switch(e.kty){case"RSA":{switch(e.alg){case"PS256":case"PS384":case"PS512":r={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},t=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":r={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},t=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":r={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},t=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new k('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(e.alg){case"ES256":r={name:"ECDSA",namedCurve:"P-256"},t=e.d?["sign"]:["verify"];break;case"ES384":r={name:"ECDSA",namedCurve:"P-384"},t=e.d?["sign"]:["verify"];break;case"ES512":r={name:"ECDSA",namedCurve:"P-521"},t=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":r={name:"ECDH",namedCurve:e.crv},t=e.d?["deriveBits"]:[];break;default:throw new k('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(e.alg){case"EdDSA":r={name:e.crv},t=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":r={name:e.crv},t=e.d?["deriveBits"]:[];break;default:throw new k('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new k('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:r,keyUsages:t}}const ee=async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:r,keyUsages:t}=Se(e),n=[r,e.ext??!1,e.key_ops??t],i={...e};return delete i.alg,delete i.use,x.subtle.importKey("jwk",i,...n)},te=e=>O(e);let L,B;const re=e=>(e==null?void 0:e[Symbol.toStringTag])==="KeyObject",ie=async(e,r,t,n)=>{let i=e.get(r);if(i!=null&&i[n])return i[n];const o=await ee({...t,alg:n});return i?i[n]=o:e.set(r,{[n]:o}),o},Ce={normalizePublicKey:(e,r)=>{if(re(e)){let t=e.export({format:"jwk"});return delete t.d,delete t.dp,delete t.dq,delete t.p,delete t.q,delete t.qi,t.k?te(t.k):(B||(B=new WeakMap),ie(B,e,t,r))}return e},normalizePrivateKey:(e,r)=>{if(re(e)){let t=e.export({format:"jwk"});return t.k?te(t.k):(L||(L=new WeakMap),ie(L,e,t,r))}return e}},P=(e,r,t=0)=>{t===0&&(r.unshift(r.length),r.unshift(6));const n=e.indexOf(r[0],t);if(n===-1)return!1;const i=e.subarray(n,n+r.length);return i.length!==r.length?!1:i.every((o,s)=>o===r[s])||P(e,r,n+1)},ne=e=>{switch(!0){case P(e,[42,134,72,206,61,3,1,7]):return"P-256";case P(e,[43,129,4,0,34]):return"P-384";case P(e,[43,129,4,0,35]):return"P-521";case P(e,[43,101,110]):return"X25519";case P(e,[43,101,111]):return"X448";case P(e,[43,101,112]):return"Ed25519";case P(e,[43,101,113]):return"Ed448";default:throw new k("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},oe=async(e,r,t,n,i)=>{let o,s;const c=new Uint8Array(atob(t.replace(e,"")).split("").map(f=>f.charCodeAt(0))),d=r==="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=ne(c);o=f.startsWith("P-")?{name:"ECDH",namedCurve:f}:{name:f},s=d?[]:["deriveBits"];break}case"EdDSA":o={name:ne(c)},s=d?["verify"]:["sign"];break;default:throw new k('Invalid or unsupported "alg" (Algorithm) value')}return x.subtle.importKey(r,c,o,!1,s)},be=(e,r,t)=>oe(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,r),Ae=(e,r,t)=>oe(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",e,r);async function ke(e,r,t){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return Ae(e,r)}async function Ie(e,r,t){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return be(e,r)}async function se(e,r){if(!N(e))throw new TypeError("JWK must be an object");switch(r||(r=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(e.oth!==void 0)throw new k('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return ee({...e,alg:r});default:throw new k('Unsupported "kty" (Key Type) Parameter value')}}const F=e=>e==null?void 0:e[Symbol.toStringTag],Pe=(e,r)=>{if(!(r instanceof Uint8Array)){if(!Z(r))throw new TypeError(Q(e,r,...J,"Uint8Array"));if(r.type!=="secret")throw new TypeError(`${F(r)} instances for symmetric algorithms must be of type "secret"`)}},Te=(e,r,t)=>{if(!Z(r))throw new TypeError(Q(e,r,...J));if(r.type==="secret")throw new TypeError(`${F(r)} instances for asymmetric algorithms must not be of type "secret"`);if(r.algorithm&&t==="verify"&&r.type==="private")throw new TypeError(`${F(r)} instances for asymmetric algorithm verifying must be of type "public"`);if(r.algorithm&&t==="encrypt"&&r.type==="private")throw new TypeError(`${F(r)} instances for asymmetric algorithm encryption must be of type "public"`)},Re=(e,r,t)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?Pe(e,r):Te(e,r,t)};function Ee(e,r,t,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=r;for(const s of n.crit){if(!o.has(s))throw new k(`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 Oe(e,r){const t=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:t,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:t,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:t,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:t,name:"ECDSA",namedCurve:r.namedCurve};case"EdDSA":return{name:r.name};default:throw new k(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function Ke(e,r,t){if(r=await Ce.normalizePublicKey(r,e),G(r))return me(r,e,t),r;if(r instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(X(r,...J));return x.subtle.importKey("raw",r,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[t])}throw new TypeError(X(r,...J,"Uint8Array"))}const Ue=async(e,r,t,n)=>{const i=await Ke(e,r,"verify");_e(e,i);const o=Oe(e,i.algorithm);try{return await x.subtle.verify(o,i,t,n)}catch{return!1}};async function Ne(e,r,t){if(!N(e))throw new C("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new C('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new C("JWS Protected Header incorrect type");if(e.payload===void 0)throw new C("JWS Payload missing");if(typeof e.signature!="string")throw new C("JWS Signature missing or incorrect type");if(e.header!==void 0&&!N(e.header))throw new C("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{const He=O(e.protected);n=JSON.parse(U.decode(He))}catch{throw new C("JWS Protected Header is invalid")}if(!we(n,e.header))throw new C("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const i={...n,...e.header},o=Ee(C,new Map([["b64",!0]]),t==null?void 0:t.crit,n,i);let s=!0;if(o.has("b64")&&(s=n.b64,typeof s!="boolean"))throw new C('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:c}=i;if(typeof c!="string"||!c)throw new C('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(s){if(typeof e.payload!="string")throw new C("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new C("JWS Payload must be a string or an Uint8Array instance");let d=!1;typeof r=="function"&&(r=await r(n,e),d=!0),Re(c,r,"verify");const f=he(D.encode(e.protected??""),D.encode("."),typeof e.payload=="string"?D.encode(e.payload):e.payload);let T;try{T=O(e.signature)}catch{throw new C("Failed to base64url decode the signature")}if(!await Ue(c,r,T,f))throw new pe;let A;if(s)try{A=O(e.payload)}catch{throw new C("Failed to base64url decode the payload")}else typeof e.payload=="string"?A=D.encode(e.payload):A=e.payload;const R={payload:A};return e.protected!==void 0&&(R.protectedHeader=n),e.header!==void 0&&(R.unprotectedHeader=e.header),d?{...R,key:r}:R}async function ze(e,r,t){if(e instanceof Uint8Array&&(e=U.decode(e)),typeof e!="string")throw new C("Compact JWS must be a string or Uint8Array");const{0:n,1:i,2:o,length:s}=e.split(".");if(s!==3)throw new C("Invalid Compact JWS");const c=await Ne({payload:i,protected:n,signature:o},r,t),d={payload:c.payload,protectedHeader:c.protectedHeader};return typeof r=="function"?{...d,key:c.key}:d}const ae=O;function ce(e){let r;if(typeof e=="string"){const t=e.split(".");(t.length===3||t.length===5)&&([r]=t)}else if(typeof e=="object"&&e)if("protected"in e)r=e.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof r!="string"||!r)throw new Error;const t=JSON.parse(U.decode(ae(r)));if(!N(t))throw new Error;return t}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}function xe(e){if(typeof e!="string")throw new E("JWTs must use Compact JWS serialization, JWT must be a string");const{1:r,length:t}=e.split(".");if(t===5)throw new E("Only JWTs using Compact JWS serialization can be decoded");if(t!==3)throw new E("Invalid JWT");if(!r)throw new E("JWTs must contain a payload");let n;try{n=ae(r)}catch{throw new E("Failed to base64url decode the payload")}let i;try{i=JSON.parse(U.decode(n))}catch{throw new E("Failed to parse the decoded payload as JSON")}if(!N(i))throw new E("Invalid JWT Claims Set");return i}const h=class h{static flowNames(r){let t={};return r.forEach(n=>{n in h.flowName&&(t[n]=h.flowName[n])}),t}static isValidFlow(r){return h.allFlows().includes(r)}static areAllValidFlows(r){let t=!0;return r.forEach(n=>{h.isValidFlow(n)||(t=!1)}),t}static allFlows(){return[h.AuthorizationCode,h.AuthorizationCodeWithPKCE,h.ClientCredentials,h.RefreshToken,h.DeviceCode,h.Password,h.PasswordMfa,h.OidcAuthorizationCode]}static grantType(r){switch(r){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"]}}};a(h,"All","all"),a(h,"AuthorizationCode","authorizationCode"),a(h,"AuthorizationCodeWithPKCE","authorizationCodeWithPKCE"),a(h,"ClientCredentials","clientCredentials"),a(h,"RefreshToken","refreshToken"),a(h,"DeviceCode","deviceCode"),a(h,"Password","password"),a(h,"PasswordMfa","passwordMfa"),a(h,"OidcAuthorizationCode","oidcAuthorizationCode"),a(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 j=h;class De{constructor({authServerBaseUrl:r,client_id:t,client_secret:n,redirect_uri:i,codeChallengeMethod:o,stateLength:s,verifierLength:c,tokenConsumer:d,authServerCredentials:f,authServerMode:T,authServerHeaders:K}){a(this,"authServerBaseUrl","");V(this,S);V(this,b);a(this,"codeChallengeMethod","S256");a(this,"verifierLength",32);a(this,"redirect_uri");a(this,"stateLength",32);a(this,"authzCode","");a(this,"oidcConfig");a(this,"tokenConsumer");a(this,"authServerHeaders",{});a(this,"authServerMode");a(this,"authServerCredentials");a(this,"oauthPostType","json");a(this,"oauthLogFetch",!1);a(this,"oauthUseUserInfoEndpoint",!1);a(this,"oauthAuthorizeRedirect");this.tokenConsumer=d,this.authServerBaseUrl=r,c&&(this.verifierLength=c),s&&(this.stateLength=s),t&&z(this,S,t),n&&z(this,b,n),i&&(this.redirect_uri=i),o&&(this.codeChallengeMethod=o),this.authServerBaseUrl=r,f&&(this.authServerCredentials=f),T&&(this.authServerMode=T),K&&(this.authServerHeaders=K)}set client_id(r){z(this,S,r)}set client_secret(r){z(this,b,r)}async loadConfig(r){if(r){l.logger.debug(u({msg:"Reading OIDC config locally"})),this.oidcConfig=r;return}let t;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),t=await fetch(n,i)}catch(n){l.logger.error(u({err:n}))}if(!t||!t.ok)throw new v(w.Connection,"Couldn't get OIDC configuration from URL"+this.authServerBaseUrl+"/.well-known/openid-configuration");this.oidcConfig={...M};try{const n=await t.json();for(const[i,o]of Object.entries(n))this.oidcConfig[i]=o}catch{throw new v(w.Connection,"Unrecognized response from OIDC configuration endpoint")}}getOidcConfig(){return this.oidcConfig}async startAuthorizationCodeFlow(r,t,n,i=!1){var c,d,f;if(l.logger.debug(u({msg:"Starting authorization code flow"})),this.oidcConfig||await this.loadConfig(),!((c=this.oidcConfig)!=null&&c.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(!m(this,S))return{error:"invalid_request",error_description:"Cannot make authorization code flow without client id"};if(!this.redirect_uri)return{error:"invalid_request",error_description:"Cannot make authorization code flow without Redirect Uri"};let o=this.oidcConfig.authorization_endpoint;this.oauthAuthorizeRedirect&&(o=this.oauthAuthorizeRedirect);let s=o+"?response_type=code&client_id="+encodeURIComponent(m(this,S))+"&state="+encodeURIComponent(r)+"&redirect_uri="+encodeURIComponent(this.redirect_uri);return t&&(s+="&scope="+encodeURIComponent(t)),i&&n&&(s+="&code_challenge="+n),{url:s}}async codeChallengeAndVerifier(){const r=this.randomValue(this.verifierLength);return{codeChallenge:this.codeChallengeMethod=="plain"?r:await this.sha256(r),codeVerifier:r}}async getIdPayload(r,t){let n,i;try{let o;if(o=await this.validateIdToken(r),!o)return n="access_denied",i="Invalid ID token received",{error:n,error_description:i};if(t&&this.oauthUseUserInfoEndpoint){const s=await this.userInfoEndpoint(t);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=v.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(r,t,n,i,o){var T,K;if(this.oidcConfig||await this.loadConfig(),i||!r)return i||(i="server_error"),o||(o="Unknown error"),{error:i,error_description:o};if(this.authzCode=r,!((T=this.oidcConfig)!=null&&T.grant_types_supported.includes("authorization_code")))return{error:"invalid_request",error_description:"Server does not support authorization code grant"};if(!((K=this.oidcConfig)!=null&&K.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const s=this.oidcConfig.token_endpoint;let c,d;c="authorization_code",d=m(this,b);let f={grant_type:c,client_id:m(this,S),code:this.authzCode,redirect_uri:this.redirect_uri};t&&(f.scope=t),d&&(f.client_secret=d),n&&(f.code_verifier=n);try{let A=await this.post(s,f,this.authServerHeaders);if(A.id_token){const R=await this.getIdPayload(A.id_token,A.access_token);if(R.error)return R;A.id_payload=R.payload}return A}catch(A){return l.logger.error(u({err:A})),{error:"server_error",error_description:"Unable to get access token from server"}}}async clientCredentialsFlow(r){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(!m(this,S))return{error:"invalid_request",error_description:"Cannot make client credentials flow without client id"};const t=this.oidcConfig.token_endpoint;let n={grant_type:"client_credentials",client_id:m(this,S),client_secret:m(this,b)};r&&(n.scope=r);try{let s=await this.post(t,n,this.authServerHeaders);if(s.id_token){const c=await this.getIdPayload(s.id_token,s.access_token);if(c.error)return c;s.id_payload=c.payload}return s}catch(s){return l.logger.error(u({err:s})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async passwordFlow(r,t,n){var s,c;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(!((c=this.oidcConfig)!=null&&c.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:m(this,S),client_secret:m(this,b),username:r,password:t};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(r){var o,s,c;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(!((c=this.oidcConfig)!=null&&c.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const t=this.oidcConfig.issuer+(this.oidcConfig.issuer.endsWith("/")?"":"/")+"mfa/authenticators",n=await this.get(t,{authorization:"Bearer "+r,...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(r,t){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:m(this,S),client_secret:m(this,b),challenge_type:"otp",mfa_token:r,authenticator_id:t},this.authServerHeaders);return i.challenge_type!="otp"?{error:i.error??"server_error",error_description:i.error_description??"Invalid OTP challenge response"}:i}async mfaOtpComplete(r,t,n){var s,c;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(!((c=this.oidcConfig)!=null&&c.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:m(this,S),client_secret:m(this,b),challenge_type:"otp",mfa_token:r,otp:t,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(r,t){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:m(this,S),client_secret:m(this,b),challenge_type:"oob",mfa_token:r,authenticator_id:t},this.authServerHeaders);return i.challenge_type!="oob"||!i.oob_code||!i.binding_method?{error:i.error??"server_error",error_description:i.error_description??"Invalid OOB challenge response"}:{challenge_type:i.challenge_type,oob_code:i.oob_code,binding_method:i.binding_method,error:i.error,error_description:i.error_description}}async mfaOobComplete(r,t,n,i){var c,d;if(l.logger.debug(u({msg:"Completing MFA OOB request"})),this.oidcConfig||await this.loadConfig(),!((c=this.oidcConfig)!=null&&c.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:m(this,S),client_secret:m(this,b),challenge_type:"otp",mfa_token:r,oob_code:t,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(r){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 t=this.oidcConfig.token_endpoint;let n;n=m(this,b);let i={grant_type:"refresh_token",refresh_token:r,client_id:m(this,S)};n&&(i.client_secret=n);try{let c=await this.post(t,i,this.authServerHeaders);if(c.id_token){const d=await this.getIdPayload(c.id_token,c.access_token);if(d.error)return d;c.id_payload=d.payload}return c}catch(c){return l.logger.error(u({err:c})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async startDeviceCodeFlow(r,t){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:m(this,S),client_secret:m(this,b)};t&&(n.scope=t);try{let o=await this.post(r,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(r){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 t={grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:m(this,S),client_secret:m(this,b),device_code:r};try{const s=await this.post((o=this.oidcConfig)==null?void 0:o.token_endpoint,t,this.authServerHeaders);if(s.error)return s;if(s.id_token){const c=await this.getIdPayload(s.id_token,s.access_token);if(c.error)return c;s.id_payload=c.payload}return s}catch(s){return l.logger.error(u({err:s})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async userInfoEndpoint(r){var i;if(!((i=this.oidcConfig)!=null&&i.userinfo_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const t=this.oidcConfig.userinfo_endpoint;return await this.post(t,{},{authorization:"Bearer "+r})}async post(r,t,n={}){l.logger.debug(u({msg:"Fetch POST",url:r,params:Object.keys(t)}));let i={};this.authServerCredentials&&(i.credentials=this.authServerCredentials),this.authServerMode&&(i.mode=this.authServerMode);let o="",s="";if(this.oauthPostType=="json")o=JSON.stringify(t),s="application/json";else{o="";for(let f in t)o!=""&&(o+="&"),o+=encodeURIComponent(f)+"="+encodeURIComponent(t[f]);s="application/x-www-form-urlencoded"}this.oauthLogFetch&&l.logger.debug(u({msg:"OAuth fetch",method:"POST",url:r,body:o}));const d=await(await fetch(r,{method:"POST",...i,headers:{Accept:"application/json","Content-Type":s,...n},body:o})).json();return this.oauthLogFetch&&l.logger.debug(u({msg:"OAuth fetch response",body:JSON.stringify(d)})),d}async get(r,t={}){l.logger.debug(u({msg:"Fetch GET",url:r}));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:r}));const o=await(await fetch(r,{method:"GET",...n,headers:{Accept:"application/json",...t}})).json();return this.oauthLogFetch&&l.logger.debug(u({msg:"OAuth fetch response",body:JSON.stringify(o)})),o}async validateIdToken(r){try{return await this.tokenConsumer.tokenAuthorized(r,"id")}catch{return}}async idTokenAuthorized(r){try{return await this.tokenConsumer.tokenAuthorized(r,"id")}catch(t){l.logger.warn(u({err:t}));return}}getTokenPayload(r){return xe(r)}}S=new WeakMap,b=new WeakMap;class We{constructor(r,t={}){a(this,"audience");a(this,"jwtKeyType");a(this,"jwtSecretKey");a(this,"jwtPublicKey");a(this,"clockTolerance",10);a(this,"authServerBaseUrl","");a(this,"oidcConfig");a(this,"keys",{});if(this.audience=r,t.authServerBaseUrl&&(this.authServerBaseUrl=t.authServerBaseUrl),t.jwtKeyType&&(this.jwtKeyType=t.jwtKeyType),t.jwtSecretKey&&(this.jwtSecretKey=t.jwtSecretKey),t.jwtPublicKey&&(this.jwtPublicKey=t.jwtPublicKey),t.clockTolerance&&(this.clockTolerance=t.clockTolerance),t.oidcConfig&&(this.oidcConfig=t.oidcConfig),this.jwtPublicKey&&!this.jwtKeyType)throw new v(w.Configuration,"If specifying jwtPublic key, must also specify jwtKeyType")}async loadKeys(r){try{if(this.jwtSecretKey){if(!this.jwtKeyType)throw new v(w.Configuration,"Must specify jwtKeyType if setting jwtSecretKey");this.keys._default=await Ie(this.jwtSecretKey,this.jwtKeyType)}else if(this.jwtPublicKey){if(!this.jwtKeyType)throw new v(w.Configuration,"Must specify jwtKeyType if setting jwtPublicKey");const t=await ke(this.jwtPublicKey,this.jwtKeyType);this.keys._default=t}else{if(this.oidcConfig||await this.loadConfig(),!this.oidcConfig)throw new v(w.Connection,"Load OIDC config before Jwks");await this.loadJwks(void 0,r)}}catch(t){throw l.logger.debug(u({err:t})),new v(w.Connection,"Couldn't load keys")}}async loadConfig(r){if(r){this.oidcConfig=r;return}if(!this.authServerBaseUrl)throw new v(w.Connection,"Couldn't get OIDC configuration. Either set authServerBaseUrl or set config manually");let t;try{t=await fetch(new URL("/.well-known/openid-configuration",this.authServerBaseUrl))}catch(n){l.logger.error(u({err:n}))}if(!t||!t.ok)throw new v(w.Connection,"Couldn't get OIDC configuration");this.oidcConfig={...M};try{const n=await t.json();for(const[i,o]of Object.entries(n))this.oidcConfig[i]=o}catch{throw new v(w.Connection,"Unrecognized response from OIDC configuration endpoint")}}async loadJwks(r,t){if(r){this.keys={};for(let n=0;n<r.keys.length;++n){const i=r.keys[n];this.keys[i.kid??"_default"]=await se(r.keys[n])}}else{if(!this.oidcConfig)throw new v(w.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 v(w.Connection,"Couldn't get OIDC configuration");this.keys={};try{const i=await n.json();if(!("keys"in i)||!Array.isArray(i.keys))throw new v(w.Connection,"Couldn't fetch keys");for(let o=0;o<i.keys.length;++o)try{let s="_default",c={...i.keys[o]};if("kid"in c&&typeof c.kid=="string"&&(s=String(c.kid)),c&&!c.alg&&!c.jwk_alg&&t)if(t.startsWith("RS")&&c.kty=="RSA")c.alg=t;else{l.logger.debug(u({msg:"Skipping key with "+c.kty}));continue}const d=await se(c);this.keys[s]=d}catch(s){throw l.logger.error(u({err:s})),new v(w.Connection,"Couldn't load keys")}}catch(i){throw l.logger.error(u({err:i})),new v(w.Connection,"Unrecognized response from OIDC jwks endpoint")}}}async tokenAuthorized(r,t){if(!this.keys||Object.keys(this.keys).length==0){const i=ce(r);await this.loadKeys(i.alg)}const n=await this.validateToken(r);if(n){if(n.iss!=this.authServerBaseUrl){const i=n.jti?n.jti:n.sid?n.sid:"";l.logger.error(u({msg:`Invalid issuer ${n.iss} in access token`,hashedAccessToken:await this.hash(i)}));return}if(n.aud){const i=n.jti?n.jti:n.sid?n.sid:"";if(Array.isArray(n.aud)&&!n.aud.includes(this.audience)||!Array.isArray(n.aud)&&n.aud!=this.audience){l.logger.error(u({msg:`Invalid audience ${n.aud} in access token`,hashedAccessToken:await this.hash(i)}));return}}return n}}async validateToken(r){(!this.keys||Object.keys(this.keys).length==0)&&l.logger.warn("No keys loaded so cannot validate tokens");let t;try{t=ce(r).kid}catch{l.logger.warn(u({msg:"Invalid access token format"}));return}let n;for(let i in this.keys)if(t==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 ze(r,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{l.logger.warn(u({msg:"Access token did not validate"}));return}}}return p.CrossauthError=v,p.CrossauthLogger=l,p.DEFAULT_OIDCCONFIG=M,p.ErrorCode=w,p.KeyPrefix=y,p.OAuthClientBase=De,p.OAuthFlows=j,p.OAuthTokenConsumerBase=We,p.UserState=g,p.httpStatus=ue,p.j=u,Object.defineProperty(p,Symbol.toStringTag,{value:"Module"}),p}({}); |
{ | ||
"name": "@crossauth/common", | ||
"private": false, | ||
"version": "0.0.36", | ||
"version": "0.0.37", | ||
"license": "Apache-2.0", | ||
@@ -6,0 +6,0 @@ "type": "module", |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
257495