@authrim/core 0.1.2 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3440 -370
- package/dist/index.d.ts +3440 -370
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/package.json +59 -59
package/dist/index.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
'use strict';function U(s){return {...s,scopes:s.scopes??["openid","profile"],flowEngine:s.flowEngine??false,discoveryCacheTtlMs:s.discoveryCacheTtlMs??3600*1e3,refreshSkewSeconds:s.refreshSkewSeconds??30,stateTtlSeconds:s.stateTtlSeconds??600,hashOptions:{hashLength:s.hashOptions?.hashLength??16}}}var a=class s extends Error{constructor(e,t,n){super(t),this.name="AuthrimError",this.code=e,this.details=n?.details,this.errorUri=n?.errorUri,this.cause=n?.cause;}static fromOAuthError(e){let n=["invalid_request","unauthorized_client","access_denied","unsupported_response_type","invalid_scope","server_error","temporarily_unavailable","invalid_grant","invalid_token"].includes(e.error)?e.error:"invalid_request";return new s(n,e.error_description??e.error,{errorUri:e.error_uri,details:{originalError:e.error}})}isRetryable(){return this.code==="network_error"||this.code==="timeout_error"}get meta(){return j(this.code)}},F={invalid_request:{transient:false,retryable:false,userAction:"contact_support",severity:"error"},unauthorized_client:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},access_denied:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},unsupported_response_type:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},invalid_scope:{transient:false,retryable:false,userAction:"contact_support",severity:"error"},server_error:{transient:true,retryable:true,retryAfterMs:5e3,maxRetries:3,userAction:"retry",severity:"error"},temporarily_unavailable:{transient:true,retryable:true,retryAfterMs:1e4,maxRetries:3,userAction:"retry",severity:"warning"},invalid_grant:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},invalid_token:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},invalid_state:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},expired_state:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},invalid_nonce:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},nonce_mismatch:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},session_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},session_check_failed:{transient:true,retryable:true,retryAfterMs:3e3,maxRetries:2,userAction:"retry",severity:"warning"},network_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:3,userAction:"check_network",severity:"error"},timeout_error:{transient:true,retryable:true,retryAfterMs:3e3,maxRetries:3,userAction:"retry",severity:"warning"},discovery_error:{transient:true,retryable:true,retryAfterMs:5e3,maxRetries:2,userAction:"retry",severity:"error"},discovery_mismatch:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},configuration_error:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},storage_error:{transient:true,retryable:true,retryAfterMs:1e3,maxRetries:2,userAction:"retry",severity:"error"},flow_engine_error:{transient:false,retryable:false,userAction:"contact_support",severity:"error"},no_tokens:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},token_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},token_error:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},refresh_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:2,userAction:"retry",severity:"error"},token_exchange_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:2,userAction:"retry",severity:"error"},oauth_error:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},missing_code:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},missing_state:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},not_initialized:{transient:false,retryable:false,userAction:"none",severity:"fatal"},no_discovery:{transient:true,retryable:true,retryAfterMs:3e3,maxRetries:2,userAction:"retry",severity:"error"},no_userinfo_endpoint:{transient:false,retryable:false,userAction:"none",severity:"warning"},userinfo_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:2,userAction:"retry",severity:"error"},introspection_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:2,userAction:"retry",severity:"error"},revocation_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:2,userAction:"retry",severity:"error"},no_introspection_endpoint:{transient:false,retryable:false,userAction:"none",severity:"warning"},no_revocation_endpoint:{transient:false,retryable:false,userAction:"none",severity:"warning"},login_required:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},interaction_required:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},consent_required:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},account_selection_required:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},dom_not_ready:{transient:true,retryable:true,retryAfterMs:100,maxRetries:3,userAction:"retry",severity:"error"},state_mismatch:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},popup_blocked:{transient:false,retryable:false,userAction:"none",severity:"warning"},popup_closed:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},invalid_response:{transient:false,retryable:false,userAction:"contact_support",severity:"error"}};function j(s){return F[s]}function g(s){return s.replace(/\/+$/,"")}var b=class b{constructor(e){this.cache=new Map;this.http=e.http,this.cacheTtlMs=e.cacheTtlMs??b.DEFAULT_CACHE_TTL_MS;}async discover(e){let t=g(e),n=this.cache.get(t);if(n&&!this.isExpired(n))return n.doc;let r=`${t}/.well-known/openid-configuration`,i;try{let c=await this.http.fetch(r);if(!c.ok)throw new a("discovery_error",`Discovery request failed: ${c.status}`,{details:{status:c.status,statusText:c.statusText}});i=c.data;}catch(c){throw c instanceof a?c:new a("discovery_error","Failed to fetch discovery document",{cause:c instanceof Error?c:void 0,details:{url:r}})}let o=g(i.issuer);if(o!==t)throw new a("discovery_mismatch",`Issuer mismatch in discovery document: expected "${t}", got "${o}"`,{details:{expected:t,actual:o}});return this.cache.set(t,{doc:i,fetchedAt:Date.now()}),i}isExpired(e){return Date.now()-e.fetchedAt>this.cacheTtlMs}clearCache(){this.cache.clear();}clearIssuer(e){this.cache.delete(g(e));}};b.DEFAULT_CACHE_TTL_MS=3600*1e3;var v=b;var _=class{constructor(){this.listeners=new Map;}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{this.off(e,t);}}once(e,t){let n=(r=>{this.off(e,n),t(r);});return this.on(e,n)}off(e,t){let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&this.listeners.delete(e));}emit(e,t){let n=this.listeners.get(e);if(n)for(let r of n)try{r(t);}catch(i){console.error(`Error in event handler for '${e}':`,i);}}removeAllListeners(e){e?this.listeners.delete(e):this.listeners.clear();}listenerCount(e){return this.listeners.get(e)?.size??0}};var T=class{constructor(e){this.crypto=e;}async generatePKCE(){let e=await this.crypto.generateCodeVerifier(),t=await this.crypto.generateCodeChallenge(e);return {codeVerifier:e,codeChallenge:t,codeChallengeMethod:"S256"}}async generateCodeVerifier(){return this.crypto.generateCodeVerifier()}async generateCodeChallenge(e){return this.crypto.generateCodeChallenge(e)}};function y(s){let e="",t=s.length;for(let n=0;n<t;n+=3){let r=s[n],i=n+1<t?s[n+1]:0,o=n+2<t?s[n+2]:0,c=r<<16|i<<8|o;e+=k[c>>18&63],e+=k[c>>12&63],e+=n+1<t?k[c>>6&63]:"",e+=n+2<t?k[c&63]:"";}return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function N(s){let e=s.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";let t=e.length,n=e.endsWith("==")?2:e.endsWith("=")?1:0,r=t*3/4-n,i=new Uint8Array(r),o=0;for(let c=0;c<t;c+=4){let h=A[e.charCodeAt(c)],d=A[e.charCodeAt(c+1)],p=A[e.charCodeAt(c+2)],u=A[e.charCodeAt(c+3)],l=h<<18|d<<12|p<<6|u;o<r&&(i[o++]=l>>16&255),o<r&&(i[o++]=l>>8&255),o<r&&(i[o++]=l&255);}return i}function J(s){let e=new TextEncoder;return y(e.encode(s))}function O(s){return new TextDecoder().decode(N(s))}var k="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",A=new Uint8Array(256);for(let s=0;s<k.length;s++)A[k.charCodeAt(s)]=s;var f={authState:(s,e,t)=>`authrim:${s}:${e}:auth:${t}`,tokens:(s,e)=>`authrim:${s}:${e}:tokens`,idToken:(s,e)=>`authrim:${s}:${e}:id_token`,authStatePrefix:(s,e)=>`authrim:${s}:${e}:auth:`},D=class D{constructor(e,t,n,r){this.crypto=e;this.storage=t;this.issuerHash=n;this.clientIdHash=r;}async generateAuthState(e){let t=e.ttlSeconds??D.DEFAULT_TTL_SECONDS,n=await this.crypto.randomBytes(32),r=await this.crypto.randomBytes(32),i=y(n),o=y(r),c=Date.now(),h={state:i,nonce:o,codeVerifier:e.codeVerifier,redirectUri:e.redirectUri,createdAt:c,expiresAt:c+t*1e3},d=f.authState(this.issuerHash,this.clientIdHash,i);return await this.storage.set(d,JSON.stringify(h)),h}async validateAndConsumeState(e){let t=f.authState(this.issuerHash,this.clientIdHash,e);try{let n=await this.storage.get(t);if(!n)throw new a("invalid_state","State not found or already used");let r;try{r=JSON.parse(n);}catch{throw new a("invalid_state","Malformed state data")}if(Date.now()>r.expiresAt)throw new a("expired_state","State has expired");return r}finally{await this.storage.remove(t);}}async cleanupExpiredStates(){if(!this.storage.getAll)return;let e=f.authStatePrefix(this.issuerHash,this.clientIdHash),t=await this.storage.getAll(),n=Date.now();for(let[r,i]of Object.entries(t))if(r.startsWith(e))try{let o=JSON.parse(i);n>o.expiresAt&&await this.storage.remove(r);}catch{await this.storage.remove(r);}}};D.DEFAULT_TTL_SECONDS=600;var w=D;function q(s){let e=s.split(".");if(e.length!==3)throw new Error("Invalid JWT format: expected 3 parts");let[t,n,r]=e;try{let i=JSON.parse(O(t)),o=JSON.parse(O(n));return {header:i,payload:o,signature:r}}catch{throw new Error("Invalid JWT format: failed to decode")}}function K(s){return q(s).payload}function V(s,e=0){if(s.exp===void 0)return false;let t=Math.floor(Date.now()/1e3);return s.exp+e<t}function M(s){try{return K(s).nonce}catch{return}}var E=class{constructor(e,t){this.http=e;this.clientId=t;}buildAuthorizationUrl(e,t,n,r){let i=e.authorization_endpoint,o=new URLSearchParams;o.set("client_id",this.clientId),o.set("response_type","code"),o.set("redirect_uri",r.redirectUri),o.set("state",t.state),o.set("nonce",t.nonce),o.set("code_challenge",n.codeChallenge),o.set("code_challenge_method",n.codeChallengeMethod);let c=r.scope??"openid profile";if(o.set("scope",c),r.prompt&&o.set("prompt",r.prompt),r.loginHint&&o.set("login_hint",r.loginHint),r.acrValues&&o.set("acr_values",r.acrValues),r.extraParams){let p=new Set(["client_id","response_type","redirect_uri","state","nonce","code_challenge","code_challenge_method","scope"]);for(let[u,l]of Object.entries(r.extraParams))p.has(u.toLowerCase())||o.set(u,l);}let d={url:`${i}?${o.toString()}`};return r.exposeState&&(d.state=t.state,d.nonce=t.nonce),d}parseCallback(e){let t;e.includes("?")?t=(e.startsWith("http")?new URL(e):new URL(e,"https://dummy.local")).searchParams:t=new URLSearchParams(e);let n=t.get("error");if(n){let o=t.get("error_description")??"Authorization failed";throw new a("oauth_error",o,{details:{error:n,error_description:o,error_uri:t.get("error_uri")}})}let r=t.get("code"),i=t.get("state");if(!r)throw new a("missing_code","Authorization code not found in callback");if(!i)throw new a("missing_state","State parameter not found in callback");return {code:r,state:i}}async exchangeCode(e,t){let n=e.token_endpoint,r=new URLSearchParams({grant_type:"authorization_code",client_id:this.clientId,code:t.code,redirect_uri:t.redirectUri,code_verifier:t.codeVerifier}),i;try{i=await this.http.fetch(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()});}catch(p){throw new a("network_error","Token request failed",{cause:p instanceof Error?p:void 0})}if(!i.ok){let p=i.data;throw new a("token_error","Token exchange failed",{details:{status:i.status,error:p?.error,error_description:p?.error_description}})}let o=i.data;if(o.id_token&&M(o.id_token)!==t.nonce)throw new a("nonce_mismatch","ID token nonce does not match expected value");let c=Math.floor(Date.now()/1e3),h=o.expires_in?c+o.expires_in:c+3600;return {accessToken:o.access_token,tokenType:o.token_type??"Bearer",expiresAt:h,refreshToken:o.refresh_token,idToken:o.id_token,scope:o.scope}}};var L={access_token:"urn:ietf:params:oauth:token-type:access_token",refresh_token:"urn:ietf:params:oauth:token-type:refresh_token",id_token:"urn:ietf:params:oauth:token-type:id_token"};var H=class H{constructor(e){this.refreshPromise=null;this.discovery=null;this.http=e.http,this.storage=e.storage,this.clientId=e.clientId,this.issuerHash=e.issuerHash,this.clientIdHash=e.clientIdHash,this.refreshSkewSeconds=e.refreshSkewSeconds??H.DEFAULT_REFRESH_SKEW_SECONDS,this.eventEmitter=e.eventEmitter;}setDiscovery(e){this.discovery=e;}get tokenKey(){return f.tokens(this.issuerHash,this.clientIdHash)}get idTokenKey(){return f.idToken(this.issuerHash,this.clientIdHash)}async getTokens(){let e=await this.storage.get(this.tokenKey);if(!e)return null;try{return JSON.parse(e)}catch{return await this.clearTokens(),null}}async saveTokens(e){await this.storage.set(this.tokenKey,JSON.stringify(e)),e.idToken&&await this.storage.set(this.idTokenKey,e.idToken);}async clearTokens(){await this.storage.remove(this.tokenKey),await this.storage.remove(this.idTokenKey);}async getAccessToken(){let e=await this.getTokens();if(!e)throw new a("no_tokens","No tokens available. Please authenticate first.");if(this.shouldRefresh(e)){if(!e.refreshToken)throw new a("token_expired","Access token expired and no refresh token available");return this.refreshWithLock(e.refreshToken)}return e.accessToken}async getIdToken(){return (await this.getTokens())?.idToken??null}shouldRefresh(e){let t=Math.floor(Date.now()/1e3);return e.expiresAt-this.refreshSkewSeconds<=t}async refreshWithLock(e){if(this.refreshPromise)return (await this.refreshPromise).accessToken;this.refreshPromise=this.doRefreshWithRetry(e);try{return (await this.refreshPromise).accessToken}finally{this.refreshPromise=null;}}async doRefreshWithRetry(e,t=false){try{return await this.doRefresh(e)}catch(n){if(this.isRetryableError(n)&&!t)return this.doRefreshWithRetry(e,true);throw n}}async doRefresh(e){if(!this.discovery)throw new a("no_discovery","Discovery document not set");let t=this.discovery.token_endpoint,n=new URLSearchParams({grant_type:"refresh_token",client_id:this.clientId,refresh_token:e}),r;try{r=await this.http.fetch(t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()});}catch(d){let p=new a("network_error","Token refresh request failed",{cause:d instanceof Error?d:void 0});throw this.eventEmitter?.emit("token:error",{error:p}),p}if(!r.ok){let d=r.data,p=new a("refresh_error","Token refresh failed",{details:{status:r.status,error:d?.error,error_description:d?.error_description}});throw this.eventEmitter?.emit("token:error",{error:p}),p}let i=r.data,o=Math.floor(Date.now()/1e3),c=i.expires_in?o+i.expires_in:o+3600,h={accessToken:i.access_token,tokenType:i.token_type??"Bearer",expiresAt:c,refreshToken:i.refresh_token??e,idToken:i.id_token,scope:i.scope};return await this.saveTokens(h),this.eventEmitter?.emit("token:refreshed",{tokens:h}),h}isRetryableError(e){return e instanceof a?e.code==="network_error":false}async isAuthenticated(){let e=await this.getTokens();if(!e)return false;let t=Math.floor(Date.now()/1e3);return e.expiresAt<=t?!!e.refreshToken:true}async exchangeToken(e){if(!this.discovery)throw new a("no_discovery","Discovery document not set");let t=this.discovery.token_endpoint,n=this.mapTokenTypeToUri(e.subjectTokenType??"access_token"),r=new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",client_id:this.clientId,subject_token:e.subjectToken,subject_token_type:n});e.audience&&r.set("audience",e.audience),e.scope&&r.set("scope",e.scope),e.requestedTokenType&&r.set("requested_token_type",this.mapTokenTypeToUri(e.requestedTokenType)),e.actorToken&&(r.set("actor_token",e.actorToken),e.actorTokenType&&r.set("actor_token_type",this.mapTokenTypeToUri(e.actorTokenType)));let i;try{i=await this.http.fetch(t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()});}catch(u){let l=new a("network_error","Token exchange request failed",{cause:u instanceof Error?u:void 0});throw this.eventEmitter?.emit("token:error",{error:l}),l}if(!i.ok){let u=i.data,l=new a("token_exchange_error","Token exchange failed",{details:{status:i.status,error:u?.error,error_description:u?.error_description}});throw this.eventEmitter?.emit("token:error",{error:l}),l}let o=i.data,c=Math.floor(Date.now()/1e3),h=o.expires_in?c+o.expires_in:c+3600,d={accessToken:o.access_token,tokenType:o.token_type??"Bearer",expiresAt:h,refreshToken:o.refresh_token,idToken:o.id_token,scope:o.scope},p={tokens:d,issuedTokenType:o.issued_token_type};return this.eventEmitter?.emit("token:exchanged",{tokens:d,issuedTokenType:o.issued_token_type}),p}mapTokenTypeToUri(e){return L[e]}};H.DEFAULT_REFRESH_SKEW_SECONDS=30;var x=H;var S=class{constructor(e){this.http=e.http,this.clientId=e.clientId;}async introspect(e,t){let n=e.introspection_endpoint;if(!n)throw new a("no_introspection_endpoint","Authorization server does not support token introspection");return this.introspectWithEndpoint(n,t)}async introspectWithEndpoint(e,t){let n=new URLSearchParams({client_id:this.clientId,token:t.token});t.tokenTypeHint&&n.set("token_type_hint",t.tokenTypeHint);let r;try{r=await this.http.fetch(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()});}catch(i){throw new a("network_error","Token introspection request failed",{cause:i instanceof Error?i:void 0})}if(!r.ok){let i=r.data;throw new a("introspection_error","Token introspection failed",{details:{status:r.status,error:i?.error,error_description:i?.error_description}})}return r.data}async isActive(e,t){return (await this.introspect(e,{token:t})).active}};var m=class{constructor(e){this.http=e.http,this.clientId=e.clientId;}async revoke(e,t){let n=e.revocation_endpoint;if(!n)throw new a("no_revocation_endpoint","Authorization server does not support token revocation");let r=new URLSearchParams({client_id:this.clientId,token:t.token});t.tokenTypeHint&&r.set("token_type_hint",t.tokenTypeHint);let i;try{i=await this.http.fetch(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()});}catch(c){throw new a("network_error","Token revocation request failed",{cause:c instanceof Error?c:void 0})}if(i.ok)return;let o=i.data;throw new a("revocation_error","Token revocation failed",{details:{status:i.status,error:o?.error,error_description:o?.error_description}})}async revokeWithEndpoint(e,t){let n=new URLSearchParams({client_id:this.clientId,token:t.token});t.tokenTypeHint&&n.set("token_type_hint",t.tokenTypeHint);let r;try{r=await this.http.fetch(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()});}catch(o){throw new a("network_error","Token revocation request failed",{cause:o instanceof Error?o:void 0})}if(r.ok)return;let i=r.data;throw new a("revocation_error","Token revocation failed",{details:{status:r.status,error:i?.error,error_description:i?.error_description}})}};var C=class{constructor(e){this.storage=e.storage,this.clientId=e.clientId,this.issuerHash=e.issuerHash,this.clientIdHash=e.clientIdHash,this.eventEmitter=e.eventEmitter,this.endpoints=e.endpoints,this.tokenRevoker=new m({http:e.http,clientId:e.clientId});}async logout(e,t){let n=await this.getStoredIdToken(),r=await this.getStoredTokens(),i;t?.revokeTokens&&e?.revocation_endpoint&&r&&(i=await this.revokeTokens(e,r)),await this.clearTokens(),this.eventEmitter?.emit("session:ended",{reason:"logout"});let o;if(this.endpoints?.endSession!==void 0?o=this.endpoints.endSession:e&&(o=e.end_session_endpoint),!o)return {localOnly:true,revocation:i};let c=t?.idTokenHint??n,h=new URLSearchParams({client_id:this.clientId});return c&&h.set("id_token_hint",c),t?.postLogoutRedirectUri&&h.set("post_logout_redirect_uri",t.postLogoutRedirectUri),t?.state&&h.set("state",t.state),{logoutUrl:`${o}?${h.toString()}`,localOnly:false,revocation:i}}async revokeTokens(e,t){let n={attempted:true};try{t.refreshToken&&(await this.tokenRevoker.revoke(e,{token:t.refreshToken,tokenTypeHint:"refresh_token"}),n.refreshTokenRevoked=!0),await this.tokenRevoker.revoke(e,{token:t.accessToken,tokenTypeHint:"access_token"}),n.accessTokenRevoked=!0;}catch(r){n.error=r instanceof Error?r:new Error(String(r));}return n}async clearTokens(){let e=f.tokens(this.issuerHash,this.clientIdHash),t=f.idToken(this.issuerHash,this.clientIdHash);await this.storage.remove(e),await this.storage.remove(t);}async getStoredIdToken(){let e=f.idToken(this.issuerHash,this.clientIdHash);return this.storage.get(e)}async getStoredTokens(){let e=f.tokens(this.issuerHash,this.clientIdHash),t=await this.storage.get(e);if(!t)return null;try{return JSON.parse(t)}catch{return null}}};var R=class{constructor(e){this.http=e.http;}async checkSession(e,t){let n=e.userinfo_endpoint;if(!n)return {valid:false,error:new a("no_userinfo_endpoint","UserInfo endpoint not available")};try{let r=await this.http.fetch(n,{method:"GET",headers:{Authorization:`Bearer ${t}`}});return r.ok?{valid:!0,user:r.data}:r.status===401?{valid:!1,error:new a("session_expired","Session has expired")}:{valid:!1,error:new a("session_check_failed","Session check failed",{details:{status:r.status}})}}catch(r){return {valid:false,error:new a("network_error","Failed to check session",{cause:r instanceof Error?r:void 0})}}}async getUserInfo(e,t){let n=e.userinfo_endpoint;if(!n)throw new a("no_userinfo_endpoint","UserInfo endpoint not available");let r;try{r=await this.http.fetch(n,{method:"GET",headers:{Authorization:`Bearer ${t}`}});}catch(i){throw new a("network_error","Failed to fetch user info",{cause:i instanceof Error?i:void 0})}if(!r.ok)throw new a("userinfo_error","Failed to get user info",{details:{status:r.status}});return r.data}};var I=class{constructor(e){this.discovery=null;this.tokenManager=e.tokenManager,this.tokenApiClient=e.tokenApiClient;}setDiscovery(e){this.discovery=e;}async isAuthenticated(){return this.tokenManager.isAuthenticated()}async checkSession(){if(!this.discovery)return {valid:false,error:new a("no_discovery","Discovery document not available")};try{let e=await this.tokenManager.getAccessToken();return this.tokenApiClient.checkSession(this.discovery,e)}catch(e){return e instanceof a?{valid:false,error:e}:{valid:false,error:new a("session_check_failed","Failed to check session",{cause:e instanceof Error?e:void 0})}}}async getUser(){if(!this.discovery)throw new a("no_discovery","Discovery document not available");let e=await this.tokenManager.getAccessToken();return this.tokenApiClient.getUserInfo(this.discovery,e)}};async function B(s,e,t=16){let n=await s.sha256(e);return y(n).slice(0,t)}var P=class{constructor(e){this.initialized=false;this.config=U(e),this.normalizedIssuer=g(e.issuer),this.events=new _,this.discoveryClient=new v({http:this.config.http,cacheTtlMs:this.config.discoveryCacheTtlMs}),this.pkce=new T(this.config.crypto),this.authCodeFlow=new E(this.config.http,this.config.clientId);}async initialize(){if(this.initialized)return;let e=this.config.hashOptions.hashLength;this.issuerHash=await B(this.config.crypto,this.normalizedIssuer,e),this.clientIdHash=await B(this.config.crypto,this.config.clientId,e),this.stateManager=new w(this.config.crypto,this.config.storage,this.issuerHash,this.clientIdHash),this.tokenManager=new x({http:this.config.http,storage:this.config.storage,clientId:this.config.clientId,issuerHash:this.issuerHash,clientIdHash:this.clientIdHash,refreshSkewSeconds:this.config.refreshSkewSeconds,eventEmitter:this.events}),this.logoutHandler=new C({storage:this.config.storage,http:this.config.http,clientId:this.config.clientId,issuerHash:this.issuerHash,clientIdHash:this.clientIdHash,eventEmitter:this.events,endpoints:this.config.endpoints}),this.tokenIntrospector=new S({http:this.config.http,clientId:this.config.clientId}),this.tokenRevoker=new m({http:this.config.http,clientId:this.config.clientId});let t=new R({http:this.config.http});this.sessionManager=new I({tokenManager:this.tokenManager,tokenApiClient:t}),await this.stateManager.cleanupExpiredStates(),this.initialized=true;}ensureInitialized(){if(!this.initialized)throw new a("not_initialized","Client not initialized. Use createAuthrimClient().")}async discover(){let e=await this.discoveryClient.discover(this.normalizedIssuer);return this.tokenManager.setDiscovery(e),this.sessionManager.setDiscovery(e),e}async buildAuthorizationUrl(e){this.ensureInitialized();let t=await this.discover(),n=await this.pkce.generatePKCE(),r=await this.stateManager.generateAuthState({redirectUri:e.redirectUri,codeVerifier:n.codeVerifier,ttlSeconds:this.config.stateTtlSeconds}),i=this.authCodeFlow.buildAuthorizationUrl(t,r,n,e);return this.events.emit("auth:redirecting",{url:i.url}),i}async handleCallback(e){this.ensureInitialized();let{code:t,state:n}=this.authCodeFlow.parseCallback(e);this.events.emit("auth:callback",{code:t,state:n});let r=await this.stateManager.validateAndConsumeState(n),i=await this.discover(),o=await this.authCodeFlow.exchangeCode(i,{code:t,state:n,redirectUri:r.redirectUri,codeVerifier:r.codeVerifier,nonce:r.nonce});return await this.tokenManager.saveTokens(o),o}get token(){return this.ensureInitialized(),{getAccessToken:()=>this.tokenManager.getAccessToken(),getTokens:()=>this.tokenManager.getTokens(),getIdToken:()=>this.tokenManager.getIdToken(),isAuthenticated:()=>this.tokenManager.isAuthenticated(),exchange:async e=>(await this.discover(),this.tokenManager.exchangeToken(e)),introspect:async e=>{let t=await this.discover();return this.tokenIntrospector.introspect(t,e)},revoke:async e=>{let t=await this.discover();return this.tokenRevoker.revoke(t,e)}}}get session(){return this.ensureInitialized(),{isAuthenticated:()=>this.sessionManager.isAuthenticated(),check:()=>this.sessionManager.checkSession()}}async isAuthenticated(){return this.ensureInitialized(),this.tokenManager.isAuthenticated()}async getUser(){return this.ensureInitialized(),this.sessionManager.getUser()}async logout(e){this.ensureInitialized();let t=null;try{t=await this.discover();}catch{}return this.logoutHandler.logout(t,e)}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}off(e,t){this.events.off(e,t);}};async function W(s){let e=new P(s);return await e.initialize(),e}var $=new Set(["login_required","interaction_required","consent_required","account_selection_required"]),z=class{constructor(e){this.clientId=e;}buildSilentAuthUrl(e,t,n,r){let i=e.authorization_endpoint,o=new URLSearchParams;o.set("client_id",this.clientId),o.set("response_type","code"),o.set("redirect_uri",r.redirectUri),o.set("state",t.state),o.set("nonce",t.nonce),o.set("prompt","none"),o.set("code_challenge",n.codeChallenge),o.set("code_challenge_method",n.codeChallengeMethod);let c=r.scope??"openid";if(o.set("scope",c),r.loginHint&&o.set("login_hint",r.loginHint),r.idTokenHint&&o.set("id_token_hint",r.idTokenHint),r.extraParams){let p=new Set(["client_id","response_type","redirect_uri","state","nonce","code_challenge","code_challenge_method","scope","prompt"]);for(let[u,l]of Object.entries(r.extraParams))p.has(u.toLowerCase())||o.set(u,l);}let d={url:`${i}?${o.toString()}`};return r.exposeState&&(d.state=t.state,d.nonce=t.nonce),d}parseSilentAuthResponse(e){let t;e.includes("?")?t=(e.startsWith("http")?new URL(e):new URL(e,"https://dummy.local")).searchParams:t=new URLSearchParams(e);let n=t.get("error");if(n){let o=t.get("error_description"),c=this.mapSilentAuthError(n);return {success:false,error:new a(c,o??this.getDefaultErrorMessage(n),{details:{error:n,error_description:o,error_uri:t.get("error_uri")}})}}let r=t.get("code"),i=t.get("state");return r?i?{success:true,code:r,state:i}:{success:false,error:new a("missing_state","State parameter not found in silent auth response")}:{success:false,error:new a("missing_code","Authorization code not found in silent auth response")}}isInteractiveLoginRequired(e){return $.has(e.code)}mapSilentAuthError(e){return $.has(e)?e:"oauth_error"}getDefaultErrorMessage(e){switch(e){case "login_required":return "User must log in - no active session found";case "interaction_required":return "User interaction required";case "consent_required":return "User consent required";case "account_selection_required":return "User must select an account";default:return "Silent authentication failed"}}};async function G(s,e){let t=await e.sha256(s),n=t.slice(0,t.length/2);return y(n)}
|
|
2
|
-
exports.AuthorizationCodeFlow=
|
|
1
|
+
'use strict';function W(s){return {...s,scopes:s.scopes??["openid","profile"],flowEngine:s.flowEngine??false,discoveryCacheTtlMs:s.discoveryCacheTtlMs??3600*1e3,refreshSkewSeconds:s.refreshSkewSeconds??30,stateTtlSeconds:s.stateTtlSeconds??600,hashOptions:{hashLength:s.hashOptions?.hashLength??16}}}var a=class s extends Error{constructor(e,t,n){super(t),this.name="AuthrimError",this.code=e,this.details=n?.details,this.errorUri=n?.errorUri,this.cause=n?.cause;}static fromOAuthError(e){let n=["invalid_request","unauthorized_client","access_denied","unsupported_response_type","invalid_scope","server_error","temporarily_unavailable","invalid_grant","invalid_token"].includes(e.error)?e.error:"invalid_request";return new s(n,e.error_description??e.error,{errorUri:e.error_uri,details:{originalError:e.error}})}isRetryable(){return this.code==="network_error"||this.code==="timeout_error"}get meta(){return ue(this.code)}},Ae={invalid_request:{transient:false,retryable:false,userAction:"contact_support",severity:"error"},unauthorized_client:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},access_denied:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},unsupported_response_type:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},invalid_scope:{transient:false,retryable:false,userAction:"contact_support",severity:"error"},server_error:{transient:true,retryable:true,retryAfterMs:5e3,maxRetries:3,userAction:"retry",severity:"error"},temporarily_unavailable:{transient:true,retryable:true,retryAfterMs:1e4,maxRetries:3,userAction:"retry",severity:"warning"},invalid_grant:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},invalid_token:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},invalid_state:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},expired_state:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},invalid_nonce:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},nonce_mismatch:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},missing_nonce:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},missing_id_token:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},session_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},session_check_failed:{transient:true,retryable:true,retryAfterMs:3e3,maxRetries:2,userAction:"retry",severity:"warning"},network_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:3,userAction:"check_network",severity:"error"},timeout_error:{transient:true,retryable:true,retryAfterMs:3e3,maxRetries:3,userAction:"retry",severity:"warning"},discovery_error:{transient:true,retryable:true,retryAfterMs:5e3,maxRetries:2,userAction:"retry",severity:"error"},discovery_mismatch:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},configuration_error:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},storage_error:{transient:true,retryable:true,retryAfterMs:1e3,maxRetries:2,userAction:"retry",severity:"error"},flow_engine_error:{transient:false,retryable:false,userAction:"contact_support",severity:"error"},no_tokens:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},token_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},token_error:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},refresh_error:{transient:false,retryable:false,retryAfterMs:0,maxRetries:0,userAction:"reauthenticate",severity:"error"},token_exchange_error:{transient:false,retryable:false,retryAfterMs:0,maxRetries:0,userAction:"reauthenticate",severity:"error"},oauth_error:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},missing_code:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},missing_state:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},not_initialized:{transient:false,retryable:false,userAction:"none",severity:"fatal"},no_discovery:{transient:true,retryable:true,retryAfterMs:3e3,maxRetries:2,userAction:"retry",severity:"error"},no_userinfo_endpoint:{transient:false,retryable:false,userAction:"none",severity:"warning"},userinfo_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:2,userAction:"retry",severity:"error"},introspection_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:2,userAction:"retry",severity:"error"},revocation_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:2,userAction:"retry",severity:"error"},no_introspection_endpoint:{transient:false,retryable:false,userAction:"none",severity:"warning"},no_revocation_endpoint:{transient:false,retryable:false,userAction:"none",severity:"warning"},login_required:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},interaction_required:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},consent_required:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},account_selection_required:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},dom_not_ready:{transient:true,retryable:true,retryAfterMs:100,maxRetries:3,userAction:"retry",severity:"error"},state_mismatch:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},popup_blocked:{transient:false,retryable:false,userAction:"none",severity:"warning"},popup_closed:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},invalid_response:{transient:false,retryable:false,userAction:"contact_support",severity:"error"},invalid_callback:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},passkey_not_found:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},passkey_verification_failed:{transient:false,retryable:true,retryAfterMs:1e3,maxRetries:3,userAction:"retry",severity:"error"},passkey_not_supported:{transient:false,retryable:false,userAction:"none",severity:"warning"},passkey_cancelled:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},passkey_invalid_credential:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},email_code_invalid:{transient:false,retryable:true,retryAfterMs:0,maxRetries:5,userAction:"retry",severity:"warning"},email_code_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},email_code_too_many_attempts:{transient:false,retryable:false,retryAfterMs:3e5,userAction:"retry",severity:"error"},challenge_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},challenge_invalid:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},auth_code_invalid:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},auth_code_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},pkce_mismatch:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},origin_not_allowed:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},mfa_required:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},email_verification_required:{transient:false,retryable:false,userAction:"none",severity:"warning"},consent_required_direct:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},rate_limited:{transient:true,retryable:true,retryAfterMs:6e4,maxRetries:3,userAction:"retry",severity:"warning"},event_handler_error:{transient:false,retryable:false,userAction:"none",severity:"warning"},par_required:{transient:false,retryable:false,userAction:"none",severity:"fatal"},no_par_endpoint:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},par_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:2,userAction:"retry",severity:"error"},par_request_uri_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},no_device_authorization_endpoint:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},device_authorization_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:2,userAction:"retry",severity:"error"},device_authorization_pending:{transient:true,retryable:true,retryAfterMs:5e3,maxRetries:60,userAction:"none",severity:"warning"},device_slow_down:{transient:true,retryable:true,retryAfterMs:1e4,maxRetries:60,userAction:"none",severity:"warning"},device_authorization_expired:{transient:false,retryable:false,userAction:"reauthenticate",severity:"warning"},device_access_denied:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},client_credentials_error:{transient:true,retryable:true,retryAfterMs:2e3,maxRetries:2,userAction:"retry",severity:"error"},invalid_client_authentication:{transient:false,retryable:false,userAction:"contact_support",severity:"fatal"},insecure_client_auth:{transient:false,retryable:false,userAction:"none",severity:"fatal"},dpop_key_generation_error:{transient:true,retryable:true,retryAfterMs:1e3,maxRetries:2,userAction:"retry",severity:"error"},dpop_proof_generation_error:{transient:false,retryable:false,userAction:"none",severity:"error"},dpop_nonce_required:{transient:true,retryable:true,retryAfterMs:0,maxRetries:1,userAction:"none",severity:"warning"},jar_signing_error:{transient:false,retryable:false,userAction:"contact_support",severity:"error"},jar_required:{transient:false,retryable:false,userAction:"none",severity:"fatal"},jarm_validation_error:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},jarm_signature_invalid:{transient:false,retryable:false,userAction:"reauthenticate",severity:"error"},operation_cancelled:{transient:false,retryable:true,retryAfterMs:0,maxRetries:1,userAction:"retry",severity:"warning"},invalid_return_to:{transient:false,retryable:false,userAction:"none",severity:"error"}};function ue(s){return Ae[s]}function G(s){let e=s.meta;if(!e.retryable&&e.userAction==="contact_support")return {severity:"fatal",remediation:"contact_support"};if(e.severity==="fatal")return {severity:"fatal",remediation:Te(e.userAction)};let t="none";return e.retryable?t="retry":e.userAction==="reauthenticate"?t="reauthenticate":s.code==="popup_blocked"?t="switch_flow":e.userAction==="contact_support"&&(t="contact_support"),{severity:"recoverable",remediation:t}}function Te(s){switch(s){case "retry":case "check_network":return "retry";case "reauthenticate":return "reauthenticate";case "contact_support":return "contact_support";default:return "none"}}function w(s){let e=G(s);return e.severity==="recoverable"&&e.remediation==="retry"}function A(s,e,t){let{severity:n,remediation:r}=G(e),i=Date.now(),o=t.source??"core",c={error:e,severity:n,remediation:r,context:t.context,timestamp:i,source:o,operationId:t.operationId};s.emit("error",c),n==="recoverable"?s.emit("error:recoverable",{...c,severity:"recoverable"}):s.emit("error:fatal",{...c,severity:"fatal"});}function T(s){return s.replace(/\/+$/,"")}var F=class F{constructor(e){this.cache=new Map;this.http=e.http,this.cacheTtlMs=e.cacheTtlMs??F.DEFAULT_CACHE_TTL_MS;}async discover(e){let t=T(e),n=this.cache.get(t);if(n&&!this.isExpired(n))return n.doc;let r=`${t}/.well-known/openid-configuration`,i;try{let c=await this.http.fetch(r);if(!c.ok)throw new a("discovery_error",`Discovery request failed: ${c.status}`,{details:{status:c.status,statusText:c.statusText}});i=c.data;}catch(c){throw c instanceof a?c:new a("discovery_error","Failed to fetch discovery document",{cause:c instanceof Error?c:void 0,details:{url:r}})}let o=T(i.issuer);if(o!==t)throw new a("discovery_mismatch",`Issuer mismatch in discovery document: expected "${t}", got "${o}"`,{details:{expected:t,actual:o}});return this.cache.set(t,{doc:i,fetchedAt:Date.now()}),i}isExpired(e){return Date.now()-e.fetchedAt>this.cacheTtlMs}clearCache(){this.cache.clear();}clearIssuer(e){this.cache.delete(T(e));}};F.DEFAULT_CACHE_TTL_MS=3600*1e3;var x=F;var S=class{constructor(){this.listeners=new Map;}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{this.off(e,t);}}once(e,t){let n=(r=>{this.off(e,n),t(r);});return this.on(e,n)}off(e,t){let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&this.listeners.delete(e));}emit(e,t){let n=this.listeners.get(e);if(n)for(let r of n)try{r(t);}catch(i){if(e!=="error"){let o=i instanceof a?i:new a("event_handler_error","Event handler threw an error",{cause:i instanceof Error?i:void 0});this.emit("error",{error:o,context:`Error in event handler for '${e}'`});}}}removeAllListeners(e){e?this.listeners.delete(e):this.listeners.clear();}listenerCount(e){return this.listeners.get(e)?.size??0}};var P=class{constructor(e){this.crypto=e;}async generatePKCE(){let e=await this.crypto.generateCodeVerifier(),t=await this.crypto.generateCodeChallenge(e);return {codeVerifier:e,codeChallenge:t,codeChallengeMethod:"S256"}}async generateCodeVerifier(){return this.crypto.generateCodeVerifier()}async generateCodeChallenge(e){return this.crypto.generateCodeChallenge(e)}};function f(s){let e="",t=s.length;for(let n=0;n<t;n+=3){let r=s[n],i=n+1<t?s[n+1]:0,o=n+2<t?s[n+2]:0,c=r<<16|i<<8|o;e+=E[c>>18&63],e+=E[c>>12&63],e+=n+1<t?E[c>>6&63]:"",e+=n+2<t?E[c&63]:"";}return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function pe(s){if(!/^[A-Za-z0-9_-]*$/.test(s))throw new Error("Invalid base64url string: contains invalid characters");let e=s.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";let t=e.length,n=e.endsWith("==")?2:e.endsWith("=")?1:0,r=t*3/4-n,i=new Uint8Array(r),o=0;for(let c=0;c<t;c+=4){let l=D[e.charCodeAt(c)],d=D[e.charCodeAt(c+1)],p=D[e.charCodeAt(c+2)],u=D[e.charCodeAt(c+3)],h=l<<18|d<<12|p<<6|u;o<r&&(i[o++]=h>>16&255),o<r&&(i[o++]=h>>8&255),o<r&&(i[o++]=h&255);}return i}function J(s){let e=new TextEncoder;return f(e.encode(s))}function B(s){return new TextDecoder().decode(pe(s))}var E="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",D=new Uint8Array(256);for(let s=0;s<E.length;s++)D[E.charCodeAt(s)]=s;var y={authState:(s,e,t)=>`authrim:${s}:${e}:auth:${t}`,tokens:(s,e)=>`authrim:${s}:${e}:tokens`,idToken:(s,e)=>`authrim:${s}:${e}:id_token`,authStatePrefix:(s,e)=>`authrim:${s}:${e}:auth:`},v=class v{constructor(e,t,n,r){this.crypto=e;this.storage=t;this.issuerHash=n;this.clientIdHash=r;this.cleanupInterval=null;}async generateAuthState(e){let t=e.ttlSeconds??v.DEFAULT_TTL_SECONDS,n;e.returnTo&&(n=this.validateReturnTo(e.returnTo,e.returnToOptions??{policy:"relative_only"}));let r=await this.crypto.randomBytes(v.ENTROPY_BYTES),i=await this.crypto.randomBytes(v.ENTROPY_BYTES),o=await this.crypto.randomBytes(v.OPERATION_ID_BYTES),c=f(r),l=f(i),d=f(o),p=Date.now(),u={state:c,nonce:l,codeVerifier:e.codeVerifier,redirectUri:e.redirectUri,scope:e.scope,createdAt:p,expiresAt:p+t*1e3,returnTo:n,operationId:d},h=y.authState(this.issuerHash,this.clientIdHash,c);return await this.storage.set(h,JSON.stringify(u)),u}validateReturnTo(e,t){switch(t.policy){case "relative_only":if(e.startsWith("/")&&!e.startsWith("//")&&!e.includes(":"))return e;throw new a("invalid_return_to","returnTo must be a relative path (e.g., /dashboard)");case "same_origin":try{let n=typeof globalThis<"u"?globalThis.window:void 0,r=t.currentOrigin??n?.location?.origin;if(!r)throw new a("invalid_return_to","currentOrigin is required for same_origin policy in non-browser environments");if(e.startsWith("/")&&!e.startsWith("//")||new URL(e).origin===r)return e}catch(n){if(n instanceof a)throw n}throw new a("invalid_return_to","returnTo must be same origin or a relative path");case "allowlist":if(!t.allowedOrigins||t.allowedOrigins.length===0)throw new a("invalid_return_to","allowedOrigins is required when using allowlist policy");if(e.startsWith("/")&&!e.startsWith("//"))return e;try{let n=new URL(e);if(t.allowedOrigins.includes(n.origin))return e}catch{}throw new a("invalid_return_to",`returnTo origin not in allowlist: ${t.allowedOrigins.join(", ")}`);default:throw new a("invalid_return_to",`Unknown returnTo policy: ${t.policy}`)}}async validateAndConsumeState(e){let t=y.authState(this.issuerHash,this.clientIdHash,e);try{let n=await this.storage.get(t);if(!n)throw new a("invalid_state","State not found or already used");let r;try{r=JSON.parse(n);}catch{throw new a("invalid_state","Malformed state data")}if(Date.now()>r.expiresAt)throw new a("expired_state","State has expired");return r}finally{await this.storage.remove(t);}}async cleanupExpiredStates(){if(!this.storage.getAll)return;let e=y.authStatePrefix(this.issuerHash,this.clientIdHash),t=await this.storage.getAll(),n=Date.now();for(let[r,i]of Object.entries(t))if(r.startsWith(e))try{let o=JSON.parse(i);n>o.expiresAt&&await this.storage.remove(r);}catch{await this.storage.remove(r);}}startAutoCleanup(e=v.DEFAULT_CLEANUP_INTERVAL_MS){this.stopAutoCleanup(),this.cleanupInterval=setInterval(()=>{this.cleanupExpiredStates().catch(()=>{});},e),this.cleanupExpiredStates().catch(()=>{});}stopAutoCleanup(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null);}async getStoredStateCount(){if(!this.storage.getAll)return -1;let e=y.authStatePrefix(this.issuerHash,this.clientIdHash),t=await this.storage.getAll(),n=0;for(let r of Object.keys(t))r.startsWith(e)&&n++;return n}};v.DEFAULT_TTL_SECONDS=600,v.ENTROPY_BYTES=32,v.OPERATION_ID_BYTES=16,v.DEFAULT_CLEANUP_INTERVAL_MS=3e5;var I=v;function C(s){let e=s.split(".");if(e.length!==3)throw new Error("Invalid JWT format: expected 3 parts");let[t,n,r]=e;try{let i=JSON.parse(B(t)),o=JSON.parse(B(n));return {header:i,payload:o,signature:r}}catch{throw new Error("Invalid JWT format: failed to decode")}}function he(s){return C(s).payload}function Ee(s,e=0){if(s.exp===void 0)return false;let t=Math.floor(Date.now()/1e3);return s.exp+e<t}function Y(s){try{return he(s).nonce}catch{return}}function m(s,e){let t=new TextEncoder,n=t.encode(s),r=t.encode(e),i=n.length,o=r.length,c=Math.max(i,o),l=i^o;for(let d=0;d<c;d++){let p=d<i?n[d]:0,u=d<o?r[d]:0;l|=p^u;}return l===0}var O=class{constructor(e,t){this.http=e;this.clientId=t;}buildAuthorizationUrl(e,t,n,r){if(e.require_pushed_authorization_requests&&!r.usePar)throw new a("par_required","Server requires PAR (Pushed Authorization Request) but usePar option is not enabled");if(e.require_signed_request_object&&!r.useJar)throw new a("jar_required","Server requires JAR (JWT Secured Authorization Request) but useJar option is not enabled");let i=e.authorization_endpoint,o=new URLSearchParams;o.set("client_id",this.clientId),o.set("response_type",r.responseType??"code"),o.set("redirect_uri",r.redirectUri),o.set("state",t.state),o.set("nonce",t.nonce),o.set("code_challenge",n.codeChallenge),o.set("code_challenge_method",n.codeChallengeMethod);let c=r.scope??"openid profile";if(o.set("scope",c),r.prompt&&o.set("prompt",r.prompt),r.loginHint&&o.set("login_hint",r.loginHint),r.acrValues&&o.set("acr_values",r.acrValues),r.extraParams){let p=new Set(["client_id","response_type","redirect_uri","state","nonce","code_challenge","code_challenge_method","scope"]);for(let[u,h]of Object.entries(r.extraParams))p.has(u.toLowerCase())||o.set(u,h);}let d={url:`${i}?${o.toString()}`};return r.exposeState&&(d.state=t.state,d.nonce=t.nonce),d}parseCallback(e){let t;e.includes("?")?t=(e.startsWith("http")?new URL(e):new URL(e,"https://dummy.local")).searchParams:t=new URLSearchParams(e);let n=t.get("error");if(n){let o=t.get("error_description")??"Authorization failed";throw new a("oauth_error",o,{details:{error:n,error_description:o,error_uri:t.get("error_uri")}})}let r=t.get("code"),i=t.get("state");if(!r)throw new a("missing_code","Authorization code not found in callback");if(!i)throw new a("missing_state","State parameter not found in callback");return {code:r,state:i}}async exchangeCode(e,t){let n=e.token_endpoint,r=new URLSearchParams({grant_type:"authorization_code",client_id:this.clientId,code:t.code,redirect_uri:t.redirectUri,code_verifier:t.codeVerifier}),i;try{i=await this.http.fetch(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()});}catch(u){throw new a("network_error","Token request failed",{cause:u instanceof Error?u:void 0})}if(!i.ok){let u=i.data;throw new a("token_error","Token exchange failed",{details:{status:i.status,error:u?.error,error_description:u?.error_description}})}let o=i.data;if(t.scope.split(" ").includes("openid")&&!o.id_token)throw new a("missing_id_token","ID token required when openid scope is requested but was not returned by the server");if(o.id_token){let u=Y(o.id_token);if(u===void 0)throw new a("missing_nonce","ID token nonce claim is missing but was sent in authorization request");if(!m(u,t.nonce))throw new a("nonce_mismatch","ID token nonce does not match expected value")}let l=Math.floor(Date.now()/1e3),d=o.expires_in?l+o.expires_in:l+3600;return {accessToken:o.access_token,tokenType:o.token_type??"Bearer",expiresAt:d,refreshToken:o.refresh_token,idToken:o.id_token,scope:o.scope}}};var L=class{constructor(e,t,n){this.http=e;this.clientId=t;this.options=n;}async pushAuthorizationRequest(e,t){let n=e.pushed_authorization_request_endpoint;if(!n)throw new a("no_par_endpoint","PAR endpoint not available in discovery document");let r=new URLSearchParams;if(r.set("client_id",this.clientId),r.set("response_type",t.responseType??"code"),r.set("redirect_uri",t.redirectUri),r.set("state",t.state),r.set("nonce",t.nonce),r.set("code_challenge",t.codeChallenge),r.set("code_challenge_method",t.codeChallengeMethod),r.set("scope",t.scope??"openid profile"),t.prompt&&r.set("prompt",t.prompt),t.loginHint&&r.set("login_hint",t.loginHint),t.acrValues&&r.set("acr_values",t.acrValues),t.extraParams){let p=new Set(["client_id","response_type","redirect_uri","state","nonce","code_challenge","code_challenge_method","scope"]);for(let[u,h]of Object.entries(t.extraParams))p.has(u.toLowerCase())||r.set(u,h);}let i={"Content-Type":"application/x-www-form-urlencoded",...this.options?.headers},o;try{o=await this.http.fetch(n,{method:"POST",headers:i,body:r.toString()});}catch(p){throw new a("network_error","PAR request failed",{cause:p instanceof Error?p:void 0})}if(!o.ok){let p=o.data;throw new a("par_error","PAR request failed",{details:{status:o.status,error:p?.error,error_description:p?.error_description}})}let c=o.data;if(!c.request_uri)throw new a("par_error","PAR response missing request_uri");if(typeof c.expires_in!="number")throw new a("par_error","PAR response missing or invalid expires_in");let d=Math.floor(Date.now()/1e3)+c.expires_in;return {requestUri:c.request_uri,expiresAt:d}}buildAuthorizationUrlWithPar(e,t){let n=new URLSearchParams;return n.set("client_id",this.clientId),n.set("request_uri",t),`${e.authorization_endpoint}?${n.toString()}`}};var Ce=5,M=class{constructor(e,t){this.http=e;this.clientId=t;}async startDeviceAuthorization(e,t){let n=e.device_authorization_endpoint;if(!n)throw new a("no_device_authorization_endpoint","Device authorization endpoint not available in discovery document");let r=new URLSearchParams({client_id:this.clientId});if(t?.scope&&r.set("scope",t.scope),t?.extraParams){let d=new Set(["client_id","scope"]);for(let[p,u]of Object.entries(t.extraParams))d.has(p.toLowerCase())||r.set(p,u);}let i;try{i=await this.http.fetch(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()});}catch(d){throw new a("network_error","Device authorization request failed",{cause:d instanceof Error?d:void 0})}if(!i.ok){let d=i.data;throw new a("device_authorization_error","Device authorization request failed",{details:{status:i.status,error:d?.error,error_description:d?.error_description}})}let o=i.data;if(!o.device_code||!o.user_code||!o.verification_uri)throw new a("device_authorization_error","Invalid device authorization response: missing required fields");let l=Math.floor(Date.now()/1e3)+o.expires_in;return {deviceCode:o.device_code,userCode:o.user_code,verificationUri:o.verification_uri,verificationUriComplete:o.verification_uri_complete,expiresAt:l,interval:o.interval??Ce}}async pollOnce(e,t){let n=Math.floor(Date.now()/1e3);if(n>=t.expiresAt)return {status:"expired"};let r=e.token_endpoint,i=new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:t.deviceCode,client_id:this.clientId}),o;try{o=await this.http.fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i.toString()});}catch(p){throw new a("network_error","Device flow token request failed",{cause:p instanceof Error?p:void 0})}if(!o.ok){let p=o.data,u=p?.error;switch(u){case "authorization_pending":return {status:"pending",retryAfter:t.interval};case "slow_down":return {status:"slow_down",retryAfter:t.interval+5};case "expired_token":return {status:"expired"};case "access_denied":return {status:"access_denied"};default:throw new a("device_authorization_error","Device flow token request failed",{details:{status:o.status,error:u,error_description:p?.error_description}})}}let c=o.data,l=c.expires_in?n+c.expires_in:n+3600;return {status:"completed",tokens:{accessToken:c.access_token,tokenType:c.token_type??"Bearer",expiresAt:l,refreshToken:c.refresh_token,idToken:c.id_token,scope:c.scope}}}async pollUntilComplete(e,t,n){let r=t.interval;for(;;){if(n?.signal?.aborted)throw new a("device_authorization_error","Device flow polling aborted");let i=await this.pollOnce(e,t);switch(i.status){case "completed":return i.tokens;case "pending":await this.sleep(i.retryAfter*1e3,n?.signal);continue;case "slow_down":r=i.retryAfter,t.interval=r,await this.sleep(r*1e3,n?.signal);continue;case "expired":throw new a("device_authorization_expired","Device authorization has expired. Please start a new authorization.");case "access_denied":throw new a("device_access_denied","User denied the device authorization request")}}}sleep(e,t){return new Promise((n,r)=>{let i=setTimeout(n,e);t&&t.addEventListener("abort",()=>{clearTimeout(i),r(new a("device_authorization_error","Device flow polling aborted"));},{once:true});})}};var H=class{constructor(e,t){this.keyPair=null;this.serverNonce=null;this.crypto=e,this.config=t??{};}async initialize(){if(!this.crypto.generateDPoPKeyPair)throw new a("dpop_key_generation_error","CryptoProvider does not support DPoP key generation");if(this.crypto.getDPoPKeyPair){let e=await this.crypto.getDPoPKeyPair();if(e){this.keyPair=e;return}}try{this.keyPair=await this.crypto.generateDPoPKeyPair(this.config.algorithm??"ES256");}catch(e){throw new a("dpop_key_generation_error","Failed to generate DPoP key pair",{cause:e instanceof Error?e:void 0})}}isInitialized(){return this.keyPair!==null}async generateProof(e,t,n){if(!this.keyPair)throw new a("dpop_proof_generation_error","DPoP manager not initialized. Call initialize() first.");let r=new URL(t),i=`${r.protocol}//${r.host}${r.pathname}`,o={typ:"dpop+jwt",alg:this.keyPair.algorithm,jwk:this.keyPair.publicKeyJwk},c=Math.floor(Date.now()/1e3),l={jti:this.generateJti(),htm:e.toUpperCase(),htu:i,iat:c};n?.accessTokenHash&&(l.ath=n.accessTokenHash),(n?.nonce??this.serverNonce)&&(l.nonce=n?.nonce??this.serverNonce??void 0);try{let d=J(JSON.stringify(o)),p=J(JSON.stringify(l)),u=`${d}.${p}`,h=await this.keyPair.sign(new TextEncoder().encode(u)),g=f(h);return `${u}.${g}`}catch(d){throw new a("dpop_proof_generation_error","Failed to generate DPoP proof",{cause:d instanceof Error?d:void 0})}}handleNonceResponse(e){this.serverNonce=e;}getServerNonce(){return this.serverNonce}clearServerNonce(){this.serverNonce=null;}getPublicKeyJwk(){return this.keyPair?.publicKeyJwk??null}getThumbprint(){return this.keyPair?.thumbprint??null}async calculateAccessTokenHash(e){let t=await this.crypto.sha256(e);return f(t)}async clear(){this.crypto.clearDPoPKeyPair&&await this.crypto.clearDPoPKeyPair(),this.keyPair=null,this.serverNonce=null;}generateJti(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).substring(2,15)}`}};var X={access_token:"urn:ietf:params:oauth:token-type:access_token",refresh_token:"urn:ietf:params:oauth:token-type:refresh_token",id_token:"urn:ietf:params:oauth:token-type:id_token"};var _=class _{constructor(e){this.refreshPromise=null;this.discovery=null;this.expiringTimeout=null;this.isLeaderTab=true;this.currentOperationId=null;this.http=e.http,this.storage=e.storage,this.clientId=e.clientId,this.issuerHash=e.issuerHash,this.clientIdHash=e.clientIdHash,this.refreshSkewSeconds=e.refreshSkewSeconds??_.DEFAULT_REFRESH_SKEW_SECONDS,this.eventEmitter=e.eventEmitter,this.expiringThresholdMs=(e.expiringThresholdSeconds??_.DEFAULT_EXPIRING_THRESHOLD_SECONDS)*1e3,this.expiringJitterMs=e.expiringJitterMs??_.DEFAULT_EXPIRING_JITTER_MS;}setDiscovery(e){this.discovery=e;}get tokenKey(){return y.tokens(this.issuerHash,this.clientIdHash)}get idTokenKey(){return y.idToken(this.issuerHash,this.clientIdHash)}async getTokens(){let e=await this.storage.get(this.tokenKey);if(!e)return null;try{return JSON.parse(e)}catch{return await this.clearTokens(),null}}async saveTokens(e){await this.storage.set(this.tokenKey,JSON.stringify(e)),e.idToken&&await this.storage.set(this.idTokenKey,e.idToken),this.scheduleExpiringEvent(e.expiresAt);}scheduleExpiringEvent(e){if(this.expiringTimeout&&(clearTimeout(this.expiringTimeout),this.expiringTimeout=null),!this.isLeaderTab)return;let t=e*1e3,n=t-this.expiringThresholdMs,r=Math.random()*this.expiringJitterMs*2-this.expiringJitterMs,i=n-Date.now()+r;i>0&&(this.expiringTimeout=setTimeout(()=>{let o=Date.now(),c=Math.max(0,Math.floor((t-o)/1e3));this.eventEmitter?.emit("token:expiring",{expiresAt:e,expiresIn:c,timestamp:o,source:"core"});},i));}setLeaderTab(e){this.isLeaderTab=e,!e&&this.expiringTimeout&&(clearTimeout(this.expiringTimeout),this.expiringTimeout=null);}setOperationId(e){this.currentOperationId=e;}getOperationId(){return this.currentOperationId}async clearTokens(){await this.storage.remove(this.tokenKey),await this.storage.remove(this.idTokenKey);}async getAccessToken(){let e=await this.getTokens();if(!e)throw new a("no_tokens","No tokens available. Please authenticate first.");if(this.shouldRefresh(e)){if(!e.refreshToken)throw new a("token_expired","Access token expired and no refresh token available");return this.refreshWithLock(e.refreshToken)}return e.accessToken}async getIdToken(){return (await this.getTokens())?.idToken??null}shouldRefresh(e){let t=Math.floor(Date.now()/1e3);return e.expiresAt-this.refreshSkewSeconds<=t}async refreshWithLock(e,t="on_demand"){if(this.refreshPromise)return (await this.refreshPromise).accessToken;this.refreshPromise=this.doRefreshWithRetry(e,t);try{return (await this.refreshPromise).accessToken}finally{this.refreshPromise=null;}}async refresh(){let e=await this.getTokens();if(!e?.refreshToken)throw new a("no_tokens","No refresh token available");if(this.refreshPromise)return this.refreshPromise;this.refreshPromise=this.doRefreshWithRetry(e.refreshToken,"manual");try{return await this.refreshPromise}finally{this.refreshPromise=null;}}async doRefreshWithRetry(e,t="on_demand",n=0){let i=Date.now();n===0&&this.eventEmitter?.emit("token:refreshing",{reason:t,timestamp:i,source:"core",operationId:this.currentOperationId??void 0});try{return await this.doRefresh(e)}catch(o){let c=o instanceof a?o:new a("refresh_error","Token refresh failed",{cause:o instanceof Error?o:void 0}),l=n<1&&w(c);if(this.eventEmitter?.emit("token:refresh:failed",{error:c,willRetry:l,attempt:n,timestamp:Date.now(),source:"core",operationId:this.currentOperationId??void 0}),l)return this.doRefreshWithRetry(e,t,n+1);throw w(c)||this.eventEmitter?.emit("auth:required",{reason:"refresh_failed",timestamp:Date.now(),source:"core",operationId:this.currentOperationId??void 0}),o}}async doRefresh(e){if(!this.discovery)throw new a("no_discovery","Discovery document not set");let t=this.discovery.token_endpoint,n=new URLSearchParams({grant_type:"refresh_token",client_id:this.clientId,refresh_token:e}),r;try{r=await this.http.fetch(t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()});}catch(d){let p=new a("network_error","Token refresh request failed",{cause:d instanceof Error?d:void 0});throw this.eventEmitter?.emit("token:error",{error:p,context:"refresh",timestamp:Date.now(),source:"core"}),this.eventEmitter&&A(this.eventEmitter,p,{context:"refresh"}),p}if(!r.ok){let d=r.data,p=new a("refresh_error","Token refresh failed",{details:{status:r.status,error:d?.error,error_description:d?.error_description}});throw this.eventEmitter?.emit("token:error",{error:p,context:"refresh",timestamp:Date.now(),source:"core"}),this.eventEmitter&&A(this.eventEmitter,p,{context:"refresh"}),p}let i=r.data,o=Math.floor(Date.now()/1e3),c=i.expires_in?o+i.expires_in:o+3600,l={accessToken:i.access_token,tokenType:i.token_type??"Bearer",expiresAt:c,refreshToken:i.refresh_token??e,idToken:i.id_token,scope:i.scope};return await this.saveTokens(l),this.eventEmitter?.emit("token:refreshed",{hasAccessToken:!!l.accessToken,hasRefreshToken:!!l.refreshToken,hasIdToken:!!l.idToken,expiresAt:l.expiresAt,timestamp:Date.now(),source:"core",operationId:this.currentOperationId??void 0}),l}async isAuthenticated(){let e=await this.getTokens();if(!e)return false;let t=Math.floor(Date.now()/1e3);return e.expiresAt<=t?!!e.refreshToken:true}async exchangeToken(e){if(!this.discovery)throw new a("no_discovery","Discovery document not set");let t=this.discovery.token_endpoint,n=this.mapTokenTypeToUri(e.subjectTokenType??"access_token"),r=new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",client_id:this.clientId,subject_token:e.subjectToken,subject_token_type:n});e.audience&&r.set("audience",e.audience),e.scope&&r.set("scope",e.scope),e.requestedTokenType&&r.set("requested_token_type",this.mapTokenTypeToUri(e.requestedTokenType)),e.actorToken&&(r.set("actor_token",e.actorToken),e.actorTokenType&&r.set("actor_token_type",this.mapTokenTypeToUri(e.actorTokenType)));let i;try{i=await this.http.fetch(t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()});}catch(u){let h=new a("network_error","Token exchange request failed",{cause:u instanceof Error?u:void 0});throw this.eventEmitter?.emit("token:error",{error:h,context:"exchange",timestamp:Date.now(),source:"core"}),this.eventEmitter&&A(this.eventEmitter,h,{context:"exchange"}),h}if(!i.ok){let u=i.data,h=new a("token_exchange_error","Token exchange failed",{details:{status:i.status,error:u?.error,error_description:u?.error_description}});throw this.eventEmitter?.emit("token:error",{error:h,context:"exchange",timestamp:Date.now(),source:"core"}),this.eventEmitter&&A(this.eventEmitter,h,{context:"exchange"}),h}let o=i.data,c=Math.floor(Date.now()/1e3),l=o.expires_in?c+o.expires_in:c+3600,d={accessToken:o.access_token,tokenType:o.token_type??"Bearer",expiresAt:l,refreshToken:o.refresh_token,idToken:o.id_token,scope:o.scope},p={tokens:d,issuedTokenType:o.issued_token_type};return this.eventEmitter?.emit("token:exchanged",{hasAccessToken:!!d.accessToken,hasRefreshToken:!!d.refreshToken,issuedTokenType:o.issued_token_type,timestamp:Date.now(),source:"core",operationId:this.currentOperationId??void 0}),p}mapTokenTypeToUri(e){return X[e]}destroy(){this.expiringTimeout&&(clearTimeout(this.expiringTimeout),this.expiringTimeout=null);}};_.DEFAULT_REFRESH_SKEW_SECONDS=30,_.DEFAULT_EXPIRING_THRESHOLD_SECONDS=300,_.DEFAULT_EXPIRING_JITTER_MS=3e4;var U=_;var j=class{constructor(e){this.http=e.http,this.clientId=e.clientId;}async introspect(e,t){let n=e.introspection_endpoint;if(!n)throw new a("no_introspection_endpoint","Authorization server does not support token introspection");return this.introspectWithEndpoint(n,t)}async introspectWithEndpoint(e,t){let n=new URLSearchParams({client_id:this.clientId,token:t.token});t.tokenTypeHint&&n.set("token_type_hint",t.tokenTypeHint);let r;try{r=await this.http.fetch(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()});}catch(i){throw new a("network_error","Token introspection request failed",{cause:i instanceof Error?i:void 0})}if(!r.ok){let i=r.data;throw new a("introspection_error","Token introspection failed",{details:{status:r.status,error:i?.error,error_description:i?.error_description}})}return r.data}async isActive(e,t){return (await this.introspect(e,{token:t})).active}};var k=class{constructor(e){this.http=e.http,this.clientId=e.clientId;}async revoke(e,t){let n=e.revocation_endpoint;if(!n)throw new a("no_revocation_endpoint","Authorization server does not support token revocation");let r=new URLSearchParams({client_id:this.clientId,token:t.token});t.tokenTypeHint&&r.set("token_type_hint",t.tokenTypeHint);let i;try{i=await this.http.fetch(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()});}catch(c){throw new a("network_error","Token revocation request failed",{cause:c instanceof Error?c:void 0})}if(i.ok)return;let o=i.data;throw new a("revocation_error","Token revocation failed",{details:{status:i.status,error:o?.error,error_description:o?.error_description}})}async revokeWithEndpoint(e,t){let n=new URLSearchParams({client_id:this.clientId,token:t.token});t.tokenTypeHint&&n.set("token_type_hint",t.tokenTypeHint);let r;try{r=await this.http.fetch(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()});}catch(o){throw new a("network_error","Token revocation request failed",{cause:o instanceof Error?o:void 0})}if(r.ok)return;let i=r.data;throw new a("revocation_error","Token revocation failed",{details:{status:r.status,error:i?.error,error_description:i?.error_description}})}};var q=class{constructor(e){this.storage=e.storage,this.clientId=e.clientId,this.issuerHash=e.issuerHash,this.clientIdHash=e.clientIdHash,this.eventEmitter=e.eventEmitter,this.endpoints=e.endpoints,this.tokenRevoker=new k({http:e.http,clientId:e.clientId});}async logout(e,t){let n=await this.getStoredIdToken(),r=await this.getStoredTokens(),i;t?.revokeTokens&&e?.revocation_endpoint&&r&&(i=await this.revokeTokens(e,r)),await this.clearTokens(),this.eventEmitter?.emit("session:ended",{reason:"logout",timestamp:Date.now(),source:"core"});let o;if(this.endpoints?.endSession!==void 0?o=this.endpoints.endSession:e&&(o=e.end_session_endpoint),!o)return {localOnly:true,revocation:i};let c=t?.idTokenHint??n,l=new URLSearchParams({client_id:this.clientId});return c&&l.set("id_token_hint",c),t?.postLogoutRedirectUri&&l.set("post_logout_redirect_uri",t.postLogoutRedirectUri),t?.state&&l.set("state",t.state),{logoutUrl:`${o}?${l.toString()}`,localOnly:false,revocation:i}}async revokeTokens(e,t){let n={attempted:true};try{t.refreshToken&&(await this.tokenRevoker.revoke(e,{token:t.refreshToken,tokenTypeHint:"refresh_token"}),n.refreshTokenRevoked=!0),await this.tokenRevoker.revoke(e,{token:t.accessToken,tokenTypeHint:"access_token"}),n.accessTokenRevoked=!0;}catch(r){n.error=r instanceof Error?r:new Error(String(r));}return n}async clearTokens(){let e=y.tokens(this.issuerHash,this.clientIdHash),t=y.idToken(this.issuerHash,this.clientIdHash);await this.storage.remove(e),await this.storage.remove(t);}async getStoredIdToken(){let e=y.idToken(this.issuerHash,this.clientIdHash);return this.storage.get(e)}async getStoredTokens(){let e=y.tokens(this.issuerHash,this.clientIdHash),t=await this.storage.get(e);if(!t)return null;try{return JSON.parse(t)}catch{return null}}};var z=class{constructor(e){this.http=e.http;}async checkSession(e,t){let n=e.userinfo_endpoint;if(!n)return {valid:false,error:new a("no_userinfo_endpoint","UserInfo endpoint not available")};try{let r=await this.http.fetch(n,{method:"GET",headers:{Authorization:`Bearer ${t}`}});return r.ok?{valid:!0,user:r.data}:r.status===401?{valid:!1,error:new a("session_expired","Session has expired")}:{valid:!1,error:new a("session_check_failed","Session check failed",{details:{status:r.status}})}}catch(r){return {valid:false,error:new a("network_error","Failed to check session",{cause:r instanceof Error?r:void 0})}}}async getUserInfo(e,t){let n=e.userinfo_endpoint;if(!n)throw new a("no_userinfo_endpoint","UserInfo endpoint not available");let r;try{r=await this.http.fetch(n,{method:"GET",headers:{Authorization:`Bearer ${t}`}});}catch(i){throw new a("network_error","Failed to fetch user info",{cause:i instanceof Error?i:void 0})}if(!r.ok)throw new a("userinfo_error","Failed to get user info",{details:{status:r.status}});return r.data}};var N=class{constructor(e){this.discovery=null;this.tokenManager=e.tokenManager,this.tokenApiClient=e.tokenApiClient;}setDiscovery(e){this.discovery=e;}async isAuthenticated(){return this.tokenManager.isAuthenticated()}async checkSession(){if(!this.discovery)return {valid:false,error:new a("no_discovery","Discovery document not available")};try{let e=await this.tokenManager.getAccessToken();return this.tokenApiClient.checkSession(this.discovery,e)}catch(e){return e instanceof a?{valid:false,error:e}:{valid:false,error:new a("session_check_failed","Failed to check session",{cause:e instanceof Error?e:void 0})}}}async getUser(){if(!this.discovery)throw new a("no_discovery","Discovery document not available");let e=await this.tokenManager.getAccessToken();return this.tokenApiClient.getUserInfo(this.discovery,e)}};async function fe(s,e,t=16){let n=await s.sha256(e);return f(n).slice(0,t)}var K=class{constructor(e){this.dpopManager=null;this.initialized=false;this.config=W(e),this.normalizedIssuer=T(e.issuer),this.events=new S,this.discoveryClient=new x({http:this.config.http,cacheTtlMs:this.config.discoveryCacheTtlMs}),this.pkce=new P(this.config.crypto),this.authCodeFlow=new O(this.config.http,this.config.clientId),this.parClient=new L(this.config.http,this.config.clientId),this.deviceFlowClient=new M(this.config.http,this.config.clientId);}get eventEmitter(){return this.events}async initialize(){if(this.initialized)return;let e=this.config.hashOptions.hashLength;this.issuerHash=await fe(this.config.crypto,this.normalizedIssuer,e),this.clientIdHash=await fe(this.config.crypto,this.config.clientId,e),this.stateManager=new I(this.config.crypto,this.config.storage,this.issuerHash,this.clientIdHash),this.tokenManager=new U({http:this.config.http,storage:this.config.storage,clientId:this.config.clientId,issuerHash:this.issuerHash,clientIdHash:this.clientIdHash,refreshSkewSeconds:this.config.refreshSkewSeconds,eventEmitter:this.events}),this.logoutHandler=new q({storage:this.config.storage,http:this.config.http,clientId:this.config.clientId,issuerHash:this.issuerHash,clientIdHash:this.clientIdHash,eventEmitter:this.events,endpoints:this.config.endpoints}),this.tokenIntrospector=new j({http:this.config.http,clientId:this.config.clientId}),this.tokenRevoker=new k({http:this.config.http,clientId:this.config.clientId});let t=new z({http:this.config.http});this.sessionManager=new N({tokenManager:this.tokenManager,tokenApiClient:t}),await this.stateManager.cleanupExpiredStates(),this.initialized=true;}ensureInitialized(){if(!this.initialized)throw new a("not_initialized","Client not initialized. Use createAuthrimClient().")}async discover(){let e=await this.discoveryClient.discover(this.normalizedIssuer);return this.tokenManager.setDiscovery(e),this.sessionManager.setDiscovery(e),e}async buildAuthorizationUrl(e){this.ensureInitialized();let t=await this.discover(),n=await this.pkce.generatePKCE(),r=e.scope??"openid profile",i=await this.stateManager.generateAuthState({redirectUri:e.redirectUri,codeVerifier:n.codeVerifier,scope:r,ttlSeconds:this.config.stateTtlSeconds}),o=this.authCodeFlow.buildAuthorizationUrl(t,i,n,e);return this.events.emit("auth:redirecting",{url:o.url,timestamp:Date.now(),source:"core",operationId:i.operationId}),o}async handleCallback(e){this.ensureInitialized();let{code:t,state:n}=this.authCodeFlow.parseCallback(e),r=await this.stateManager.validateAndConsumeState(n),i=r.operationId;this.events.emit("auth:callback",{code:t,state:n,timestamp:Date.now(),source:"core",operationId:i}),this.events.emit("auth:callback:processing",{state:n,timestamp:Date.now(),source:"core",operationId:i});try{let o=await this.discover(),c=await this.authCodeFlow.exchangeCode(o,{code:t,state:n,redirectUri:r.redirectUri,codeVerifier:r.codeVerifier,nonce:r.nonce,scope:r.scope});return await this.tokenManager.saveTokens(c),this.events.emit("auth:callback:complete",{success:!0,timestamp:Date.now(),source:"core",operationId:i}),c}catch(o){throw this.events.emit("auth:callback:complete",{success:false,timestamp:Date.now(),source:"core",operationId:i}),o}}get par(){return {push:async e=>{this.ensureInitialized();let t=await this.discover(),n=await this.pkce.generatePKCE(),r=e.scope??"openid profile",i=await this.stateManager.generateAuthState({redirectUri:e.redirectUri,codeVerifier:n.codeVerifier,scope:r,ttlSeconds:this.config.stateTtlSeconds});return this.parClient.pushAuthorizationRequest(t,{redirectUri:e.redirectUri,scope:r,state:i.state,nonce:i.nonce,codeChallenge:n.codeChallenge,codeChallengeMethod:"S256",prompt:e.prompt,loginHint:e.loginHint,acrValues:e.acrValues,extraParams:e.extraParams})},buildAuthorizationUrl:async e=>{let t=await this.discover();return this.parClient.buildAuthorizationUrlWithPar(t,e)},isAvailable:async()=>!!(await this.discover()).pushed_authorization_request_endpoint,isRequired:async()=>(await this.discover()).require_pushed_authorization_requests===true}}get deviceFlow(){return {start:async e=>{this.ensureInitialized();let t=await this.discover();return this.deviceFlowClient.startDeviceAuthorization(t,e)},pollOnce:async e=>{let t=await this.discover();return this.deviceFlowClient.pollOnce(t,e)},pollUntilComplete:async(e,t)=>{let n=await this.discover(),r=await this.deviceFlowClient.pollUntilComplete(n,e,t);return await this.tokenManager.saveTokens(r),r},isAvailable:async()=>!!(await this.discover()).device_authorization_endpoint}}get dpop(){if(!this.config.crypto.generateDPoPKeyPair)return;this.dpopManager||(this.dpopManager=new H(this.config.crypto));let t=this.dpopManager;return {initialize:()=>t.initialize(),isInitialized:()=>t.isInitialized(),generateProof:(n,r,i)=>t.generateProof(n,r,i),handleNonceResponse:n=>t.handleNonceResponse(n),calculateAccessTokenHash:n=>t.calculateAccessTokenHash(n),getPublicKeyJwk:()=>t.getPublicKeyJwk(),getThumbprint:()=>t.getThumbprint(),clear:()=>t.clear(),isServerSupported:async()=>{let n=await this.discover();return Array.isArray(n.dpop_signing_alg_values_supported)&&n.dpop_signing_alg_values_supported.length>0}}}get token(){return this.ensureInitialized(),{getAccessToken:()=>this.tokenManager.getAccessToken(),getTokens:()=>this.tokenManager.getTokens(),getIdToken:()=>this.tokenManager.getIdToken(),isAuthenticated:()=>this.tokenManager.isAuthenticated(),exchange:async e=>(await this.discover(),this.tokenManager.exchangeToken(e)),introspect:async e=>{let t=await this.discover();return this.tokenIntrospector.introspect(t,e)},revoke:async e=>{let t=await this.discover();return this.tokenRevoker.revoke(t,e)}}}get session(){return this.ensureInitialized(),{isAuthenticated:()=>this.sessionManager.isAuthenticated(),check:()=>this.sessionManager.checkSession()}}async isAuthenticated(){return this.ensureInitialized(),this.tokenManager.isAuthenticated()}async getUser(){return this.ensureInitialized(),this.sessionManager.getUser()}async logout(e){this.ensureInitialized();let t=null;try{t=await this.discover();}catch{}return this.logoutHandler.logout(t,e)}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}off(e,t){this.events.off(e,t);}};async function Re(s){let e=new K(s);return await e.initialize(),e}var me=new Set(["login_required","interaction_required","consent_required","account_selection_required"]),Z=class{constructor(e){this.clientId=e;}buildSilentAuthUrl(e,t,n,r){let i=e.authorization_endpoint,o=new URLSearchParams;o.set("client_id",this.clientId),o.set("response_type",r.responseType??"code"),o.set("redirect_uri",r.redirectUri),o.set("state",t.state),o.set("nonce",t.nonce),o.set("prompt","none"),o.set("code_challenge",n.codeChallenge),o.set("code_challenge_method",n.codeChallengeMethod);let c=r.scope??"openid";if(o.set("scope",c),r.loginHint&&o.set("login_hint",r.loginHint),r.idTokenHint&&o.set("id_token_hint",r.idTokenHint),r.extraParams){let p=new Set(["client_id","response_type","redirect_uri","state","nonce","code_challenge","code_challenge_method","scope","prompt"]);for(let[u,h]of Object.entries(r.extraParams))p.has(u.toLowerCase())||o.set(u,h);}let d={url:`${i}?${o.toString()}`};return r.exposeState&&(d.state=t.state,d.nonce=t.nonce),d}parseSilentAuthResponse(e){let t;e.includes("?")?t=(e.startsWith("http")?new URL(e):new URL(e,"https://dummy.local")).searchParams:t=new URLSearchParams(e);let n=t.get("error");if(n){let o=t.get("error_description"),c=this.mapSilentAuthError(n);return {success:false,error:new a(c,o??this.getDefaultErrorMessage(n),{details:{error:n,error_description:o,error_uri:t.get("error_uri")}})}}let r=t.get("code"),i=t.get("state");return r?i?{success:true,code:r,state:i}:{success:false,error:new a("missing_state","State parameter not found in silent auth response")}:{success:false,error:new a("missing_code","Authorization code not found in silent auth response")}}isInteractiveLoginRequired(e){return me.has(e.code)}mapSilentAuthError(e){return me.has(e)?e:"oauth_error"}getDefaultErrorMessage(e){switch(e){case "login_required":return "User must log in - no active session found";case "interaction_required":return "User interaction required";case "consent_required":return "User consent required";case "account_selection_required":return "User must select an account";default:return "Silent authentication failed"}}};async function Q(s,e,t){let n={},r={};switch(s.method){case "client_secret_basic":{let i=btoa(`${e}:${s.clientSecret}`);n.Authorization=`Basic ${i}`;break}case "client_secret_post":{r.client_id=e,r.client_secret=s.clientSecret;break}case "private_key_jwt":{let i=Math.floor(Date.now()/1e3),o={iss:e,sub:e,aud:t,jti:be(),exp:i+300,iat:i},c;try{c=await s.signJwt(o);}catch(l){throw new a("invalid_client_authentication","Failed to sign client assertion JWT",{cause:l instanceof Error?l:void 0})}r.client_id=e,r.client_assertion_type="urn:ietf:params:oauth:client-assertion-type:jwt-bearer",r.client_assertion=c;break}case "none":{if(!("dangerouslyAllowInsecure"in s)||s.dangerouslyAllowInsecure!==true)throw new a("insecure_client_auth",'Client authentication method "none" requires dangerouslyAllowInsecure: true');r.client_id=e;break}default:{let i=s;throw new a("invalid_client_authentication",`Unknown client authentication method: ${i.method}`)}}return {headers:n,bodyParams:r}}function be(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).substring(2,15)}`}var ee=class{constructor(e){this.http=e.http,this.clientId=e.clientId,this.credentials=e.credentials;}async getToken(e,t){let n=e.token_endpoint,{headers:r,bodyParams:i}=await Q(this.credentials,this.clientId,n),o=new URLSearchParams({grant_type:"client_credentials",...i});if(t?.scope&&o.set("scope",t.scope),t?.audience&&o.set("audience",t.audience),t?.extraParams){let g=new Set(["grant_type","client_id","client_secret","client_assertion","client_assertion_type","scope","audience"]);for(let[b,we]of Object.entries(t.extraParams))g.has(b.toLowerCase())||o.set(b,we);}let c={"Content-Type":"application/x-www-form-urlencoded",...r},l;try{l=await this.http.fetch(n,{method:"POST",headers:c,body:o.toString()});}catch(g){throw new a("network_error","Client credentials token request failed",{cause:g instanceof Error?g:void 0})}if(!l.ok){let g=l.data;throw new a("client_credentials_error","Client credentials token request failed",{details:{status:l.status,error:g?.error,error_description:g?.error_description}})}let d=l.data,p=Math.floor(Date.now()/1e3),u=d.expires_in?p+d.expires_in:p+3600;return {accessToken:d.access_token,tokenType:d.token_type??"Bearer",expiresAt:u,refreshToken:d.refresh_token,scope:d.scope}}};var te=class{constructor(e){this.config=e;}async buildRequestObject(e){let t=Math.floor(Date.now()/1e3),n=this.config.lifetime??300,r={alg:this.config.algorithm??"RS256",typ:"oauth-authz-req+jwt"};this.config.keyId&&(r.kid=this.config.keyId);let i={iss:e.clientId,aud:e.issuer,response_type:e.responseType??"code",client_id:e.clientId,redirect_uri:e.redirectUri,scope:e.scope,state:e.state,nonce:e.nonce,code_challenge:e.codeChallenge,code_challenge_method:e.codeChallengeMethod,iat:t,exp:t+n,jti:this.generateJti()};if(e.prompt&&(i.prompt=e.prompt),e.loginHint&&(i.login_hint=e.loginHint),e.acrValues&&(i.acr_values=e.acrValues),e.extraClaims){let o=new Set(["iss","aud","response_type","client_id","redirect_uri","scope","state","nonce","code_challenge","code_challenge_method","iat","exp","jti","nbf"]);for(let[c,l]of Object.entries(e.extraClaims))o.has(c)||(i[c]=l);}try{return await this.config.signJwt(r,i)}catch(o){throw new a("jar_signing_error","Failed to sign JAR request object",{cause:o instanceof Error?o:void 0})}}generateJti(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).substring(2,15)}`}};function xe(s){return s.require_signed_request_object===true}var re=class{constructor(e){this.config=e;}async validateResponse(e,t,n){let r=n.clockSkewSeconds??60,i;try{i=await this.config.verifyJwt(t,e.issuer);}catch(l){throw new a("jarm_signature_invalid","Failed to verify JARM response signature",{cause:l instanceof Error?l:void 0})}if(i.iss!==e.issuer)throw new a("jarm_validation_error","JARM response issuer does not match discovery issuer",{details:{expected:e.issuer,actual:i.iss}});if(!(Array.isArray(i.aud)?i.aud:[i.aud]).includes(n.clientId))throw new a("jarm_validation_error","JARM response audience does not match client_id",{details:{expected:n.clientId,actual:i.aud}});let c=Math.floor(Date.now()/1e3);if(i.exp&&i.exp+r<c)throw new a("jarm_validation_error","JARM response has expired");if(i.iat&&i.iat-r>c)throw new a("jarm_validation_error","JARM response iat is in the future");if(i.error)throw new a("oauth_error",i.error_description??i.error,{details:{error:i.error,error_description:i.error_description,error_uri:i.error_uri}});if(!i.state)throw new a("jarm_validation_error","JARM response is missing state claim");if(!m(i.state,n.expectedState))throw new a("jarm_validation_error","JARM response state does not match expected state");if(!i.code)throw new a("jarm_validation_error","JARM response is missing authorization code");return {code:i.code,state:i.state}}static extractResponseFromCallback(e){let t;return e.includes("?")?t=(e.startsWith("http")?new URL(e):new URL(e,"https://dummy.local")).searchParams:t=new URLSearchParams(e),t.get("response")}};var R=class R{constructor(e){this.tokenManager=null;this.checkInterval=null;this.abortController=null;this.isRunning=false;this.options={thresholdSeconds:e?.thresholdSeconds??R.DEFAULT_THRESHOLD_SECONDS,checkIntervalMs:e?.checkIntervalMs??R.DEFAULT_CHECK_INTERVAL_MS,eventEmitter:e?.eventEmitter};}start(e){this.isRunning||(this.tokenManager=e,this.abortController=new AbortController,this.isRunning=true,this.checkInterval=setInterval(()=>{this.checkAndRefresh().catch(()=>{});},this.options.checkIntervalMs),this.checkAndRefresh().catch(()=>{}));}stop(){this.isRunning&&(this.isRunning=false,this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=null),this.abortController&&(this.abortController.abort(),this.abortController=null),this.tokenManager=null);}get running(){return this.isRunning}get signal(){return this.abortController?.signal??null}async checkAndRefresh(){if(!(!this.tokenManager||!this.isRunning))try{let e=await this.tokenManager.getTokens();if(!e)return;let t=Math.floor(Date.now()/1e3);e.expiresAt-t<=this.options.thresholdSeconds&&e.refreshToken&&await this.tokenManager.refresh();}catch{}}async forceCheck(){await this.checkAndRefresh();}};R.DEFAULT_THRESHOLD_SECONDS=60,R.DEFAULT_CHECK_INTERVAL_MS=3e4;var ne=R;var ie=class{constructor(e){this.crypto=e.crypto;}async calculate(e){let t=e.salt;if(!t){let c=await this.crypto.randomBytes(16);t=f(c);}let n=e.clientId+" "+e.origin+" "+e.opBrowserState+t,r=await this.crypto.sha256(n),i=f(r);return {sessionState:i+"."+t,hash:i,salt:t}}async validate(e,t){let n=this.parse(e);if(!n)return false;let r=await this.calculate({...t,salt:n.salt});return m(r.sessionState,e)}parse(e){if(!e||typeof e!="string"||e.length>512)return null;let i=e.lastIndexOf(".");if(i===-1||i===0||i===e.length-1)return null;let o=e.substring(0,i),c=e.substring(i+1);if(!o||!c||o.length>256||c.length>128)return null;let l=/^[A-Za-z0-9_-]+$/;return !l.test(o)||!l.test(c)?null:{hash:o,salt:c}}};var oe=class{build(e,t){let n=new URL(e.logoutUri),r={};return e.includeIssuer&&t.iss&&(n.searchParams.set("iss",t.iss),r.iss=t.iss),e.includeSessionId&&t.sid&&(n.searchParams.set("sid",t.sid),r.sid=t.sid),{url:n.toString(),params:r}}parseParams(e){let t=typeof e=="string"?new URL(e):e,n={},r=t.searchParams.get("iss");r&&(n.iss=r);let i=t.searchParams.get("sid");return i&&(n.sid=i),n}validateRequest(e,t={}){let n;try{n=this.parseParams(e);}catch{return {valid:false,error:"Invalid URL format"}}return t.requireIss&&!n.iss?{valid:false,error:"Missing required iss parameter"}:t.requireSid&&!n.sid?{valid:false,error:"Missing required sid parameter"}:t.issuer&&n.iss&&!m(n.iss,t.issuer)?{valid:false,error:"Issuer validation failed"}:t.sessionId&&n.sid&&!m(n.sid,t.sessionId)?{valid:false,error:"Session ID validation failed"}:{valid:true,params:n}}};var se="http://schemas.openid.net/event/backchannel-logout",ae=class{validate(e,t){let n,r;try{let u=C(e);n=u.header,r=u.payload;}catch{return {valid:false,error:"Invalid JWT format",errorCode:"invalid_format"}}if(!r.iss||!m(r.iss,t.issuer))return {valid:false,error:"Issuer validation failed",errorCode:"invalid_issuer"};if(!(Array.isArray(r.aud)?r.aud:[r.aud]).some(u=>m(u,t.audience)))return {valid:false,error:"Audience validation failed",errorCode:"invalid_audience"};if(!r.events||typeof r.events!="object")return {valid:false,error:"Missing or invalid events claim",errorCode:"invalid_events"};let c=r.events[se];if(c===void 0)return {valid:false,error:`Missing ${se} in events claim`,errorCode:"invalid_events"};if(typeof c!="object"||c===null||Object.keys(c).length!==0)return {valid:false,error:"Back-channel logout event must be an empty object",errorCode:"invalid_events"};if(!r.jti)return {valid:false,error:"Missing jti claim",errorCode:"missing_jti"};if(!r.sub&&!r.sid)return {valid:false,error:"Logout token must contain either sub or sid (or both)",errorCode:"missing_sub_and_sid"};if("nonce"in r&&r.nonce!==void 0)return {valid:false,error:"Logout token must not contain nonce claim",errorCode:"nonce_present"};let l=Math.floor(Date.now()/1e3),d=t.maxAge??60,p=t.clockSkew??30;return r.iat&&l-r.iat>d+p?{valid:false,error:`Token too old: iat ${r.iat} is more than ${d} seconds ago`,errorCode:"expired"}:r.iat&&r.iat>l+p?{valid:false,error:`Token iat is in the future: ${r.iat}`,errorCode:"not_yet_valid"}:t.expectedSub&&r.sub&&!m(r.sub,t.expectedSub)?{valid:false,error:"Subject validation failed",errorCode:"sub_mismatch"}:t.expectedSid&&r.sid&&!m(r.sid,t.expectedSid)?{valid:false,error:"Session ID validation failed",errorCode:"sid_mismatch"}:{valid:true,claims:r,header:n}}extractClaims(e){try{return C(e).payload}catch{return null}}extractHeader(e){try{return C(e).header}catch{return null}}};var Se=["accessToken","refreshToken","idToken","token","code","password","secret","credentials","authorization","bearer","codeVerifier","code_verifier","client_secret"],ye=["code","state","nonce","id_token","access_token","refresh_token","token"],V=class{constructor(e){this.entries=[];this.maxEvents=e?.maxEvents??100,this.redactLevel=e?.redactLevel??"default";}record(e,t,n){let r=n?.redact??this.redactLevel,i=this.redactData(t,r),o={type:e,timestamp:Date.now(),operationId:n?.operationId,data:i};for(this.entries.push(o);this.entries.length>this.maxEvents;)this.entries.shift();}getRecent(e){return e===void 0?[...this.entries]:this.entries.slice(-e)}getByOperationId(e){return this.entries.filter(t=>t.operationId===e)}getByType(e){return this.entries.filter(t=>t.type===e)}clear(){this.entries=[];}get length(){return this.entries.length}toJSON(){return JSON.stringify(this.entries,null,2)}setRedactLevel(e){this.redactLevel=e;}redactData(e,t){return t==="none"||e===void 0||e===null||typeof e!="object"?e:this.deepRedact(e,t)}deepRedact(e,t){let n={};for(let[r,i]of Object.entries(e)){let o=r.toLowerCase();if(this.isSensitiveKey(o)){let c=r.charAt(0).toUpperCase()+r.slice(1);n[`has${c}`]=i!=null,n[r]="[REDACTED]";continue}if(t==="aggressive"&&o==="url"&&typeof i=="string"){n[r]=this.redactUrl(i);continue}if(i!==null&&typeof i=="object"&&!Array.isArray(i)){n[r]=this.deepRedact(i,t);continue}if(Array.isArray(i)){n[r]=i.map(c=>c!==null&&typeof c=="object"?this.deepRedact(c,t):c);continue}n[r]=i;}return n}isSensitiveKey(e){return Se.some(t=>e===t.toLowerCase()||e.includes(t.toLowerCase()))}redactUrl(e){try{let t=new URL(e);for(let n of ye)t.searchParams.has(n)&&t.searchParams.set(n,"[REDACTED]");if(t.hash){let n=new URLSearchParams(t.hash.slice(1)),r=!1;for(let i of ye)n.has(i)&&(n.set(i,"[REDACTED]"),r=!0);r&&(t.hash="#"+n.toString());}return t.toString()}catch{return e.replace(/([?&])(code|token|state|nonce)=[^&]*/gi,"$1$2=[REDACTED]")}}};function ce(s){let e=s?.timestamps??false;return {log(t,n,r){let i=e?`[Authrim:${t.toUpperCase()} ${new Date().toISOString()}]`:`[Authrim:${t.toUpperCase()}]`,o=t==="debug"?"log":t,c=typeof console<"u"?console:null;c&&(r!==void 0?c[o]?.(i,n,r):c[o]?.(i,n));}}}var le={log(){}};function ge(s){return s.enabled?s.logger?s.logger:ce({timestamps:s.logTimestamps}):le}var $=class{constructor(e,t){this.operationId=null;this.logger=e,this.verbose=t?.verbose??false;}setOperationId(e){this.operationId=e;}getOperationId(){return this.operationId}debug(e,t){this.verbose&&this.logger.log("debug",this.formatMessage(e),t);}info(e,t){this.logger.log("info",this.formatMessage(e),t);}warn(e,t){this.logger.log("warn",this.formatMessage(e),t);}error(e,t){this.logger.log("error",this.formatMessage(e),t);}formatMessage(e){return this.operationId?`[${this.operationId.slice(0,8)}] ${e}`:e}};async function Pe(s,e){let t=await e.sha256(s),n=t.slice(0,t.length/2);return f(n)}function De(s,e){return new Promise((t,n)=>{let r=new a("operation_cancelled","Operation was cancelled");if(e.aborted){n(r);return}let i=()=>{n(r);};e.addEventListener("abort",i,{once:true}),s.then(t).catch(n).finally(()=>{e.removeEventListener("abort",i);});})}function Ie(s){let e=new AbortController;return {promise:s(e.signal),cancel:()=>e.abort(),signal:e.signal}}function de(s){return s instanceof a&&s.code==="operation_cancelled"}async function Oe(s){try{let e=await Promise.race(s.map(t=>t.promise));return s.forEach(t=>t.cancel()),e}catch(e){throw s.forEach(t=>t.cancel()),e}}var Le={maxRetries:3,baseDelayMs:1e3,maxDelayMs:3e4,jitter:true};function ve(s,e,t,n){let r=e*Math.pow(2,s),i=Math.min(r,t);if(n){let o=i*.5,c=Math.random()*o-o/2;return Math.max(0,Math.floor(i+c))}return i}function _e(s,e){return new Promise((t,n)=>{if(e?.aborted){n(new a("operation_cancelled","Sleep was cancelled"));return}let r=setTimeout(t,s);if(e){let i=()=>{clearTimeout(r),n(new a("operation_cancelled","Sleep was cancelled"));};e.addEventListener("abort",i,{once:true});}})}async function ke(s,e){let t={...Le,...e},{maxRetries:n,baseDelayMs:r,maxDelayMs:i,jitter:o,signal:c,shouldRetry:l,onRetry:d}=t,p;for(let u=0;u<=n;u++)try{if(c?.aborted)throw new a("operation_cancelled","Operation was cancelled");return await s()}catch(h){if(p=h,de(h))throw h;let g=l?l(h,u):h instanceof a&&w(h);if(u>=n||!g)throw h;let b=ve(u,r,i,o);d?.(h,u+1,b),await _e(b,c);}throw p}function Me(s){return (e,t)=>ke(e,{...s,...t})}function He(s){let e=s instanceof Headers?s.get("retry-after"):s["retry-after"]??s["Retry-After"];if(!e)return null;let t=parseInt(e,10);if(!isNaN(t))return t*1e3;let n=new Date(e);if(!isNaN(n.getTime())){let r=n.getTime()-Date.now();return Math.max(0,r)}return null}
|
|
2
|
+
exports.AuthorizationCodeFlow=O;exports.AuthrimClient=K;exports.AuthrimError=a;exports.AutoRefreshScheduler=ne;exports.BACKCHANNEL_LOGOUT_EVENT=se;exports.BackChannelLogoutValidator=ae;exports.ClientCredentialsClient=ee;exports.DPoPManager=H;exports.DebugContext=$;exports.DeviceFlowClient=M;exports.DiscoveryClient=x;exports.EventEmitter=S;exports.EventTimeline=V;exports.FrontChannelLogoutUrlBuilder=oe;exports.JARBuilder=te;exports.JARMValidator=re;exports.LogoutHandler=q;exports.PARClient=L;exports.PKCEHelper=P;exports.STORAGE_KEYS=y;exports.SessionManager=N;exports.SessionStateCalculator=ie;exports.SilentAuthHandler=Z;exports.StateManager=I;exports.TOKEN_TYPE_URIS=X;exports.TokenApiClient=z;exports.TokenIntrospector=j;exports.TokenManager=U;exports.TokenRevoker=k;exports.base64urlDecode=pe;exports.base64urlEncode=f;exports.base64urlToString=B;exports.buildClientAuthentication=Q;exports.calculateBackoffDelay=ve;exports.calculateDsHash=Pe;exports.classifyError=G;exports.createAuthrimClient=Re;exports.createCancellableOperation=Ie;exports.createConsoleLogger=ce;exports.createDebugLogger=ge;exports.createRetryFunction=Me;exports.decodeIdToken=he;exports.decodeJwt=C;exports.emitClassifiedError=A;exports.getErrorMeta=ue;exports.getIdTokenNonce=Y;exports.isCancellationError=de;exports.isJarRequired=xe;exports.isJwtExpired=Ee;exports.isRetryableError=w;exports.noopLogger=le;exports.normalizeIssuer=T;exports.parseRetryAfterHeader=He;exports.raceWithCancellation=Oe;exports.resolveConfig=W;exports.sleep=_e;exports.stringToBase64url=J;exports.timingSafeEqual=m;exports.withAbortSignal=De;exports.withRetry=ke;//# sourceMappingURL=index.cjs.map
|
|
3
3
|
//# sourceMappingURL=index.cjs.map
|