@crossauth/common 1.0.0 → 1.1.0

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