Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@crossauth/common

Package Overview
Dependencies
Maintainers
0
Versions
33
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@crossauth/common - npm Package Compare versions

Comparing version 0.0.30 to 0.0.32

2

dist/index.iife.js

@@ -1,1 +0,1 @@

var crossauth_common=function(u){"use strict";var Me=Object.defineProperty;var he=u=>{throw TypeError(u)};var $e=(u,g,y)=>g in u?Me(u,g,{enumerable:!0,configurable:!0,writable:!0,value:y}):u[g]=y;var a=(u,g,y)=>$e(u,typeof g!="symbol"?g+"":g,y),ue=(u,g,y)=>g.has(u)||he("Cannot "+y);var p=(u,g,y)=>(ue(u,g,"read from private field"),y?y.call(u):g.get(u)),z=(u,g,y)=>g.has(u)?he("Cannot add the same private member more than once"):g instanceof WeakSet?g.add(u):g.set(u,y),A=(u,g,y,m)=>(ue(u,g,"write to private field"),m?m.call(u,y):g.set(u,y),y);var _,b,N,R,E;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 m=(e=>(e[e.UserNotExist=0]="UserNotExist",e[e.PasswordInvalid=1]="PasswordInvalid",e[e.EmailNotExist=2]="EmailNotExist",e[e.UsernameOrPasswordInvalid=3]="UsernameOrPasswordInvalid",e[e.InvalidClientId=4]="InvalidClientId",e[e.ClientExists=5]="ClientExists",e[e.InvalidClientSecret=6]="InvalidClientSecret",e[e.InvalidClientIdOrSecret=7]="InvalidClientIdOrSecret",e[e.InvalidRedirectUri=8]="InvalidRedirectUri",e[e.InvalidOAuthFlow=9]="InvalidOAuthFlow",e[e.UserNotActive=10]="UserNotActive",e[e.EmailNotVerified=11]="EmailNotVerified",e[e.TwoFactorIncomplete=12]="TwoFactorIncomplete",e[e.Unauthorized=13]="Unauthorized",e[e.UnauthorizedClient=14]="UnauthorizedClient",e[e.InvalidScope=15]="InvalidScope",e[e.InsufficientScope=16]="InsufficientScope",e[e.InsufficientPriviledges=17]="InsufficientPriviledges",e[e.Forbidden=18]="Forbidden",e[e.InvalidKey=19]="InvalidKey",e[e.InvalidCsrf=20]="InvalidCsrf",e[e.InvalidSession=21]="InvalidSession",e[e.Expired=22]="Expired",e[e.Connection=23]="Connection",e[e.InvalidHash=24]="InvalidHash",e[e.UnsupportedAlgorithm=25]="UnsupportedAlgorithm",e[e.KeyExists=26]="KeyExists",e[e.PasswordChangeNeeded=27]="PasswordChangeNeeded",e[e.PasswordResetNeeded=28]="PasswordResetNeeded",e[e.Factor2ResetNeeded=29]="Factor2ResetNeeded",e[e.Configuration=30]="Configuration",e[e.InvalidEmail=31]="InvalidEmail",e[e.InvalidPhoneNumber=32]="InvalidPhoneNumber",e[e.InvalidUsername=33]="InvalidUsername",e[e.PasswordMatch=34]="PasswordMatch",e[e.InvalidToken=35]="InvalidToken",e[e.MfaRequired=36]="MfaRequired",e[e.PasswordFormat=37]="PasswordFormat",e[e.DataFormat=38]="DataFormat",e[e.FetchError=39]="FetchError",e[e.UserExists=40]="UserExists",e[e.FormEntry=41]="FormEntry",e[e.BadRequest=42]="BadRequest",e[e.AuthorizationPending=43]="AuthorizationPending",e[e.SlowDown=44]="SlowDown",e[e.ExpiredToken=45]="ExpiredToken",e[e.ConstraintViolation=46]="ConstraintViolation",e[e.NotImplemented=47]="NotImplemented",e[e.UnknownError=48]="UnknownError",e))(m||{});class w extends Error{constructor(r,n=void 0){let i,o=500;r==0?(i="User does not exist",o=401):r==1?(i="Password doesn't match",o=401):r==3?(i="Username or password incorrect",o=401):r==4?(i="Client id is invalid",o=401):r==5?(i="Client ID or name already exists",o=500):r==6?(i="Client secret is invalid",o=401):r==7?(i="Client id or secret is invalid",o=401):r==8?(i="Redirect Uri is not registered",o=401):r==9?(i="Invalid OAuth flow type",o=500):r==2?(i="No user exists with that email address",o=401):r==10?(i="Account is not active",o=403):r==33?(i="Username is not in an allowed format",o=400):r==31?(i="Email is not in an allowed format",o=400):r==32?(i="Phone number is not in an allowed format",o=400):r==11?(i="Email address has not been verified",o=403):r==12?(i="Two-factor setup is not complete",o=403):r==13?(i="Not authorized",o=401):r==14?(i="Client not authorized",o=401):r==15?(i="Invalid scope",o=403):r==16?(i="Insufficient scope",o=403):r==23?i="Connection failure":r==22?(i="Token has expired",o=401):r==24?i="Hash is not in a valid format":r==19?(i="Key is invalid",o=401):r==18?(i="You do not have permission to access this resource",o=403):r==17?(i="You do not have the right privileges to access this resource",o=401):r==20?(i="CSRF token is invalid",o=401):r==21?(i="Session cookie is invalid",o=401):r==25?i="Algorithm not supported":r==26?i="Attempt to create a key that already exists":r==27?(i="User must change password",o=403):r==28?(i="User must reset password",o=403):r==29?(i="User must reset 2FA",o=403):r==30?i="There was an error in the configuration":r==34?(i="Passwords do not match",o=401):r==35?(i="Token is not valid",o=401):r==36?(i="MFA is required",o=401):r==37?(i="Password format was incorrect",o=401):r==40?(i="User already exists",o=400):r==42?(i="The request is invalid",o=400):r==38?(i="Session data has unexpected format",o=500):r==39?(i="Couldn't execute a fetch",o=500):r==43?(i="Waiting for authorization",o=200):r==44?(i="Slow polling down by 5 seconds",o=200):r==45?(i="Token has expired",o=401):r==46?(i="Database update/insert caused a constraint violation",o=500):r==47?(i="This method has not been implemented",o=500):(i="Unknown error",o=500),n!=null&&!Array.isArray(n)?i=n:Array.isArray(n)&&(i=n.join(". "));super(i);a(this,"isCrossauthError",!0);a(this,"httpStatus");a(this,"code");a(this,"codeName");a(this,"messages");this.code=r,this.codeName=m[r],this.httpStatus=o,this.name="CrossauthError",Array.isArray(n)?this.messages=n:this.messages=[i],Object.setPrototypeOf(this,w.prototype)}static fromOAuthError(r,n){let i;switch(r){case"invalid_request":i=42;break;case"unauthorized_client":i=14;break;case"access_denied":i=13;break;case"unsupported_response_type":i=42;break;case"invalid_scope":i=15;break;case"server_error":i=48;break;case"temporarily_unavailable":i=23;break;case"invalid_token":i=35;break;case"expired_token":i=45;break;case"insufficient_scope":i=35;break;case"mfa_required":i=36;break;case"authorization_pending":i=43;break;case"slow_down":i=44;break;default:i=48}return new w(i,n)}get oauthErrorCode(){switch(this.code){case 42:return"invalid_request";case 14:return"unauthorized_client";case 13:return"access_denied";case 15:return"invalid_scope";case 23:return"temporarily_unavailable";case 35:return"invalid_token";case 36:return"mfa_required";case 43:return"authorization_pending";case 44:return"slow_down";case 45:return"expired_token";case 22:return"expired_token";default:return"server_error"}}static asCrossauthError(r,n){if(r instanceof Error)return"isCrossauthError"in r?r:new w(48,r.message);if("errorCode"in r){let o=48;try{o=Number(r.errorCode)??48}catch{}let s=n??m[o];return"errorMessage"in r?s=r.errorMessage:"message"in r&&(s=r.message),new w(o,s)}let i=n??m[48];return"message"in r&&(i=r.message),new w(48,i)}}function fe(e){return typeof e=="number"&&(e=""+e),e in L?L[e]:L[500]}const L={200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Unused",307:"Temporary Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Required",413:"Request Entry Too Large",414:"Request-URI Too Long",415:"Unsupported Media Type",416:"Requested Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",429:"Too Many Requests",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported"},S=class S{constructor(t){a(this,"level");if(t)this.level=t;else if(typeof process<"u"&&"CROSSAUTH_LOG_LEVEL"in process.env){const r=(process.env.CROSSAUTH_LOG_LEVEL??"ERROR").toUpperCase();S.levelName.includes(r)?this.level=S.levelName.indexOf(r):this.level=S.Error}else this.level=S.Error}static get logger(){return globalThis.crossauthLogger}setLevel(t){this.level=t}log(t,r){t<=this.level&&(typeof r=="string"?console.log("Crossauth "+S.levelName[t]+" "+new Date().toISOString(),r):console.log(JSON.stringify({level:S.levelName[t],time:new Date().toISOString(),...r})))}error(t){this.log(S.Error,t)}warn(t){this.log(S.Warn,t)}info(t){this.log(S.Info,t)}debug(t){this.log(S.Debug,t)}static setLogger(t,r){globalThis.crossauthLogger=t,globalThis.crossauthLoggerAcceptsJson=r}};a(S,"None",0),a(S,"Error",1),a(S,"Warn",2),a(S,"Info",3),a(S,"Debug",4),a(S,"levelName",["NONE","ERROR","WARN","INFO","DEBUG"]);let c=S;function h(e){let t;typeof e=="object"&&"err"in e&&typeof e.err=="object"&&(t=e.err.stack);try{typeof e=="object"&&"err"in e&&typeof e.err=="object"&&e.err&&"message"in e.err&&!("msg"in e)&&(e.msg=e.err.message)}catch{}try{typeof e=="object"&&"err"in e&&typeof e.err=="object"&&(e.err={...e.err,stack:t})}catch{}try{typeof e=="object"&&"err"in e&&!("msg"in e)&&(e.msg=e.msg="An unknown error occurred")}catch{}try{typeof e=="object"&&"cerr"in e&&"isCrossauthError"in e.cerr&&e.cerr&&(e.errorCode=e.cerr.code,e.errorCodeName=e.cerr.codeName,e.httpStatus=e.cerr.httpStatus,"msg"in e||(e.msg=e.cerr.message),delete e.cerr)}catch{}return typeof e=="string"||globalThis.crossauthLoggerAcceptsJson?e:JSON.stringify(e)}globalThis.crossauthLogger=new c(c.None),globalThis.crossauthLoggerAcceptsJson=!0;const V={issuer:"",authorization_endpoint:"",token_endpoint:"",jwks_uri:"",response_types_supported:[],subject_types_supported:[],response_modes_supported:["query","fragment"],grant_types_supported:["authorization_code","implicit"],id_token_signing_alg_values_supported:[],claim_types_supported:["normal"],claims_parameter_supported:!1,request_parameter_supported:!1,request_uri_parameter_supported:!0,require_request_uri_registration:!1},W=crypto,Q=e=>e instanceof CryptoKey,H=new TextEncoder,D=new TextDecoder;function pe(...e){const t=e.reduce((i,{length:o})=>i+o,0),r=new Uint8Array(t);let n=0;for(const i of e)r.set(i,n),n+=i.length;return r}const ge=e=>{const t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r},U=e=>{let t=e;t instanceof Uint8Array&&(t=D.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return ge(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class J extends Error{static get code(){return"ERR_JOSE_GENERIC"}constructor(t){var r;super(t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(r=Error.captureStackTrace)==null||r.call(Error,this,this.constructor)}}class k extends J{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}}class C extends J{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}}class K extends J{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}static get code(){return"ERR_JWT_INVALID"}}class ye extends J{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,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function q(e,t){return e.name===t}function j(e){return parseInt(e.name.slice(4),10)}function me(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function we(e,t){if(t.length&&!t.some(r=>e.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(t.length>2){const n=t.pop();r+=`one of ${t.join(", ")}, or ${n}.`}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}function ve(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!q(e.algorithm,"HMAC"))throw I("HMAC");const n=parseInt(t.slice(2),10);if(j(e.algorithm.hash)!==n)throw I(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!q(e.algorithm,"RSASSA-PKCS1-v1_5"))throw I("RSASSA-PKCS1-v1_5");const n=parseInt(t.slice(2),10);if(j(e.algorithm.hash)!==n)throw I(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!q(e.algorithm,"RSA-PSS"))throw I("RSA-PSS");const n=parseInt(t.slice(2),10);if(j(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(!q(e.algorithm,"ECDSA"))throw I("ECDSA");const n=me(t);if(e.algorithm.namedCurve!==n)throw I(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}we(e,r)}function Z(e,t,...r){var n;if(r.length>2){const i=r.pop();e+=`one of type ${r.join(", ")}, or ${i}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&(n=t.constructor)!=null&&n.name&&(e+=` Received an instance of ${t.constructor.name}`),e}const ee=(e,...t)=>Z("Key must be ",e,...t);function te(e,t,...r){return Z(`Key for the ${e} algorithm must be `,t,...r)}const re=e=>Q(e)?!0:(e==null?void 0:e[Symbol.toStringTag])==="KeyObject",F=["CryptoKey"],Se=(...e)=>{const t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(const n of t){const i=Object.keys(n);if(!r||r.size===0){r=new Set(i);continue}for(const o of i){if(r.has(o))return!1;r.add(o)}}return!0};function _e(e){return typeof e=="object"&&e!==null}function x(e){if(!_e(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}const Ce=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};function be(e){let t,r;switch(e.kty){case"RSA":{switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new k('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new k('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(e.alg){case"EdDSA":t={name:e.crv},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new 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:t,keyUsages:r}}const ie=async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:r}=be(e),n=[t,e.ext??!1,e.key_ops??r],i={...e};return delete i.alg,delete i.use,W.subtle.importKey("jwk",i,...n)},ne=e=>U(e);let G,Y;const oe=e=>(e==null?void 0:e[Symbol.toStringTag])==="KeyObject",se=async(e,t,r,n)=>{let i=e.get(t);if(i!=null&&i[n])return i[n];const o=await ie({...r,alg:n});return i?i[n]=o:e.set(t,{[n]:o}),o},Ae={normalizePublicKey:(e,t)=>{if(oe(e)){let r=e.export({format:"jwk"});return delete r.d,delete r.dp,delete r.dq,delete r.p,delete r.q,delete r.qi,r.k?ne(r.k):(Y||(Y=new WeakMap),se(Y,e,r,t))}return e},normalizePrivateKey:(e,t)=>{if(oe(e)){let r=e.export({format:"jwk"});return r.k?ne(r.k):(G||(G=new WeakMap),se(G,e,r,t))}return e}},T=(e,t,r=0)=>{r===0&&(t.unshift(t.length),t.unshift(6));const n=e.indexOf(t[0],r);if(n===-1)return!1;const i=e.subarray(n,n+t.length);return i.length!==t.length?!1:i.every((o,s)=>o===t[s])||T(e,t,n+1)},ae=e=>{switch(!0){case T(e,[42,134,72,206,61,3,1,7]):return"P-256";case T(e,[43,129,4,0,34]):return"P-384";case T(e,[43,129,4,0,35]):return"P-521";case T(e,[43,101,110]):return"X25519";case T(e,[43,101,111]):return"X448";case T(e,[43,101,112]):return"Ed25519";case T(e,[43,101,113]):return"Ed448";default:throw new k("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},ce=async(e,t,r,n,i)=>{let o,s;const l=new Uint8Array(atob(r.replace(e,"")).split("").map(v=>v.charCodeAt(0))),f=t==="spki";switch(n){case"PS256":case"PS384":case"PS512":o={name:"RSA-PSS",hash:`SHA-${n.slice(-3)}`},s=f?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":o={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.slice(-3)}`},s=f?["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=f?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":o={name:"ECDSA",namedCurve:"P-256"},s=f?["verify"]:["sign"];break;case"ES384":o={name:"ECDSA",namedCurve:"P-384"},s=f?["verify"]:["sign"];break;case"ES512":o={name:"ECDSA",namedCurve:"P-521"},s=f?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{const v=ae(l);o=v.startsWith("P-")?{name:"ECDH",namedCurve:v}:{name:v},s=f?[]:["deriveBits"];break}case"EdDSA":o={name:ae(l)},s=f?["verify"]:["sign"];break;default:throw new k('Invalid or unsupported "alg" (Algorithm) value')}return W.subtle.importKey(t,l,o,!1,s)},ke=(e,t,r)=>ce(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t),Ie=(e,t,r)=>ce(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",e,t);async function Pe(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return Ie(e,t)}async function Te(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return ke(e,t)}async function de(e,t){if(!x(e))throw new TypeError("JWK must be an object");switch(t||(t=e.alg),e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return U(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 ie({...e,alg:t});default:throw new k('Unsupported "kty" (Key Type) Parameter value')}}const M=e=>e==null?void 0:e[Symbol.toStringTag],Re=(e,t)=>{if(!(t instanceof Uint8Array)){if(!re(t))throw new TypeError(te(e,t,...F,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${M(t)} instances for symmetric algorithms must be of type "secret"`)}},Ee=(e,t,r)=>{if(!re(t))throw new TypeError(te(e,t,...F));if(t.type==="secret")throw new TypeError(`${M(t)} instances for asymmetric algorithms must not be of type "secret"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${M(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${M(t)} instances for asymmetric algorithm encryption must be of type "public"`)},Oe=(e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?Re(e,t):Ee(e,t,r)};function Ke(e,t,r,n,i){if(i.crit!==void 0&&(n==null?void 0:n.crit)===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(s=>typeof s!="string"||s.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let o;o=t;for(const s of n.crit){if(!o.has(s))throw new 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 Ue(e,t){const r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"EdDSA":return{name:t.name};default:throw new k(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function Ne(e,t,r){if(t=await Ae.normalizePublicKey(t,e),Q(t))return ve(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(ee(t,...F));return W.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(ee(t,...F,"Uint8Array"))}const ze=async(e,t,r,n)=>{const i=await Ne(e,t,"verify");Ce(e,i);const o=Ue(e,i.algorithm);try{return await W.subtle.verify(o,i,r,n)}catch{return!1}};async function De(e,t,r){if(!x(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&&!x(e.header))throw new C("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{const Fe=U(e.protected);n=JSON.parse(D.decode(Fe))}catch{throw new C("JWS Protected Header is invalid")}if(!Se(n,e.header))throw new C("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const i={...n,...e.header},o=Ke(C,new Map([["b64",!0]]),r==null?void 0:r.crit,n,i);let s=!0;if(o.has("b64")&&(s=n.b64,typeof s!="boolean"))throw new C('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:l}=i;if(typeof l!="string"||!l)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 f=!1;typeof t=="function"&&(t=await t(n,e),f=!0),Oe(l,t,"verify");const v=pe(H.encode(e.protected??""),H.encode("."),typeof e.payload=="string"?H.encode(e.payload):e.payload);let O;try{O=U(e.signature)}catch{throw new C("Failed to base64url decode the signature")}if(!await ze(l,t,O,v))throw new ye;let $;if(s)try{$=U(e.payload)}catch{throw new C("Failed to base64url decode the payload")}else typeof e.payload=="string"?$=H.encode(e.payload):$=e.payload;const B={payload:$};return e.protected!==void 0&&(B.protectedHeader=n),e.header!==void 0&&(B.unprotectedHeader=e.header),f?{...B,key:t}:B}async function xe(e,t,r){if(e instanceof Uint8Array&&(e=D.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 l=await De({payload:i,protected:n,signature:o},t,r),f={payload:l.payload,protectedHeader:l.protectedHeader};return typeof t=="function"?{...f,key:l.key}:f}const le=U;function We(e){let t;if(typeof e=="string"){const r=e.split(".");(r.length===3||r.length===5)&&([t]=r)}else if(typeof e=="object"&&e)if("protected"in e)t=e.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof t!="string"||!t)throw new Error;const r=JSON.parse(D.decode(le(t)));if(!x(r))throw new Error;return r}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}function He(e){if(typeof e!="string")throw new K("JWTs must use Compact JWS serialization, JWT must be a string");const{1:t,length:r}=e.split(".");if(r===5)throw new K("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new K("Invalid JWT");if(!t)throw new K("JWTs must contain a payload");let n;try{n=le(t)}catch{throw new K("Failed to base64url decode the payload")}let i;try{i=JSON.parse(D.decode(n))}catch{throw new K("Failed to parse the decoded payload as JSON")}if(!x(i))throw new K("Invalid JWT Claims Set");return i}const d=class d{static flowNames(t){let r={};return t.forEach(n=>{n in d.flowName&&(r[n]=d.flowName[n])}),r}static isValidFlow(t){return d.allFlows().includes(t)}static areAllValidFlows(t){let r=!0;return t.forEach(n=>{d.isValidFlow(n)||(r=!1)}),r}static allFlows(){return[d.AuthorizationCode,d.AuthorizationCodeWithPKCE,d.ClientCredentials,d.RefreshToken,d.DeviceCode,d.Password,d.PasswordMfa,d.OidcAuthorizationCode]}static grantType(t){switch(t){case d.AuthorizationCode:case d.AuthorizationCodeWithPKCE:case d.OidcAuthorizationCode:return["authorization_code"];case d.ClientCredentials:return["client_credentials"];case d.RefreshToken:return["refresh_token"];case d.Password:return["password"];case d.PasswordMfa:return["http://auth0.com/oauth/grant-type/mfa-otp","http://auth0.com/oauth/grant-type/mfa-oob"];case d.DeviceCode:return["urn:ietf:params:oauth:grant-type:device_code"]}}};a(d,"All","all"),a(d,"AuthorizationCode","authorizationCode"),a(d,"AuthorizationCodeWithPKCE","authorizationCodeWithPKCE"),a(d,"ClientCredentials","clientCredentials"),a(d,"RefreshToken","refreshToken"),a(d,"DeviceCode","deviceCode"),a(d,"Password","password"),a(d,"PasswordMfa","passwordMfa"),a(d,"OidcAuthorizationCode","oidcAuthorizationCode"),a(d,"flowName",{[d.AuthorizationCode]:"Authorization Code",[d.AuthorizationCodeWithPKCE]:"Authorization Code with PKCE",[d.ClientCredentials]:"Client Credentials",[d.RefreshToken]:"Refresh Token",[d.DeviceCode]:"Device Code",[d.Password]:"Password",[d.PasswordMfa]:"Password MFA",[d.OidcAuthorizationCode]:"OIDC Authorization Code"});let X=d;class Je{constructor({authServerBaseUrl:t,client_id:r,client_secret:n,redirect_uri:i,codeChallengeMethod:o,stateLength:s,verifierLength:l,tokenConsumer:f,authServerCredentials:v,authServerMode:O,authServerHeaders:P}){a(this,"authServerBaseUrl","");z(this,_);z(this,b);z(this,N);a(this,"codeChallengeMethod","S256");z(this,R);a(this,"verifierLength",32);a(this,"redirect_uri");z(this,E,"");a(this,"stateLength",32);a(this,"authzCode","");a(this,"oidcConfig");a(this,"tokenConsumer");a(this,"authServerHeaders",{});a(this,"authServerMode");a(this,"authServerCredentials");this.tokenConsumer=f,this.authServerBaseUrl=t,l&&(this.verifierLength=l),s&&(this.stateLength=s),r&&A(this,_,r),n&&A(this,b,n),i&&(this.redirect_uri=i),o&&(this.codeChallengeMethod=o),this.authServerBaseUrl=t,v&&(this.authServerCredentials=v),O&&(this.authServerMode=O),P&&(this.authServerHeaders=P)}set client_id(t){A(this,_,t)}set client_secret(t){A(this,b,t)}set codeVerifier(t){A(this,R,t)}set codeChallenge(t){A(this,N,t)}set state(t){A(this,E,t)}async loadConfig(t){if(t){c.logger.debug(h({msg:"Reading OIDC config locally"})),this.oidcConfig=t;return}let r;try{const n=new URL(this.authServerBaseUrl+"/.well-known/openid-configuration");c.logger.debug(h({msg:`Fetching OIDC config from ${n}`}));let i={headers:this.authServerHeaders};this.authServerMode&&(i.mode=this.authServerMode),this.authServerCredentials&&(i.credentials=this.authServerCredentials),r=await fetch(n,i)}catch(n){c.logger.error(h({err:n}))}if(!r||!r.ok)throw new w(m.Connection,"Couldn't get OIDC configuration from URL"+this.authServerBaseUrl+"/.well-known/openid-configuration");this.oidcConfig={...V};try{const n=await r.json();for(const[i,o]of Object.entries(n))this.oidcConfig[i]=o}catch{throw new w(m.Connection,"Unrecognized response from OIDC configuration endpoint")}}getOidcConfig(){return this.oidcConfig}async startAuthorizationCodeFlow(t,r=!1){var o,s,l;if(c.logger.debug(h({msg:"Starting authorization code flow"})),this.oidcConfig||await this.loadConfig(),!((o=this.oidcConfig)!=null&&o.response_types_supported.includes("code"))||!((s=this.oidcConfig)!=null&&s.response_modes_supported.includes("query")))return{error:"invalid_request",error_description:"Server does not support authorization code flow"};if(!((l=this.oidcConfig)!=null&&l.authorization_endpoint))return{error:"server_error",error_description:"Cannot get authorize endpoint"};if(A(this,E,this.randomValue(this.stateLength)),!p(this,_))return{error:"invalid_request",error_description:"Cannot make authorization code flow without client id"};if(!this.redirect_uri)return{error:"invalid_request",error_description:"Cannot make authorization code flow without Redirect Uri"};let i=this.oidcConfig.authorization_endpoint+"?response_type=code&client_id="+encodeURIComponent(p(this,_))+"&state="+encodeURIComponent(p(this,E))+"&redirect_uri="+encodeURIComponent(this.redirect_uri);return t&&(i+="&scope="+encodeURIComponent(t)),r&&(A(this,R,this.randomValue(this.verifierLength)),A(this,N,this.codeChallengeMethod=="plain"?p(this,R):await this.sha256(p(this,R))),i+="&code_challenge="+p(this,N)),{url:i}}async redirectEndpoint(t,r,n,i){var v,O;if(this.oidcConfig||await this.loadConfig(),n||!t)return n||(n="server_error"),i||(i="Unknown error"),{error:n,error_description:i};if(p(this,E)&&r!=p(this,E))return{error:"access_denied",error_description:"State is not valid"};if(this.authzCode=t,!((v=this.oidcConfig)!=null&&v.grant_types_supported.includes("authorization_code")))return{error:"invalid_request",error_description:"Server does not support authorization code grant"};if(!((O=this.oidcConfig)!=null&&O.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const o=this.oidcConfig.token_endpoint;let s,l;s="authorization_code",l=p(this,b);let f={grant_type:s,client_id:p(this,_),code:this.authzCode};l&&(f.client_secret=l),f.code_verifier=p(this,R);try{const P=await this.post(o,f,this.authServerHeaders);return P.id_token&&!await this.validateIdToken(P.id_token)?{error:"access_denied",error_description:"Invalid ID token"}:P}catch(P){return c.logger.error(h({err:P})),{error:"server_error",error_description:"Unable to get access token from server"}}}async clientCredentialsFlow(t){var i,o;if(c.logger.debug(h({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(!p(this,_))return{error:"invalid_request",error_description:"Cannot make client credentials flow without client id"};const r=this.oidcConfig.token_endpoint;let n={grant_type:"client_credentials",client_id:p(this,_),client_secret:p(this,b)};t&&(n.scope=t);try{return await this.post(r,n,this.authServerHeaders)}catch(s){return c.logger.error(h({err:s})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async passwordFlow(t,r,n){var s,l;if(c.logger.debug(h({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(!((l=this.oidcConfig)!=null&&l.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:p(this,_),client_secret:p(this,b),username:t,password:r};n&&(o.scope=n);try{let f=await this.post(i,o,this.authServerHeaders);return f.id_token&&!await this.validateIdToken(f.id_token)?{error:"access_denied",error_description:"Invalid ID token"}:f}catch(f){return c.logger.error(h({err:f})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async mfaAuthenticators(t){var o,s,l;if(c.logger.debug(h({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(!((l=this.oidcConfig)!=null&&l.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const r=this.oidcConfig.issuer+(this.oidcConfig.issuer.endsWith("/")?"":"/")+"mfa/authenticators",n=await this.get(r,{authorization:"Bearer "+t,...this.authServerHeaders});if(!Array.isArray(n))return{error:"server_error",error_description:"Expected array of authenticators in mfa/authenticators response"};let i=[];for(let f=0;f<n.length;++f){const v=n[f];if(!v.id||!v.authenticator_type||!v.active)return{error:"server_error",error_description:"Invalid mfa/authenticators response"};i.push({id:v.id,authenticator_type:v.authenticator_type,active:v.active,name:v.name,oob_channel:v.oob_channel})}return{authenticators:i}}async mfaOtpRequest(t,r){var o,s;if(c.logger.debug(h({msg:"Making MFA OTB request"})),this.oidcConfig||await this.loadConfig(),!((o=this.oidcConfig)!=null&&o.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((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:p(this,_),client_secret:p(this,b),challenge_type:"otp",mfa_token:t,authenticator_id:r},this.authServerHeaders);return i.challenge_type!="otp"?{error:i.error??"server_error",error_description:i.error_description??"Invalid OTP challenge response"}:i}async mfaOtpComplete(t,r,n){var s,l;if(c.logger.debug(h({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(!((l=this.oidcConfig)!=null&&l.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:p(this,_),client_secret:p(this,b),challenge_type:"otp",mfa_token:t,otp:r,scope:n},this.authServerHeaders);return{id_token:o.id_token,access_token:o.access_token,refresh_token:o.refresh_token,expires_in:Number(o.expires_in),scope:o.scope,token_type:o.token_type,error:o.error,error_description:o.error_description}}async mfaOobRequest(t,r){var o,s;if(c.logger.debug(h({msg:"Making MFA OOB request"})),this.oidcConfig||await this.loadConfig(),!((o=this.oidcConfig)!=null&&o.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((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:p(this,_),client_secret:p(this,b),challenge_type:"oob",mfa_token:t,authenticator_id:r},this.authServerHeaders);return i.challenge_type!="oob"||!i.oob_code||!i.binding_method?{error:i.error??"server_error",error_description:i.error_description??"Invalid OOB challenge response"}:{challenge_type:i.challenge_type,oob_code:i.oob_code,binding_method:i.binding_method,error:i.error,error_description:i.error_description}}async mfaOobComplete(t,r,n,i){var l,f;if(c.logger.debug(h({msg:"Completing MFA OOB request"})),this.oidcConfig||await this.loadConfig(),!((l=this.oidcConfig)!=null&&l.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(!((f=this.oidcConfig)!=null&&f.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:p(this,_),client_secret:p(this,b),challenge_type:"otp",mfa_token:t,oob_code:r,binding_code:n,scope:i},this.authServerHeaders);return s.error?{error:s.error,error_description:s.error_description}:s.id_token&&!await this.validateIdToken(s.id_token)?{error:"access_denied",error_description:"Invalid ID token"}:{id_token:s.id_token,access_token:s.access_token,refresh_token:s.refresh_token,expires_in:"expires_in"in s?Number(s.expires_in):void 0,scope:s.scope,token_type:s.token_type}}async refreshTokenFlow(t){var o,s;if(c.logger.debug(h({msg:"Starting refresh token flow"})),this.oidcConfig||await this.loadConfig(),!((o=this.oidcConfig)!=null&&o.grant_types_supported.includes("refresh_token")))return{error:"invalid_request",error_description:"Server does not support refresh_token grant"};if(!((s=this.oidcConfig)!=null&&s.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const r=this.oidcConfig.token_endpoint;let n;n=p(this,b);let i={grant_type:"refresh_token",refresh_token:t,client_id:p(this,_)};n&&(i.client_secret=n);try{let l=await this.post(r,i,this.authServerHeaders);return l.id_token&&!await this.validateIdToken(l.id_token)?{error:"access_denied",error_description:"Invalid ID token"}:l}catch(l){return c.logger.error(h({err:l})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async startDeviceCodeFlow(t,r){var i;if(c.logger.debug(h({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:p(this,_),client_secret:p(this,b)};r&&(n.scope=r);try{let o=await this.post(t,n,this.authServerHeaders);return o.id_token&&!await this.validateIdToken(o.id_token)?{error:"access_denied",error_description:"Invalid ID token"}:o}catch(o){return c.logger.error(h({err:o})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async pollDeviceCodeFlow(t){var n,i,o;if(c.logger.debug(h({msg:"Starting device code flow"})),this.oidcConfig||await this.loadConfig(),!((n=this.oidcConfig)!=null&&n.grant_types_supported.includes("urn:ietf:params:oauth:grant-type:device_code")))return{error:"invalid_request",error_description:"Server does not support device code grant"};if(!((i=this.oidcConfig)!=null&&i.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};let r={grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:p(this,_),client_secret:p(this,b),device_code:t};try{const s=await this.post((o=this.oidcConfig)==null?void 0:o.token_endpoint,r,this.authServerHeaders);return s.error?s:s.id_token&&!await this.validateIdToken(s.id_token)?{error:"access_denied",error_description:"Invalid ID token"}:s}catch(s){return c.logger.error(h({err:s})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async post(t,r,n={}){c.logger.debug(h({msg:"Fetch POST",url:t,params:Object.keys(r)}));let i={};return this.authServerCredentials&&(i.credentials=this.authServerCredentials),this.authServerMode&&(i.mode=this.authServerMode),await(await fetch(t,{method:"POST",...i,headers:{Accept:"application/json","Content-Type":"application/json",...n},body:JSON.stringify(r)})).json()}async get(t,r={}){c.logger.debug(h({msg:"Fetch GET",url:t}));let n={};return this.authServerCredentials&&(n.credentials=this.authServerCredentials),this.authServerMode&&(n.mode=this.authServerMode),await(await fetch(t,{method:"GET",...n,headers:{Accept:"application/json","Content-Type":"application/json",...r}})).json()}async validateIdToken(t){try{return await this.tokenConsumer.tokenAuthorized(t,"id")}catch{return}}async idTokenAuthorized(t){try{return await this.tokenConsumer.tokenAuthorized(t,"id")}catch(r){c.logger.warn(h({err:r}));return}}getTokenPayload(t){return He(t)}}_=new WeakMap,b=new WeakMap,N=new WeakMap,R=new WeakMap,E=new WeakMap;class qe{constructor(t,r={}){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=t,r.authServerBaseUrl&&(this.authServerBaseUrl=r.authServerBaseUrl),r.jwtKeyType&&(this.jwtKeyType=r.jwtKeyType),r.jwtSecretKey&&(this.jwtSecretKey=r.jwtSecretKey),r.jwtPublicKey&&(this.jwtPublicKey=r.jwtPublicKey),r.clockTolerance&&(this.clockTolerance=r.clockTolerance),r.oidcConfig&&(this.oidcConfig=r.oidcConfig),this.jwtPublicKey&&!this.jwtKeyType)throw new w(m.Configuration,"If specifying jwtPublic key, must also specify jwtKeyType")}async loadKeys(){try{if(this.jwtSecretKey){if(!this.jwtKeyType)throw new w(m.Configuration,"Must specify jwtKeyType if setting jwtSecretKey");this.keys._default=await Te(this.jwtSecretKey,this.jwtKeyType)}else if(this.jwtPublicKey){if(!this.jwtKeyType)throw new w(m.Configuration,"Must specify jwtKeyType if setting jwtPublicKey");const t=await Pe(this.jwtPublicKey,this.jwtKeyType);this.keys._default=t}else{if(this.oidcConfig||await this.loadConfig(),!this.oidcConfig)throw new w(m.Connection,"Load OIDC config before Jwks");await this.loadJwks()}}catch(t){throw c.logger.debug(h({err:t})),new w(m.Connection,"Couldn't load keys")}}async loadConfig(t){if(t){this.oidcConfig=t;return}if(!this.authServerBaseUrl)throw new w(m.Connection,"Couldn't get OIDC configuration. Either set authServerBaseUrl or set config manually");let r;try{r=await fetch(new URL("/.well-known/openid-configuration",this.authServerBaseUrl))}catch(n){c.logger.error(h({err:n}))}if(!r||!r.ok)throw new w(m.Connection,"Couldn't get OIDC configuration");this.oidcConfig={...V};try{const n=await r.json();for(const[i,o]of Object.entries(n))this.oidcConfig[i]=o}catch{throw new w(m.Connection,"Unrecognized response from OIDC configuration endpoint")}}async loadJwks(t){if(t){this.keys={};for(let r=0;r<t.keys.length;++r){const n=t.keys[r];this.keys[n.kid??"_default"]=await de(t.keys[r])}}else{if(!this.oidcConfig)throw new w(m.Connection,"Load OIDC config before Jwks");let r;try{r=await fetch(new URL(this.oidcConfig.jwks_uri))}catch(n){c.logger.error(h({err:n}))}if(!r||!r.ok)throw new w(m.Connection,"Couldn't get OIDC configuration");this.keys={};try{const n=await r.json();if(!("keys"in n)||!Array.isArray(n.keys))throw new w(m.Connection,"Couldn't fetch keys");for(let i=0;i<n.keys.length;++i)try{let o="_default";"kid"in n.keys[i]&&typeof n.keys[i]=="string"&&(o=String(n.keys[i]));const s=await de(n.keys[i]);this.keys[o]=s}catch(o){throw c.logger.error(h({err:o})),new w(m.Connection,"Couldn't load keys")}}catch(n){throw c.logger.error(h({err:n})),new w(m.Connection,"Unrecognized response from OIDC jwks endpoint")}}}async tokenAuthorized(t,r){(!this.keys||Object.keys(this.keys).length==0)&&await this.loadKeys();const n=await this.validateToken(t);if(n){if(n.type!=r){c.logger.error(h({msg:r+" expected but got "+n.type}));return}if(n.iss!=this.authServerBaseUrl){c.logger.error(h({msg:`Invalid issuer ${n.iss} in access token`,hashedAccessToken:await this.hash(n.jti)}));return}if(n.aud&&(Array.isArray(n.aud)&&!n.aud.includes(this.audience)||!Array.isArray(n.aud)&&n.aud!=this.audience)){c.logger.error(h({msg:`Invalid audience ${n.aud} in access token`,hashedAccessToken:await this.hash(n.jti)}));return}return n}}async validateToken(t){(!this.keys||Object.keys(this.keys).length==0)&&c.logger.warn("No keys loaded so cannot validate tokens");let r;try{r=We(t).kid}catch{c.logger.warn(h({msg:"Invalid access token format"}));return}let n;"_default"in this.keys&&(n=this.keys._default);for(let i in this.keys)if(r==i){n=this.keys[i];break}if(!n){c.logger.warn(h({msg:"No matching keys found for access token"}));return}try{const{payload:i}=await xe(t,n),o=JSON.parse(new TextDecoder().decode(i));if(o.exp*1e3<Date.now()+this.clockTolerance){c.logger.warn(h({msg:"Access token has expired"}));return}return o}catch{c.logger.warn(h({msg:"Access token did not validate"}));return}}}return u.CrossauthError=w,u.CrossauthLogger=c,u.DEFAULT_OIDCCONFIG=V,u.ErrorCode=m,u.KeyPrefix=y,u.OAuthClientBase=Je,u.OAuthFlows=X,u.OAuthTokenConsumerBase=qe,u.UserState=g,u.httpStatus=fe,u.j=h,Object.defineProperty(u,Symbol.toStringTag,{value:"Module"}),u}({});
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);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 s=this.oidcConfig.authorization_endpoint+"?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}({});

@@ -74,2 +74,5 @@ import { OpenIdConfiguration, OAuthTokenConsumerBase, GrantType } from '..';

id_token?: string;
id_payload?: {
[key: string]: any;
};
token_type?: string;

@@ -147,2 +150,5 @@ expires_in?: number;

protected authServerCredentials: "include" | "omit" | "same-origin" | undefined;
protected oauthPostType: "json" | "form";
protected oauthLogFetch: boolean;
protected oauthUseUserInfoEndpoint: boolean;
/**

@@ -192,5 +198,2 @@ * Constructor.

set client_secret(value: string);
set codeVerifier(value: string);
set codeChallenge(value: string);
set state(value: string);
/**

@@ -241,3 +244,3 @@ * Loads OpenID Connect configuration so that the client can determine

*/
startAuthorizationCodeFlow(scope?: string, pkce?: boolean): Promise<{
startAuthorizationCodeFlow(state: string, scope?: string, codeChallenge?: string, pkce?: boolean): Promise<{
url?: string;

@@ -247,2 +250,13 @@ error?: string;

}>;
protected codeChallengeAndVerifier(): Promise<{
codeChallenge: string;
codeVerifier: string;
}>;
protected getIdPayload(id_token: string, access_token?: string): Promise<{
payload?: {
[key: string]: any;
};
error?: string;
error_description?: string;
}>;
/**

@@ -268,3 +282,3 @@ * This implements the functionality behind the redirect URI

*/
protected redirectEndpoint(code?: string, state?: string, error?: string, errorDescription?: string): Promise<OAuthTokenResponse>;
protected redirectEndpoint(code?: string, scope?: string, codeVerifier?: string, error?: string, errorDescription?: string): Promise<OAuthTokenResponse>;
/**

@@ -412,2 +426,5 @@ * Performs the client credentials flow.

pollDeviceCodeFlow(deviceCode: string): Promise<OAuthTokenResponse>;
userInfoEndpoint(access_token: string): Promise<{
[key: string]: any;
}>;
/**

@@ -414,0 +431,0 @@ * Makes a POST request to the given URL using `fetch()`.

@@ -75,3 +75,3 @@ import { OpenIdConfiguration } from './wellknown';

*/
loadKeys(): Promise<void>;
loadKeys(defaultAlg?: string): Promise<void>;
/**

@@ -98,3 +98,3 @@ * Loads OpenID Connect configuration, or fetches it from the

keys: jose.JWK[];
}): Promise<void>;
}, defaultAlg?: string): Promise<void>;
/**

@@ -111,3 +111,3 @@ * Returns JWT payload if the token is valid, undefined otherwise.

*/
tokenAuthorized(token: string, tokenType: "access" | "refresh" | "id"): Promise<{
tokenAuthorized(token: string, _tokenType: "access" | "refresh" | "id"): Promise<{
[key: string]: any;

@@ -114,0 +114,0 @@ } | undefined>;

{
"name": "@crossauth/common",
"private": false,
"version": "0.0.30",
"version": "0.0.32",
"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

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc