New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@crossauth/common

Package Overview
Dependencies
Maintainers
0
Versions
34
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.14 to 0.0.15

6

dist/error.d.ts
/**
* Indicates the type of error reported by {@link @crossauth/common!CrossauthError}
* Indicates the type of error reported by {@link CrossauthError}
*/

@@ -140,3 +140,3 @@ export declare enum ErrorCode {

*
* @param error as returned by an OAuth call (converted to an {@link @crossauth/common!ErrorCode}).
* @param error as returned by an OAuth call (converted to an {@link ErrorCode}).
* @param error_description as returned by an OAuth call (put in the `message`)

@@ -152,3 +152,3 @@ * @returns a `CrossauthError` instance.

* CrossauthError from that and `errorMessage`, if present.
* Otherwise creates a `CrossauthError` object with {@link @crossauth/common!ErrorCode}
* Otherwise creates a `CrossauthError` object with {@link ErrorCode}
* of `Unknown` from it, setting the `message` if possible.

@@ -155,0 +155,0 @@ *

@@ -7,5 +7,5 @@ export { UserState, KeyPrefix } from './interfaces';

export { DEFAULT_OIDCCONFIG } from './oauth/wellknown';
export { OAuthClientBase, OAuthFlows, type OAuthTokenResponse, type MfaAuthenticatorResponse, type OAuthDeviceAuthorizationResponse, type OAuthDeviceResponse } from './oauth/client';
export { OAuthClientBase, OAuthFlows, type OAuthTokenResponse, type MfaAuthenticatorResponse, type MfaAuthenticatorsResponse, type OAuthDeviceAuthorizationResponse, type OAuthDeviceResponse } from './oauth/client';
export { OAuthTokenConsumerBase } from './oauth/tokenconsumer';
export type { OAuthTokenConsumerBaseOptions, EncryptionKey } from './oauth/tokenconsumer';
//# sourceMappingURL=index.d.ts.map

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

var crossauth_common=function(u){"use strict";var Me=Object.defineProperty;var he=u=>{throw TypeError(u)};var $e=(u,p,y)=>p in u?Me(u,p,{enumerable:!0,configurable:!0,writable:!0,value:y}):u[p]=y;var a=(u,p,y)=>$e(u,typeof p!="symbol"?p+"":p,y),ue=(u,p,y)=>p.has(u)||he("Cannot "+y);var f=(u,p,y)=>(ue(u,p,"read from private field"),y?y.call(u):p.get(u)),N=(u,p,y)=>p.has(u)?he("Cannot add the same private member more than once"):p instanceof WeakSet?p.add(u):p.set(u,y),A=(u,p,y,m)=>(ue(u,p,"write to private field"),m?m.call(u,y):p.set(u,y),y);var _,b,U,I,R;class p{}a(p,"active","active"),a(p,"disabled","disabled"),a(p,"awaitingTwoFactorSetup","awaitingtwofactorsetup"),a(p,"awaitingEmailVerification","awaitingemailverification"),a(p,"passwordChangeNeeded","passwordchangeneeded"),a(p,"passwordResetNeeded","passwordresetneeded"),a(p,"factor2ResetNeeded","factor2resetneeded"),a(p,"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,s=500;r==0?(i="User does not exist",s=401):r==1?(i="Password doesn't match",s=401):r==3?(i="Username or password incorrect",s=401):r==4?(i="Client id is invalid",s=401):r==5?(i="Client ID or name already exists",s=500):r==6?(i="Client secret is invalid",s=401):r==7?(i="Client id or secret is invalid",s=401):r==8?(i="Redirect Uri is not registered",s=401):r==9?(i="Invalid OAuth flow type",s=500):r==2?(i="No user exists with that email address",s=401):r==10?(i="Account is not active",s=403):r==33?(i="Username is not in an allowed format",s=400):r==31?(i="Email is not in an allowed format",s=400):r==32?(i="Phone number is not in an allowed format",s=400):r==11?(i="Email address has not been verified",s=403):r==12?(i="Two-factor setup is not complete",s=403):r==13?(i="Not authorized",s=401):r==14?(i="Client not authorized",s=401):r==15?(i="Invalid scope",s=403):r==16?(i="Insufficient scope",s=403):r==23?i="Connection failure":r==22?(i="Token has expired",s=401):r==24?i="Hash is not in a valid format":r==19?(i="Key is invalid",s=401):r==18?(i="You do not have permission to access this resource",s=403):r==17?(i="You do not have the right privileges to access this resource",s=401):r==20?(i="CSRF token is invalid",s=401):r==21?(i="Session cookie is invalid",s=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",s=403):r==28?(i="User must reset password",s=403):r==29?(i="User must reset 2FA",s=403):r==30?i="There was an error in the configuration":r==34?(i="Passwords do not match",s=401):r==35?(i="Token is not valid",s=401):r==36?(i="MFA is required",s=401):r==37?(i="Password format was incorrect",s=401):r==40?(i="User already exists",s=400):r==42?(i="The request is invalid",s=400):r==38?(i="Session data has unexpected format",s=500):r==39?(i="Couldn't execute a fetch",s=500):r==43?(i="Waiting for authorization",s=200):r==44?(i="Slow polling down by 5 seconds",s=200):r==45?(i="Token has expired",s=401):r==46?(i="Database update/insert caused a constraint violation",s=500):r==47?(i="This method has not been implemented",s=500):(i="Unknown error",s=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=s,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 s=48;try{s=Number(r.errorCode)??48}catch{}let o=n??m[s];return"errorMessage"in r?o=r.errorMessage:"message"in r&&(o=r.message),new w(s,o)}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 l(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,z=new TextDecoder;function pe(...e){const t=e.reduce((i,{length:s})=>i+s,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},K=e=>{let t=e;t instanceof Uint8Array&&(t=z.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 P 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 O 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 k(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 k("HMAC");const n=parseInt(t.slice(2),10);if(j(e.algorithm.hash)!==n)throw k(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!q(e.algorithm,"RSASSA-PKCS1-v1_5"))throw k("RSASSA-PKCS1-v1_5");const n=parseInt(t.slice(2),10);if(j(e.algorithm.hash)!==n)throw k(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!q(e.algorithm,"RSA-PSS"))throw k("RSA-PSS");const n=parseInt(t.slice(2),10);if(j(e.algorithm.hash)!==n)throw k(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw k("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!q(e.algorithm,"ECDSA"))throw k("ECDSA");const n=me(t);if(e.algorithm.namedCurve!==n)throw k(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 s of i){if(r.has(s))return!1;r.add(s)}}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 P('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 P('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 P('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new P('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=>K(e);let G,Y;const se=e=>(e==null?void 0:e[Symbol.toStringTag])==="KeyObject",oe=async(e,t,r,n)=>{let i=e.get(t);if(i!=null&&i[n])return i[n];const s=await ie({...r,alg:n});return i?i[n]=s:e.set(t,{[n]:s}),s},Ae={normalizePublicKey:(e,t)=>{if(se(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),oe(Y,e,r,t))}return e},normalizePrivateKey:(e,t)=>{if(se(e)){let r=e.export({format:"jwk"});return r.k?ne(r.k):(G||(G=new WeakMap),oe(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((s,o)=>s===t[o])||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 P("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},ce=async(e,t,r,n,i)=>{let s,o;const h=new Uint8Array(atob(r.replace(e,"")).split("").map(v=>v.charCodeAt(0))),g=t==="spki";switch(n){case"PS256":case"PS384":case"PS512":s={name:"RSA-PSS",hash:`SHA-${n.slice(-3)}`},o=g?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":s={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.slice(-3)}`},o=g?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":s={name:"RSA-OAEP",hash:`SHA-${parseInt(n.slice(-3),10)||1}`},o=g?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":s={name:"ECDSA",namedCurve:"P-256"},o=g?["verify"]:["sign"];break;case"ES384":s={name:"ECDSA",namedCurve:"P-384"},o=g?["verify"]:["sign"];break;case"ES512":s={name:"ECDSA",namedCurve:"P-521"},o=g?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{const v=ae(h);s=v.startsWith("P-")?{name:"ECDH",namedCurve:v}:{name:v},o=g?[]:["deriveBits"];break}case"EdDSA":s={name:ae(h)},o=g?["verify"]:["sign"];break;default:throw new P('Invalid or unsupported "alg" (Algorithm) value')}return W.subtle.importKey(t,h,s,!1,o)},Pe=(e,t,r)=>ce(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t),ke=(e,t,r)=>ce(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",e,t);async function Te(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return ke(e,t)}async function Ie(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return Pe(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 K(e.k);case"RSA":if(e.oth!==void 0)throw new P('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return ie({...e,alg:t});default:throw new P('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(o=>typeof o!="string"||o.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let s;s=t;for(const o of n.crit){if(!s.has(o))throw new P(`Extension Header Parameter "${o}" is not recognized`);if(i[o]===void 0)throw new e(`Extension Header Parameter "${o}" is missing`);if(s.get(o)&&n[o]===void 0)throw new e(`Extension Header Parameter "${o}" 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 P(`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 s=Ue(e,i.algorithm);try{return await W.subtle.verify(s,i,r,n)}catch{return!1}};async function xe(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=K(e.protected);n=JSON.parse(z.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},s=Ke(C,new Map([["b64",!0]]),r==null?void 0:r.crit,n,i);let o=!0;if(s.has("b64")&&(o=n.b64,typeof o!="boolean"))throw new C('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:h}=i;if(typeof h!="string"||!h)throw new C('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(o){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 g=!1;typeof t=="function"&&(t=await t(n,e),g=!0),Oe(h,t,"verify");const v=pe(H.encode(e.protected??""),H.encode("."),typeof e.payload=="string"?H.encode(e.payload):e.payload);let E;try{E=K(e.signature)}catch{throw new C("Failed to base64url decode the signature")}if(!await ze(h,t,E,v))throw new ye;let $;if(o)try{$=K(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),g?{...B,key:t}:B}async function De(e,t,r){if(e instanceof Uint8Array&&(e=z.decode(e)),typeof e!="string")throw new C("Compact JWS must be a string or Uint8Array");const{0:n,1:i,2:s,length:o}=e.split(".");if(o!==3)throw new C("Invalid Compact JWS");const h=await xe({payload:i,protected:n,signature:s},t,r),g={payload:h.payload,protectedHeader:h.protectedHeader};return typeof t=="function"?{...g,key:h.key}:g}const le=K;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(z.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 O("JWTs must use Compact JWS serialization, JWT must be a string");const{1:t,length:r}=e.split(".");if(r===5)throw new O("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new O("Invalid JWT");if(!t)throw new O("JWTs must contain a payload");let n;try{n=le(t)}catch{throw new O("Failed to base64url decode the payload")}let i;try{i=JSON.parse(z.decode(n))}catch{throw new O("Failed to parse the decoded payload as JSON")}if(!x(i))throw new O("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:s,stateLength:o,verifierLength:h,tokenConsumer:g,authServerCredentials:v,authServerMode:E,authServerHeaders:D}){a(this,"authServerBaseUrl","");N(this,_);N(this,b);N(this,U);a(this,"codeChallengeMethod","S256");N(this,I);a(this,"verifierLength",32);a(this,"redirect_uri");N(this,R,"");a(this,"stateLength",32);a(this,"authzCode","");a(this,"oidcConfig");a(this,"tokenConsumer");a(this,"authServerHeaders",{});a(this,"authServerMode");a(this,"authServerCredentials");this.tokenConsumer=g,this.authServerBaseUrl=t,h&&(this.verifierLength=h),o&&(this.stateLength=o),r&&A(this,_,r),n&&A(this,b,n),i&&(this.redirect_uri=i),s&&(this.codeChallengeMethod=s),this.authServerBaseUrl=t,v&&(this.authServerCredentials=v),E&&(this.authServerMode=E),D&&(this.authServerHeaders=D)}set client_id(t){A(this,_,t)}set client_secret(t){A(this,b,t)}set codeVerifier(t){A(this,I,t)}set codeChallenge(t){A(this,U,t)}set state(t){A(this,R,t)}async loadConfig(t){if(t){c.logger.debug(l({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(l({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(l({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,s]of Object.entries(n))this.oidcConfig[i]=s}catch{throw new w(m.Connection,"Unrecognized response from OIDC configuration endpoint")}}getOidcConfig(){return this.oidcConfig}async startAuthorizationCodeFlow(t,r=!1){var s,o,h;if(c.logger.debug(l({msg:"Starting authorization code flow"})),this.oidcConfig||await this.loadConfig(),!((s=this.oidcConfig)!=null&&s.response_types_supported.includes("code"))||!((o=this.oidcConfig)!=null&&o.response_modes_supported.includes("query")))return{error:"invalid_request",error_description:"Server does not support authorization code flow"};if(!((h=this.oidcConfig)!=null&&h.authorization_endpoint))return{error:"server_error",error_description:"Cannot get authorize endpoint"};if(A(this,R,this.randomValue(this.stateLength)),!f(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(f(this,_))+"&state="+encodeURIComponent(f(this,R))+"&redirect_uri="+encodeURIComponent(this.redirect_uri);return t&&(i+="&scope="+encodeURIComponent(t)),r&&(A(this,I,this.randomValue(this.verifierLength)),A(this,U,this.codeChallengeMethod=="plain"?f(this,I):await this.sha256(f(this,I))),i+="&code_challenge="+f(this,U)),{url:i}}async redirectEndpoint(t,r,n,i){var v,E;if(this.oidcConfig||await this.loadConfig(),n||!t)return n||(n="server_error"),i||(i="Unknown error"),{error:n,error_description:i};if(f(this,R)&&r!=f(this,R))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(!((E=this.oidcConfig)!=null&&E.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const s=this.oidcConfig.token_endpoint;let o,h;o="authorization_code",h=f(this,b);let g={grant_type:o,client_id:f(this,_),code:this.authzCode};h&&(g.client_secret=h),g.code_verifier=f(this,I);try{return this.post(s,g,this.authServerHeaders)}catch(D){return c.logger.error(l({err:D})),{error:"server_error",error_description:"Unable to get access token from server"}}}async clientCredentialsFlow(t){var i,s;if(c.logger.debug(l({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(!((s=this.oidcConfig)!=null&&s.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};if(!f(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:f(this,_),client_secret:f(this,b)};t&&(n.scope=t);try{return await this.post(r,n,this.authServerHeaders)}catch(o){return c.logger.error(l({err:o})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async passwordFlow(t,r,n){var o,h;if(c.logger.debug(l({msg:"Starting password flow"})),this.oidcConfig||await this.loadConfig(),!((o=this.oidcConfig)!=null&&o.grant_types_supported.includes("password")))return{error:"invalid_request",error_description:"Server does not support password grant"};if(!((h=this.oidcConfig)!=null&&h.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const i=this.oidcConfig.token_endpoint;let s={grant_type:"password",client_id:f(this,_),client_secret:f(this,b),username:t,password:r};n&&(s.scope=n);try{return await this.post(i,s,this.authServerHeaders)}catch(g){return c.logger.error(l({err:g})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async mfaAuthenticators(t){var s,o,h;if(c.logger.debug(l({msg:"Getting valid MFA authenticators"})),this.oidcConfig||await this.loadConfig(),!((s=this.oidcConfig)!=null&&s.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-otp"))&&((o=this.oidcConfig)!=null&&o.grant_types_supported.includes("http://auth0.com/oauth/grant-type/mfa-oob")))return{error:"invalid_request",error_description:"Server does not support password_mfa grant"};if(!((h=this.oidcConfig)!=null&&h.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 g=0;g<n.length;++g){const v=n[g];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 s,o;if(c.logger.debug(l({msg:"Making MFA OTB 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(!((o=this.oidcConfig)!=null&&o.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:f(this,_),client_secret:f(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 o,h;if(c.logger.debug(l({msg:"Completing MFA OTP 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(!((h=this.oidcConfig)!=null&&h.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const i=this.oidcConfig.token_endpoint,s=await this.post(i,{grant_type:"http://auth0.com/oauth/grant-type/mfa-otp",client_id:f(this,_),client_secret:f(this,b),challenge_type:"otp",mfa_token:t,otp:r,scope:n},this.authServerHeaders);return{id_token:s.id_token,access_token:s.access_token,refresh_token:s.refresh_token,expires_in:Number(s.expires_in),scope:s.scope,token_type:s.token_type,error:s.error,error_description:s.error_description}}async mfaOobRequest(t,r){var s,o;if(c.logger.debug(l({msg:"Making MFA OOB 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(!((o=this.oidcConfig)!=null&&o.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:f(this,_),client_secret:f(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 h,g;if(c.logger.debug(l({msg:"Completing MFA OOB request"})),this.oidcConfig||await this.loadConfig(),!((h=this.oidcConfig)!=null&&h.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(!((g=this.oidcConfig)!=null&&g.issuer))return{error:"server_error",error_description:"Cannot get issuer"};const s=this.oidcConfig.token_endpoint,o=await this.post(s,{grant_type:"http://auth0.com/oauth/grant-type/mfa-oob",client_id:f(this,_),client_secret:f(this,b),challenge_type:"otp",mfa_token:t,oob_code:r,binding_code:n,scope:i},this.authServerHeaders);return o.error?{error:o.error,error_description:o.error_description}:{id_token:o.id_token,access_token:o.access_token,refresh_token:o.refresh_token,expires_in:"expires_in"in o?Number(o.expires_in):void 0,scope:o.scope,token_type:o.token_type}}async refreshTokenFlow(t){var s,o;if(c.logger.debug(l({msg:"Starting refresh token flow"})),this.oidcConfig||await this.loadConfig(),!((s=this.oidcConfig)!=null&&s.grant_types_supported.includes("refresh_token")))return{error:"invalid_request",error_description:"Server does not support refresh_token grant"};if(!((o=this.oidcConfig)!=null&&o.token_endpoint))return{error:"server_error",error_description:"Cannot get token endpoint"};const r=this.oidcConfig.token_endpoint;let n;n=f(this,b);let i={grant_type:"refresh_token",refresh_token:t,client_id:f(this,_)};n&&(i.client_secret=n);try{return await this.post(r,i,this.authServerHeaders)}catch(h){return c.logger.error(l({err:h})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async startDeviceCodeFlow(t,r){var i;if(c.logger.debug(l({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:f(this,_),client_secret:f(this,b)};r&&(n.scope=r);try{return await this.post(t,n,this.authServerHeaders)}catch(s){return c.logger.error(l({err:s})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async pollDeviceCodeFlow(t){var n,i,s;if(c.logger.debug(l({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:f(this,_),client_secret:f(this,b),device_code:t};try{const o=await this.post((s=this.oidcConfig)==null?void 0:s.token_endpoint,r,this.authServerHeaders);return o.error,o}catch(o){return c.logger.error(l({err:o})),{error:"server_error",error_description:"Error connecting to authorization server"}}}async post(t,r,n={}){c.logger.debug(l({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(l({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(l({err:r}));return}}getTokenPayload(t){return He(t)}}_=new WeakMap,b=new WeakMap,U=new WeakMap,I=new WeakMap,R=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 Ie(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 Te(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(l({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(l({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,s]of Object.entries(n))this.oidcConfig[i]=s}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(l({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 s="_default";"kid"in n.keys[i]&&typeof n.keys[i]=="string"&&(s=String(n.keys[i]));const o=await de(n.keys[i]);this.keys[s]=o}catch(s){throw c.logger.error(l({err:s})),new w(m.Connection,"Couldn't load keys")}}catch(n){throw c.logger.error(l({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(l({msg:r+" expected but got "+n.type})),n.iss!=this.authServerBaseUrl){c.logger.error(l({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(l({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(l({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(l({msg:"No matching keys found for access token"}));return}try{const{payload:i}=await De(t,n),s=JSON.parse(new TextDecoder().decode(i));if(s.exp*1e3<Date.now()+this.clockTolerance){c.logger.warn(l({msg:"Access token has expired"}));return}return s}catch{c.logger.warn(l({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=p,u.httpStatus=fe,u.j=l,Object.defineProperty(u,Symbol.toStringTag,{value:"Module"}),u}({});
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}({});

@@ -62,4 +62,3 @@ /**

*
* This is extendible with additional fields - provide them to the
* {@link @crossauth/backend!UserStorage} class as `extraFields`.
* This is extendible with additional fields.
*

@@ -93,5 +92,3 @@ * You may want to do this if you want to pass additional user data back to the

/**
* This is included as any other fields in your user table will
* automatically be added to the user object if they are included in
* `extraFields` in {@link @crossauth/backend!UserStorage}.
* This allows you to add your own fields
*/

@@ -164,3 +161,3 @@ [key: string]: any;

*
* See {@link @crossauth/common!OAuthFlows}.
* See {@link OAuthFlows}.
*/

@@ -167,0 +164,0 @@ valid_flow: string[];

@@ -33,3 +33,3 @@ /**

* - `err` : an error object. If a subclass of Error, it wil contain at least `message` and
* a stack trace in `stack`. If the error is of type{@link @crossauth/common!CrossauthError}
* a stack trace in `stack`. If the error is of type{@link CrossauthError}
* it also will also contain `code` and `httpStatus`.

@@ -36,0 +36,0 @@ * - `hashedSessionCookie` : for security reasons, session cookies are not included in logs.

@@ -119,3 +119,3 @@ import { OpenIdConfiguration, OAuthTokenConsumerBase, GrantType } from '..';

* in derived Node-only and Browser-only classes.
* See {@link @crossauth/backend!OAuthClientBackend}.
* See `@crossauth/backend/OAuthClientBackend`.
*

@@ -202,3 +202,3 @@ * Flows supported are Authorization Code Flow with and without PKCE,

* `authServerBaseUrl`.
* @throws {@link @crossauth/common!CrossauthError} with the following {@link @crossauth/common!ErrorCode}s
* @throws {@link CrossauthError} with the following {@link ErrorCode}s
* - `Connection` if data from the URL could not be fetched or parsed.

@@ -477,2 +477,7 @@ */

}
export interface MfaAuthenticatorsResponse {
authenticators?: MfaAuthenticatorResponse[];
error?: string;
error_description?: string;
}
//# sourceMappingURL=client.d.ts.map

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

* the authorization server
* @throws a {@link @crossauth/common!CrossauthError} object with {@link @crossauth/common!ErrorCode} of
* @throws a {@link CrossauthError} object with {@link ErrorCode} of
* - `Connection` if the fetch to the authorization server failed.

@@ -92,3 +92,3 @@ */

* the authorization server.
* @throws a {@link @crossauth/common!CrossauthError} object with {@link @crossauth/common!ErrorCode} of
* @throws a {@link CrossauthError} object with {@link ErrorCode} of
* - `Connection` if the fetch to the authorization server failed,

@@ -95,0 +95,0 @@ * the OIDC configuration wasn't set or the keys could not be parsed.

@@ -56,5 +56,5 @@ import { JsonWebKey } from 'crypto';

* This is the detault configuration for
* {@link @crossauth/backend!OAuthAuthorizationServer}.wellknown
* `@crossauth/backend/OAuthAuthorizationServer.wellknown`
*/
export declare const DEFAULT_OIDCCONFIG: OpenIdConfiguration;
//# sourceMappingURL=wellknown.d.ts.map
{
"name": "@crossauth/common",
"private": false,
"version": "0.0.14",
"version": "0.0.15",
"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 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

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